xref: /src/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1909545a8SDimitry Andric //===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
2909545a8SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6909545a8SDimitry Andric //
7909545a8SDimitry Andric //===----------------------------------------------------------------------===//
8909545a8SDimitry Andric ///
9909545a8SDimitry Andric /// \file
10eb11fae6SDimitry Andric /// Fix bitcasted functions.
11909545a8SDimitry Andric ///
12909545a8SDimitry Andric /// WebAssembly requires caller and callee signatures to match, however in LLVM,
13909545a8SDimitry Andric /// some amount of slop is vaguely permitted. Detect mismatch by looking for
14909545a8SDimitry Andric /// bitcasts of functions and rewrite them to use wrapper functions instead.
15909545a8SDimitry Andric ///
16909545a8SDimitry Andric /// This doesn't catch all cases, such as when a function's address is taken in
17909545a8SDimitry Andric /// one place and casted in another, but it works for many common cases.
18909545a8SDimitry Andric ///
19909545a8SDimitry Andric /// Note that LLVM already optimizes away function bitcasts in common cases by
20909545a8SDimitry Andric /// dropping arguments as needed, so this pass only ends up getting used in less
21909545a8SDimitry Andric /// common cases.
22909545a8SDimitry Andric ///
23909545a8SDimitry Andric //===----------------------------------------------------------------------===//
24909545a8SDimitry Andric 
25909545a8SDimitry Andric #include "WebAssembly.h"
26909545a8SDimitry Andric #include "llvm/IR/Constants.h"
27909545a8SDimitry Andric #include "llvm/IR/Instructions.h"
28909545a8SDimitry Andric #include "llvm/IR/Module.h"
29909545a8SDimitry Andric #include "llvm/IR/Operator.h"
30909545a8SDimitry Andric #include "llvm/Pass.h"
31909545a8SDimitry Andric #include "llvm/Support/Debug.h"
32909545a8SDimitry Andric #include "llvm/Support/raw_ostream.h"
33909545a8SDimitry Andric using namespace llvm;
34909545a8SDimitry Andric 
35909545a8SDimitry Andric #define DEBUG_TYPE "wasm-fix-function-bitcasts"
36909545a8SDimitry Andric 
37909545a8SDimitry Andric namespace {
38909545a8SDimitry Andric class FixFunctionBitcasts final : public ModulePass {
getPassName() const39909545a8SDimitry Andric   StringRef getPassName() const override {
40909545a8SDimitry Andric     return "WebAssembly Fix Function Bitcasts";
41909545a8SDimitry Andric   }
42909545a8SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const43909545a8SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
44909545a8SDimitry Andric     AU.setPreservesCFG();
45909545a8SDimitry Andric     ModulePass::getAnalysisUsage(AU);
46909545a8SDimitry Andric   }
47909545a8SDimitry Andric 
48909545a8SDimitry Andric   bool runOnModule(Module &M) override;
49909545a8SDimitry Andric 
50909545a8SDimitry Andric public:
51909545a8SDimitry Andric   static char ID;
FixFunctionBitcasts()52909545a8SDimitry Andric   FixFunctionBitcasts() : ModulePass(ID) {}
53909545a8SDimitry Andric };
54909545a8SDimitry Andric } // End anonymous namespace
55909545a8SDimitry Andric 
56909545a8SDimitry Andric char FixFunctionBitcasts::ID = 0;
57eb11fae6SDimitry Andric INITIALIZE_PASS(FixFunctionBitcasts, DEBUG_TYPE,
58eb11fae6SDimitry Andric                 "Fix mismatching bitcasts for WebAssembly", false, false)
59eb11fae6SDimitry Andric 
createWebAssemblyFixFunctionBitcasts()60909545a8SDimitry Andric ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
61909545a8SDimitry Andric   return new FixFunctionBitcasts();
62909545a8SDimitry Andric }
63909545a8SDimitry Andric 
64909545a8SDimitry Andric // Recursively descend the def-use lists from V to find non-bitcast users of
65909545a8SDimitry Andric // bitcasts of V.
findUses(Value * V,Function & F,SmallVectorImpl<std::pair<CallBase *,Function * >> & Uses)66e6d15924SDimitry Andric static void findUses(Value *V, Function &F,
67c0981da4SDimitry Andric                      SmallVectorImpl<std::pair<CallBase *, Function *>> &Uses) {
68c0981da4SDimitry Andric   for (User *U : V->users()) {
69c0981da4SDimitry Andric     if (auto *BC = dyn_cast<BitCastOperator>(U))
70c0981da4SDimitry Andric       findUses(BC, F, Uses);
71c0981da4SDimitry Andric     else if (auto *A = dyn_cast<GlobalAlias>(U))
72c0981da4SDimitry Andric       findUses(A, F, Uses);
73c0981da4SDimitry Andric     else if (auto *CB = dyn_cast<CallBase>(U)) {
74cfca06d7SDimitry Andric       Value *Callee = CB->getCalledOperand();
75044eb2f6SDimitry Andric       if (Callee != V)
76044eb2f6SDimitry Andric         // Skip calls where the function isn't the callee
77044eb2f6SDimitry Andric         continue;
78c0981da4SDimitry Andric       if (CB->getFunctionType() == F.getValueType())
79c0981da4SDimitry Andric         // Skip uses that are immediately called
80044eb2f6SDimitry Andric         continue;
81c0981da4SDimitry Andric       Uses.push_back(std::make_pair(CB, &F));
82909545a8SDimitry Andric     }
83909545a8SDimitry Andric   }
84581a6d85SDimitry Andric }
85909545a8SDimitry Andric 
86909545a8SDimitry Andric // Create a wrapper function with type Ty that calls F (which may have a
87909545a8SDimitry Andric // different type). Attempt to support common bitcasted function idioms:
88909545a8SDimitry Andric //  - Call with more arguments than needed: arguments are dropped
89909545a8SDimitry Andric //  - Call with fewer arguments than needed: arguments are filled in with undef
90909545a8SDimitry Andric //  - Return value is not needed: drop it
91909545a8SDimitry Andric //  - Return value needed but not present: supply an undef
92909545a8SDimitry Andric //
93d8e91e46SDimitry Andric // If the all the argument types of trivially castable to one another (i.e.
94d8e91e46SDimitry Andric // I32 vs pointer type) then we don't create a wrapper at all (return nullptr
95d8e91e46SDimitry Andric // instead).
96d8e91e46SDimitry Andric //
97d8e91e46SDimitry Andric // If there is a type mismatch that we know would result in an invalid wasm
98d8e91e46SDimitry Andric // module then generate wrapper that contains unreachable (i.e. abort at
99d8e91e46SDimitry Andric // runtime).  Such programs are deep into undefined behaviour territory,
100d8e91e46SDimitry Andric // but we choose to fail at runtime rather than generate and invalid module
101d8e91e46SDimitry Andric // or fail at compiler time.  The reason we delay the error is that we want
102d8e91e46SDimitry Andric // to support the CMake which expects to be able to compile and link programs
103d8e91e46SDimitry Andric // that refer to functions with entirely incorrect signatures (this is how
104d8e91e46SDimitry Andric // CMake detects the existence of a function in a toolchain).
105d8e91e46SDimitry Andric //
106d8e91e46SDimitry Andric // For bitcasts that involve struct types we don't know at this stage if they
107d8e91e46SDimitry Andric // would be equivalent at the wasm level and so we can't know if we need to
108d8e91e46SDimitry Andric // generate a wrapper.
createWrapper(Function * F,FunctionType * Ty)109e6d15924SDimitry Andric static Function *createWrapper(Function *F, FunctionType *Ty) {
110909545a8SDimitry Andric   Module *M = F->getParent();
111909545a8SDimitry Andric 
112d8e91e46SDimitry Andric   Function *Wrapper = Function::Create(Ty, Function::PrivateLinkage,
113d8e91e46SDimitry Andric                                        F->getName() + "_bitcast", M);
114909545a8SDimitry Andric   BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
115ac9a064cSDimitry Andric   const DataLayout &DL = BB->getDataLayout();
116909545a8SDimitry Andric 
117909545a8SDimitry Andric   // Determine what arguments to pass.
118909545a8SDimitry Andric   SmallVector<Value *, 4> Args;
119909545a8SDimitry Andric   Function::arg_iterator AI = Wrapper->arg_begin();
120044eb2f6SDimitry Andric   Function::arg_iterator AE = Wrapper->arg_end();
121909545a8SDimitry Andric   FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
122909545a8SDimitry Andric   FunctionType::param_iterator PE = F->getFunctionType()->param_end();
123d8e91e46SDimitry Andric   bool TypeMismatch = false;
124d8e91e46SDimitry Andric   bool WrapperNeeded = false;
125d8e91e46SDimitry Andric 
126d8e91e46SDimitry Andric   Type *ExpectedRtnType = F->getFunctionType()->getReturnType();
127d8e91e46SDimitry Andric   Type *RtnType = Ty->getReturnType();
128d8e91e46SDimitry Andric 
129d8e91e46SDimitry Andric   if ((F->getFunctionType()->getNumParams() != Ty->getNumParams()) ||
130d8e91e46SDimitry Andric       (F->getFunctionType()->isVarArg() != Ty->isVarArg()) ||
131d8e91e46SDimitry Andric       (ExpectedRtnType != RtnType))
132d8e91e46SDimitry Andric     WrapperNeeded = true;
133d8e91e46SDimitry Andric 
134044eb2f6SDimitry Andric   for (; AI != AE && PI != PE; ++AI, ++PI) {
135d8e91e46SDimitry Andric     Type *ArgType = AI->getType();
136d8e91e46SDimitry Andric     Type *ParamType = *PI;
137d8e91e46SDimitry Andric 
138d8e91e46SDimitry Andric     if (ArgType == ParamType) {
139909545a8SDimitry Andric       Args.push_back(&*AI);
140d8e91e46SDimitry Andric     } else {
141d8e91e46SDimitry Andric       if (CastInst::isBitOrNoopPointerCastable(ArgType, ParamType, DL)) {
142d8e91e46SDimitry Andric         Instruction *PtrCast =
143d8e91e46SDimitry Andric             CastInst::CreateBitOrPointerCast(AI, ParamType, "cast");
144e3b55780SDimitry Andric         PtrCast->insertInto(BB, BB->end());
145d8e91e46SDimitry Andric         Args.push_back(PtrCast);
146d8e91e46SDimitry Andric       } else if (ArgType->isStructTy() || ParamType->isStructTy()) {
147e6d15924SDimitry Andric         LLVM_DEBUG(dbgs() << "createWrapper: struct param type in bitcast: "
148d8e91e46SDimitry Andric                           << F->getName() << "\n");
149d8e91e46SDimitry Andric         WrapperNeeded = false;
150d8e91e46SDimitry Andric       } else {
151e6d15924SDimitry Andric         LLVM_DEBUG(dbgs() << "createWrapper: arg type mismatch calling: "
152d8e91e46SDimitry Andric                           << F->getName() << "\n");
153d8e91e46SDimitry Andric         LLVM_DEBUG(dbgs() << "Arg[" << Args.size() << "] Expected: "
154d8e91e46SDimitry Andric                           << *ParamType << " Got: " << *ArgType << "\n");
155d8e91e46SDimitry Andric         TypeMismatch = true;
156d8e91e46SDimitry Andric         break;
157909545a8SDimitry Andric       }
158d8e91e46SDimitry Andric     }
159d8e91e46SDimitry Andric   }
160d8e91e46SDimitry Andric 
161d8e91e46SDimitry Andric   if (WrapperNeeded && !TypeMismatch) {
162909545a8SDimitry Andric     for (; PI != PE; ++PI)
163909545a8SDimitry Andric       Args.push_back(UndefValue::get(*PI));
164044eb2f6SDimitry Andric     if (F->isVarArg())
165044eb2f6SDimitry Andric       for (; AI != AE; ++AI)
166044eb2f6SDimitry Andric         Args.push_back(&*AI);
167909545a8SDimitry Andric 
168909545a8SDimitry Andric     CallInst *Call = CallInst::Create(F, Args, "", BB);
169909545a8SDimitry Andric 
170d8e91e46SDimitry Andric     Type *ExpectedRtnType = F->getFunctionType()->getReturnType();
171d8e91e46SDimitry Andric     Type *RtnType = Ty->getReturnType();
172909545a8SDimitry Andric     // Determine what value to return.
173d8e91e46SDimitry Andric     if (RtnType->isVoidTy()) {
174909545a8SDimitry Andric       ReturnInst::Create(M->getContext(), BB);
175d8e91e46SDimitry Andric     } else if (ExpectedRtnType->isVoidTy()) {
176d8e91e46SDimitry Andric       LLVM_DEBUG(dbgs() << "Creating dummy return: " << *RtnType << "\n");
177d8e91e46SDimitry Andric       ReturnInst::Create(M->getContext(), UndefValue::get(RtnType), BB);
178d8e91e46SDimitry Andric     } else if (RtnType == ExpectedRtnType) {
179909545a8SDimitry Andric       ReturnInst::Create(M->getContext(), Call, BB);
180d8e91e46SDimitry Andric     } else if (CastInst::isBitOrNoopPointerCastable(ExpectedRtnType, RtnType,
181d8e91e46SDimitry Andric                                                     DL)) {
182d8e91e46SDimitry Andric       Instruction *Cast =
183d8e91e46SDimitry Andric           CastInst::CreateBitOrPointerCast(Call, RtnType, "cast");
184e3b55780SDimitry Andric       Cast->insertInto(BB, BB->end());
185d8e91e46SDimitry Andric       ReturnInst::Create(M->getContext(), Cast, BB);
186d8e91e46SDimitry Andric     } else if (RtnType->isStructTy() || ExpectedRtnType->isStructTy()) {
187e6d15924SDimitry Andric       LLVM_DEBUG(dbgs() << "createWrapper: struct return type in bitcast: "
188d8e91e46SDimitry Andric                         << F->getName() << "\n");
189d8e91e46SDimitry Andric       WrapperNeeded = false;
190d8e91e46SDimitry Andric     } else {
191e6d15924SDimitry Andric       LLVM_DEBUG(dbgs() << "createWrapper: return type mismatch calling: "
192d8e91e46SDimitry Andric                         << F->getName() << "\n");
193d8e91e46SDimitry Andric       LLVM_DEBUG(dbgs() << "Expected: " << *ExpectedRtnType
194d8e91e46SDimitry Andric                         << " Got: " << *RtnType << "\n");
195d8e91e46SDimitry Andric       TypeMismatch = true;
196d8e91e46SDimitry Andric     }
197d8e91e46SDimitry Andric   }
198d8e91e46SDimitry Andric 
199d8e91e46SDimitry Andric   if (TypeMismatch) {
200d8e91e46SDimitry Andric     // Create a new wrapper that simply contains `unreachable`.
201d8e91e46SDimitry Andric     Wrapper->eraseFromParent();
202d8e91e46SDimitry Andric     Wrapper = Function::Create(Ty, Function::PrivateLinkage,
203d8e91e46SDimitry Andric                                F->getName() + "_bitcast_invalid", M);
204d8e91e46SDimitry Andric     BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
205d8e91e46SDimitry Andric     new UnreachableInst(M->getContext(), BB);
206d8e91e46SDimitry Andric     Wrapper->setName(F->getName() + "_bitcast_invalid");
207d8e91e46SDimitry Andric   } else if (!WrapperNeeded) {
208e6d15924SDimitry Andric     LLVM_DEBUG(dbgs() << "createWrapper: no wrapper needed: " << F->getName()
209d8e91e46SDimitry Andric                       << "\n");
210909545a8SDimitry Andric     Wrapper->eraseFromParent();
211909545a8SDimitry Andric     return nullptr;
212909545a8SDimitry Andric   }
213e6d15924SDimitry Andric   LLVM_DEBUG(dbgs() << "createWrapper: " << F->getName() << "\n");
214909545a8SDimitry Andric   return Wrapper;
215909545a8SDimitry Andric }
216909545a8SDimitry Andric 
217e6d15924SDimitry Andric // Test whether a main function with type FuncTy should be rewritten to have
218e6d15924SDimitry Andric // type MainTy.
shouldFixMainFunction(FunctionType * FuncTy,FunctionType * MainTy)219e6d15924SDimitry Andric static bool shouldFixMainFunction(FunctionType *FuncTy, FunctionType *MainTy) {
220e6d15924SDimitry Andric   // Only fix the main function if it's the standard zero-arg form. That way,
221e6d15924SDimitry Andric   // the standard cases will work as expected, and users will see signature
222e6d15924SDimitry Andric   // mismatches from the linker for non-standard cases.
223e6d15924SDimitry Andric   return FuncTy->getReturnType() == MainTy->getReturnType() &&
224e6d15924SDimitry Andric          FuncTy->getNumParams() == 0 &&
225e6d15924SDimitry Andric          !FuncTy->isVarArg();
226e6d15924SDimitry Andric }
227e6d15924SDimitry Andric 
runOnModule(Module & M)228909545a8SDimitry Andric bool FixFunctionBitcasts::runOnModule(Module &M) {
229d8e91e46SDimitry Andric   LLVM_DEBUG(dbgs() << "********** Fix Function Bitcasts **********\n");
230d8e91e46SDimitry Andric 
231044eb2f6SDimitry Andric   Function *Main = nullptr;
232044eb2f6SDimitry Andric   CallInst *CallMain = nullptr;
233c0981da4SDimitry Andric   SmallVector<std::pair<CallBase *, Function *>, 0> Uses;
234909545a8SDimitry Andric 
235909545a8SDimitry Andric   // Collect all the places that need wrappers.
236044eb2f6SDimitry Andric   for (Function &F : M) {
237cfca06d7SDimitry Andric     // Skip to fix when the function is swiftcc because swiftcc allows
238cfca06d7SDimitry Andric     // bitcast type difference for swiftself and swifterror.
239cfca06d7SDimitry Andric     if (F.getCallingConv() == CallingConv::Swift)
240cfca06d7SDimitry Andric       continue;
241c0981da4SDimitry Andric     findUses(&F, F, Uses);
242044eb2f6SDimitry Andric 
243044eb2f6SDimitry Andric     // If we have a "main" function, and its type isn't
244044eb2f6SDimitry Andric     // "int main(int argc, char *argv[])", create an artificial call with it
245044eb2f6SDimitry Andric     // bitcasted to that type so that we generate a wrapper for it, so that
246044eb2f6SDimitry Andric     // the C runtime can call it.
247e6d15924SDimitry Andric     if (F.getName() == "main") {
248044eb2f6SDimitry Andric       Main = &F;
249044eb2f6SDimitry Andric       LLVMContext &C = M.getContext();
250b1c73532SDimitry Andric       Type *MainArgTys[] = {Type::getInt32Ty(C), PointerType::get(C, 0)};
251044eb2f6SDimitry Andric       FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys,
252044eb2f6SDimitry Andric                                                /*isVarArg=*/false);
253e6d15924SDimitry Andric       if (shouldFixMainFunction(F.getFunctionType(), MainTy)) {
254d8e91e46SDimitry Andric         LLVM_DEBUG(dbgs() << "Found `main` function with incorrect type: "
255d8e91e46SDimitry Andric                           << *F.getFunctionType() << "\n");
256d8e91e46SDimitry Andric         Value *Args[] = {UndefValue::get(MainArgTys[0]),
257d8e91e46SDimitry Andric                          UndefValue::get(MainArgTys[1])};
258b1c73532SDimitry Andric         CallMain = CallInst::Create(MainTy, Main, Args, "call_main");
259c0981da4SDimitry Andric         Uses.push_back(std::make_pair(CallMain, &F));
260044eb2f6SDimitry Andric       }
261044eb2f6SDimitry Andric     }
262044eb2f6SDimitry Andric   }
263909545a8SDimitry Andric 
264909545a8SDimitry Andric   DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
265909545a8SDimitry Andric 
266909545a8SDimitry Andric   for (auto &UseFunc : Uses) {
267c0981da4SDimitry Andric     CallBase *CB = UseFunc.first;
268909545a8SDimitry Andric     Function *F = UseFunc.second;
269c0981da4SDimitry Andric     FunctionType *Ty = CB->getFunctionType();
27071d5a254SDimitry Andric 
271909545a8SDimitry Andric     auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
272909545a8SDimitry Andric     if (Pair.second)
273e6d15924SDimitry Andric       Pair.first->second = createWrapper(F, Ty);
274909545a8SDimitry Andric 
275909545a8SDimitry Andric     Function *Wrapper = Pair.first->second;
276909545a8SDimitry Andric     if (!Wrapper)
277909545a8SDimitry Andric       continue;
278909545a8SDimitry Andric 
279c0981da4SDimitry Andric     CB->setCalledOperand(Wrapper);
280909545a8SDimitry Andric   }
281909545a8SDimitry Andric 
282044eb2f6SDimitry Andric   // If we created a wrapper for main, rename the wrapper so that it's the
283044eb2f6SDimitry Andric   // one that gets called from startup.
284044eb2f6SDimitry Andric   if (CallMain) {
285044eb2f6SDimitry Andric     Main->setName("__original_main");
286e6d15924SDimitry Andric     auto *MainWrapper =
287cfca06d7SDimitry Andric         cast<Function>(CallMain->getCalledOperand()->stripPointerCasts());
288e6d15924SDimitry Andric     delete CallMain;
289e6d15924SDimitry Andric     if (Main->isDeclaration()) {
290e6d15924SDimitry Andric       // The wrapper is not needed in this case as we don't need to export
291e6d15924SDimitry Andric       // it to anyone else.
292e6d15924SDimitry Andric       MainWrapper->eraseFromParent();
293e6d15924SDimitry Andric     } else {
294e6d15924SDimitry Andric       // Otherwise give the wrapper the same linkage as the original main
295e6d15924SDimitry Andric       // function, so that it can be called from the same places.
296044eb2f6SDimitry Andric       MainWrapper->setName("main");
297044eb2f6SDimitry Andric       MainWrapper->setLinkage(Main->getLinkage());
298044eb2f6SDimitry Andric       MainWrapper->setVisibility(Main->getVisibility());
299e6d15924SDimitry Andric     }
300044eb2f6SDimitry Andric   }
301044eb2f6SDimitry Andric 
302909545a8SDimitry Andric   return true;
303909545a8SDimitry Andric }
304