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 static cl::opt<bool> TemporaryWorkarounds( 40 "wasm-temporary-workarounds", 41 cl::desc("Apply certain temporary workarounds"), 42 cl::init(true), cl::Hidden); 43 44 namespace { 45 class FixFunctionBitcasts final : public ModulePass { 46 StringRef getPassName() const override { 47 return "WebAssembly Fix Function Bitcasts"; 48 } 49 50 void getAnalysisUsage(AnalysisUsage &AU) const override { 51 AU.setPreservesCFG(); 52 ModulePass::getAnalysisUsage(AU); 53 } 54 55 bool runOnModule(Module &M) override; 56 57 public: 58 static char ID; 59 FixFunctionBitcasts() : ModulePass(ID) {} 60 }; 61 } // End anonymous namespace 62 63 char FixFunctionBitcasts::ID = 0; 64 ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() { 65 return new FixFunctionBitcasts(); 66 } 67 68 // Recursively descend the def-use lists from V to find non-bitcast users of 69 // bitcasts of V. 70 static void FindUses(Value *V, Function &F, 71 SmallVectorImpl<std::pair<Use *, Function *>> &Uses, 72 SmallPtrSetImpl<Constant *> &ConstantBCs) { 73 for (Use &U : V->uses()) { 74 if (BitCastOperator *BC = dyn_cast<BitCastOperator>(U.getUser())) 75 FindUses(BC, F, Uses, ConstantBCs); 76 else if (U.get()->getType() != F.getType()) { 77 CallSite CS(U.getUser()); 78 if (!CS) 79 // Skip uses that aren't immediately called 80 continue; 81 Value *Callee = CS.getCalledValue(); 82 if (Callee != V) 83 // Skip calls where the function isn't the callee 84 continue; 85 if (isa<Constant>(U.get())) { 86 // Only add constant bitcasts to the list once; they get RAUW'd 87 auto c = ConstantBCs.insert(cast<Constant>(U.get())); 88 if (!c.second) 89 continue; 90 } 91 Uses.push_back(std::make_pair(&U, &F)); 92 } 93 } 94 } 95 96 // Create a wrapper function with type Ty that calls F (which may have a 97 // different type). Attempt to support common bitcasted function idioms: 98 // - Call with more arguments than needed: arguments are dropped 99 // - Call with fewer arguments than needed: arguments are filled in with undef 100 // - Return value is not needed: drop it 101 // - Return value needed but not present: supply an undef 102 // 103 // For now, return nullptr without creating a wrapper if the wrapper cannot 104 // be generated due to incompatible types. 105 static Function *CreateWrapper(Function *F, FunctionType *Ty) { 106 Module *M = F->getParent(); 107 108 Function *Wrapper = 109 Function::Create(Ty, Function::PrivateLinkage, "bitcast", M); 110 BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper); 111 112 // Determine what arguments to pass. 113 SmallVector<Value *, 4> Args; 114 Function::arg_iterator AI = Wrapper->arg_begin(); 115 Function::arg_iterator AE = Wrapper->arg_end(); 116 FunctionType::param_iterator PI = F->getFunctionType()->param_begin(); 117 FunctionType::param_iterator PE = F->getFunctionType()->param_end(); 118 for (; AI != AE && PI != PE; ++AI, ++PI) { 119 if (AI->getType() != *PI) { 120 Wrapper->eraseFromParent(); 121 return nullptr; 122 } 123 Args.push_back(&*AI); 124 } 125 for (; PI != PE; ++PI) 126 Args.push_back(UndefValue::get(*PI)); 127 if (F->isVarArg()) 128 for (; AI != AE; ++AI) 129 Args.push_back(&*AI); 130 131 CallInst *Call = CallInst::Create(F, Args, "", BB); 132 133 // Determine what value to return. 134 if (Ty->getReturnType()->isVoidTy()) 135 ReturnInst::Create(M->getContext(), BB); 136 else if (F->getFunctionType()->getReturnType()->isVoidTy()) 137 ReturnInst::Create(M->getContext(), UndefValue::get(Ty->getReturnType()), 138 BB); 139 else if (F->getFunctionType()->getReturnType() == Ty->getReturnType()) 140 ReturnInst::Create(M->getContext(), Call, BB); 141 else { 142 Wrapper->eraseFromParent(); 143 return nullptr; 144 } 145 146 return Wrapper; 147 } 148 149 bool FixFunctionBitcasts::runOnModule(Module &M) { 150 Function *Main = nullptr; 151 CallInst *CallMain = nullptr; 152 SmallVector<std::pair<Use *, Function *>, 0> Uses; 153 SmallPtrSet<Constant *, 2> ConstantBCs; 154 155 // Collect all the places that need wrappers. 156 for (Function &F : M) { 157 FindUses(&F, F, Uses, ConstantBCs); 158 159 // If we have a "main" function, and its type isn't 160 // "int main(int argc, char *argv[])", create an artificial call with it 161 // bitcasted to that type so that we generate a wrapper for it, so that 162 // the C runtime can call it. 163 if (!TemporaryWorkarounds && !F.isDeclaration() && F.getName() == "main") { 164 Main = &F; 165 LLVMContext &C = M.getContext(); 166 Type *MainArgTys[] = { 167 PointerType::get(Type::getInt8PtrTy(C), 0), 168 Type::getInt32Ty(C) 169 }; 170 FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys, 171 /*isVarArg=*/false); 172 if (F.getFunctionType() != MainTy) { 173 Value *Args[] = { 174 UndefValue::get(MainArgTys[0]), 175 UndefValue::get(MainArgTys[1]) 176 }; 177 Value *Casted = ConstantExpr::getBitCast(Main, 178 PointerType::get(MainTy, 0)); 179 CallMain = CallInst::Create(Casted, Args, "call_main"); 180 Use *UseMain = &CallMain->getOperandUse(2); 181 Uses.push_back(std::make_pair(UseMain, &F)); 182 } 183 } 184 } 185 186 DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers; 187 188 for (auto &UseFunc : Uses) { 189 Use *U = UseFunc.first; 190 Function *F = UseFunc.second; 191 PointerType *PTy = cast<PointerType>(U->get()->getType()); 192 FunctionType *Ty = dyn_cast<FunctionType>(PTy->getElementType()); 193 194 // If the function is casted to something like i8* as a "generic pointer" 195 // to be later casted to something else, we can't generate a wrapper for it. 196 // Just ignore such casts for now. 197 if (!Ty) 198 continue; 199 200 // Bitcasted vararg functions occur in Emscripten's implementation of 201 // EM_ASM, so suppress wrappers for them for now. 202 if (TemporaryWorkarounds && (Ty->isVarArg() || F->isVarArg())) 203 continue; 204 205 auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr)); 206 if (Pair.second) 207 Pair.first->second = CreateWrapper(F, Ty); 208 209 Function *Wrapper = Pair.first->second; 210 if (!Wrapper) 211 continue; 212 213 if (isa<Constant>(U->get())) 214 U->get()->replaceAllUsesWith(Wrapper); 215 else 216 U->set(Wrapper); 217 } 218 219 // If we created a wrapper for main, rename the wrapper so that it's the 220 // one that gets called from startup. 221 if (CallMain) { 222 Main->setName("__original_main"); 223 Function *MainWrapper = 224 cast<Function>(CallMain->getCalledValue()->stripPointerCasts()); 225 MainWrapper->setName("main"); 226 MainWrapper->setLinkage(Main->getLinkage()); 227 MainWrapper->setVisibility(Main->getVisibility()); 228 Main->setLinkage(Function::PrivateLinkage); 229 Main->setVisibility(Function::DefaultVisibility); 230 delete CallMain; 231 } 232 233 return true; 234 } 235