xref: /llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp (revision cdaa87dd2e5c91127348ca998ddac87f9622e88b)
1 //===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief Fix bitcasted functions.
12 ///
13 /// WebAssembly requires caller and callee signatures to match, however in LLVM,
14 /// some amount of slop is vaguely permitted. Detect mismatch by looking for
15 /// bitcasts of functions and rewrite them to use wrapper functions instead.
16 ///
17 /// This doesn't catch all cases, such as when a function's address is taken in
18 /// one place and casted in another, but it works for many common cases.
19 ///
20 /// Note that LLVM already optimizes away function bitcasts in common cases by
21 /// dropping arguments as needed, so this pass only ends up getting used in less
22 /// common cases.
23 ///
24 //===----------------------------------------------------------------------===//
25 
26 #include "WebAssembly.h"
27 #include "llvm/IR/CallSite.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "wasm-fix-function-bitcasts"
38 
39 namespace {
40 class FixFunctionBitcasts final : public ModulePass {
41   StringRef getPassName() const override {
42     return "WebAssembly Fix Function Bitcasts";
43   }
44 
45   void getAnalysisUsage(AnalysisUsage &AU) const override {
46     AU.setPreservesCFG();
47     ModulePass::getAnalysisUsage(AU);
48   }
49 
50   bool runOnModule(Module &M) override;
51 
52 public:
53   static char ID;
54   FixFunctionBitcasts() : ModulePass(ID) {}
55 };
56 } // End anonymous namespace
57 
58 char FixFunctionBitcasts::ID = 0;
59 ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
60   return new FixFunctionBitcasts();
61 }
62 
63 // Recursively descend the def-use lists from V to find non-bitcast users of
64 // bitcasts of V.
65 static void FindUses(Value *V, Function &F,
66                      SmallVectorImpl<std::pair<Use *, Function *>> &Uses,
67                      SmallPtrSetImpl<Constant *> &ConstantBCs) {
68   for (Use &U : V->uses()) {
69     if (BitCastOperator *BC = dyn_cast<BitCastOperator>(U.getUser()))
70       FindUses(BC, F, Uses, ConstantBCs);
71     else if (U.get()->getType() != F.getType()) {
72       CallSite CS(U.getUser());
73       if (!CS)
74         // Skip uses that aren't immediately called
75         continue;
76       Value *Callee = CS.getCalledValue();
77       if (Callee != V)
78         // Skip calls where the function isn't the callee
79         continue;
80       if (isa<Constant>(U.get())) {
81         // Only add constant bitcasts to the list once; they get RAUW'd
82         auto c = ConstantBCs.insert(cast<Constant>(U.get()));
83         if (!c.second)
84           continue;
85       }
86       Uses.push_back(std::make_pair(&U, &F));
87     }
88   }
89 }
90 
91 // Create a wrapper function with type Ty that calls F (which may have a
92 // different type). Attempt to support common bitcasted function idioms:
93 //  - Call with more arguments than needed: arguments are dropped
94 //  - Call with fewer arguments than needed: arguments are filled in with undef
95 //  - Return value is not needed: drop it
96 //  - Return value needed but not present: supply an undef
97 //
98 // For now, return nullptr without creating a wrapper if the wrapper cannot
99 // be generated due to incompatible types.
100 static Function *CreateWrapper(Function *F, FunctionType *Ty) {
101   Module *M = F->getParent();
102 
103   Function *Wrapper =
104       Function::Create(Ty, Function::PrivateLinkage, "bitcast", M);
105   BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
106 
107   // Determine what arguments to pass.
108   SmallVector<Value *, 4> Args;
109   Function::arg_iterator AI = Wrapper->arg_begin();
110   Function::arg_iterator AE = Wrapper->arg_end();
111   FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
112   FunctionType::param_iterator PE = F->getFunctionType()->param_end();
113   for (; AI != AE && PI != PE; ++AI, ++PI) {
114     if (AI->getType() != *PI) {
115       Wrapper->eraseFromParent();
116       return nullptr;
117     }
118     Args.push_back(&*AI);
119   }
120   for (; PI != PE; ++PI)
121     Args.push_back(UndefValue::get(*PI));
122   if (F->isVarArg())
123     for (; AI != AE; ++AI)
124       Args.push_back(&*AI);
125 
126   CallInst *Call = CallInst::Create(F, Args, "", BB);
127 
128   // Determine what value to return.
129   if (Ty->getReturnType()->isVoidTy())
130     ReturnInst::Create(M->getContext(), BB);
131   else if (F->getFunctionType()->getReturnType()->isVoidTy())
132     ReturnInst::Create(M->getContext(), UndefValue::get(Ty->getReturnType()),
133                        BB);
134   else if (F->getFunctionType()->getReturnType() == Ty->getReturnType())
135     ReturnInst::Create(M->getContext(), Call, BB);
136   else {
137     Wrapper->eraseFromParent();
138     return nullptr;
139   }
140 
141   return Wrapper;
142 }
143 
144 bool FixFunctionBitcasts::runOnModule(Module &M) {
145   Function *Main = nullptr;
146   CallInst *CallMain = nullptr;
147   SmallVector<std::pair<Use *, Function *>, 0> Uses;
148   SmallPtrSet<Constant *, 2> ConstantBCs;
149 
150   // Collect all the places that need wrappers.
151   for (Function &F : M) {
152     FindUses(&F, F, Uses, ConstantBCs);
153 
154     // If we have a "main" function, and its type isn't
155     // "int main(int argc, char *argv[])", create an artificial call with it
156     // bitcasted to that type so that we generate a wrapper for it, so that
157     // the C runtime can call it.
158     if (F.getName() == "main") {
159       Main = &F;
160       LLVMContext &C = M.getContext();
161       Type *MainArgTys[] = {
162         PointerType::get(Type::getInt8PtrTy(C), 0),
163         Type::getInt32Ty(C)
164       };
165       FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys,
166                                                /*isVarArg=*/false);
167       if (F.getFunctionType() != MainTy) {
168         Value *Args[] = {
169           UndefValue::get(MainArgTys[0]),
170           UndefValue::get(MainArgTys[1])
171         };
172         Value *Casted = ConstantExpr::getBitCast(Main,
173                                                  PointerType::get(MainTy, 0));
174         CallMain = CallInst::Create(Casted, Args, "call_main");
175         Use *UseMain = &CallMain->getOperandUse(2);
176         Uses.push_back(std::make_pair(UseMain, &F));
177       }
178     }
179   }
180 
181   DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
182 
183   for (auto &UseFunc : Uses) {
184     Use *U = UseFunc.first;
185     Function *F = UseFunc.second;
186     PointerType *PTy = cast<PointerType>(U->get()->getType());
187     FunctionType *Ty = dyn_cast<FunctionType>(PTy->getElementType());
188 
189     // If the function is casted to something like i8* as a "generic pointer"
190     // to be later casted to something else, we can't generate a wrapper for it.
191     // Just ignore such casts for now.
192     if (!Ty)
193       continue;
194 
195     // Bitcasted vararg functions occur in Emscripten's implementation of
196     // EM_ASM, so suppress wrappers for them for now.
197     if (Ty->isVarArg() || F->isVarArg())
198       continue;
199 
200     auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
201     if (Pair.second)
202       Pair.first->second = CreateWrapper(F, Ty);
203 
204     Function *Wrapper = Pair.first->second;
205     if (!Wrapper)
206       continue;
207 
208     if (isa<Constant>(U->get()))
209       U->get()->replaceAllUsesWith(Wrapper);
210     else
211       U->set(Wrapper);
212   }
213 
214   // If we created a wrapper for main, rename the wrapper so that it's the
215   // one that gets called from startup.
216   if (CallMain) {
217     Main->setName("__original_main");
218     Function *MainWrapper =
219         cast<Function>(CallMain->getCalledValue()->stripPointerCasts());
220     MainWrapper->setName("main");
221     MainWrapper->setLinkage(Main->getLinkage());
222     MainWrapper->setVisibility(Main->getVisibility());
223     Main->setLinkage(Function::PrivateLinkage);
224     Main->setVisibility(Function::DefaultVisibility);
225     delete CallMain;
226   }
227 
228   return true;
229 }
230