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 /// 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 INITIALIZE_PASS(FixFunctionBitcasts, DEBUG_TYPE, 65 "Fix mismatching bitcasts for WebAssembly", false, false) 66 67 ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() { 68 return new FixFunctionBitcasts(); 69 } 70 71 // Recursively descend the def-use lists from V to find non-bitcast users of 72 // bitcasts of V. 73 static void FindUses(Value *V, Function &F, 74 SmallVectorImpl<std::pair<Use *, Function *>> &Uses, 75 SmallPtrSetImpl<Constant *> &ConstantBCs) { 76 for (Use &U : V->uses()) { 77 if (BitCastOperator *BC = dyn_cast<BitCastOperator>(U.getUser())) 78 FindUses(BC, F, Uses, ConstantBCs); 79 else if (U.get()->getType() != F.getType()) { 80 CallSite CS(U.getUser()); 81 if (!CS) 82 // Skip uses that aren't immediately called 83 continue; 84 Value *Callee = CS.getCalledValue(); 85 if (Callee != V) 86 // Skip calls where the function isn't the callee 87 continue; 88 if (isa<Constant>(U.get())) { 89 // Only add constant bitcasts to the list once; they get RAUW'd 90 auto c = ConstantBCs.insert(cast<Constant>(U.get())); 91 if (!c.second) 92 continue; 93 } 94 Uses.push_back(std::make_pair(&U, &F)); 95 } 96 } 97 } 98 99 // Create a wrapper function with type Ty that calls F (which may have a 100 // different type). Attempt to support common bitcasted function idioms: 101 // - Call with more arguments than needed: arguments are dropped 102 // - Call with fewer arguments than needed: arguments are filled in with undef 103 // - Return value is not needed: drop it 104 // - Return value needed but not present: supply an undef 105 // 106 // If the all the argument types of trivially castable to one another (i.e. 107 // I32 vs pointer type) then we don't create a wrapper at all (return nullptr 108 // instead). 109 // 110 // If there is a type mismatch that would result in an invalid wasm module 111 // being written then generate wrapper that contains unreachable (i.e. abort 112 // at runtime). Such programs are deep into undefined behaviour territory, 113 // but we choose to fail at runtime rather than generate and invalid module 114 // or fail at compiler time. The reason we delay the error is that we want 115 // to support the CMake which expects to be able to compile and link programs 116 // that refer to functions with entirely incorrect signatures (this is how 117 // CMake detects the existence of a function in a toolchain). 118 static Function *CreateWrapper(Function *F, FunctionType *Ty) { 119 Module *M = F->getParent(); 120 121 Function *Wrapper = Function::Create(Ty, Function::PrivateLinkage, 122 F->getName() + "_bitcast", M); 123 BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper); 124 const DataLayout &DL = BB->getModule()->getDataLayout(); 125 126 // Determine what arguments to pass. 127 SmallVector<Value *, 4> Args; 128 Function::arg_iterator AI = Wrapper->arg_begin(); 129 Function::arg_iterator AE = Wrapper->arg_end(); 130 FunctionType::param_iterator PI = F->getFunctionType()->param_begin(); 131 FunctionType::param_iterator PE = F->getFunctionType()->param_end(); 132 bool TypeMismatch = false; 133 bool WrapperNeeded = false; 134 135 if ((F->getFunctionType()->getNumParams() != Ty->getNumParams()) || 136 (F->getFunctionType()->isVarArg() != Ty->isVarArg())) 137 WrapperNeeded = true; 138 139 for (; AI != AE && PI != PE; ++AI, ++PI) { 140 Type *ArgType = AI->getType(); 141 Type *ParamType = *PI; 142 143 if (ArgType == ParamType) { 144 Args.push_back(&*AI); 145 } else { 146 if (CastInst::isBitOrNoopPointerCastable(ArgType, ParamType, DL)) { 147 Instruction *PtrCast = 148 CastInst::CreateBitOrPointerCast(AI, ParamType, "cast"); 149 BB->getInstList().push_back(PtrCast); 150 Args.push_back(PtrCast); 151 } else { 152 LLVM_DEBUG(dbgs() << "CreateWrapper: arg type mismatch calling: " 153 << F->getName() << "\n"); 154 LLVM_DEBUG(dbgs() << "Arg[" << Args.size() << "] Expected: " 155 << *ParamType << " Got: " << *ArgType << "\n"); 156 TypeMismatch = true; 157 break; 158 } 159 } 160 } 161 162 if (!TypeMismatch) { 163 for (; PI != PE; ++PI) 164 Args.push_back(UndefValue::get(*PI)); 165 if (F->isVarArg()) 166 for (; AI != AE; ++AI) 167 Args.push_back(&*AI); 168 169 CallInst *Call = CallInst::Create(F, Args, "", BB); 170 171 Type *ExpectedRtnType = F->getFunctionType()->getReturnType(); 172 Type *RtnType = Ty->getReturnType(); 173 // Determine what value to return. 174 if (RtnType->isVoidTy()) { 175 ReturnInst::Create(M->getContext(), BB); 176 WrapperNeeded = true; 177 } else if (ExpectedRtnType->isVoidTy()) { 178 ReturnInst::Create(M->getContext(), UndefValue::get(RtnType), BB); 179 WrapperNeeded = true; 180 } else if (RtnType == ExpectedRtnType) { 181 ReturnInst::Create(M->getContext(), Call, BB); 182 } else if (CastInst::isBitOrNoopPointerCastable(ExpectedRtnType, RtnType, 183 DL)) { 184 Instruction *Cast = 185 CastInst::CreateBitOrPointerCast(Call, RtnType, "cast"); 186 BB->getInstList().push_back(Cast); 187 ReturnInst::Create(M->getContext(), Cast, BB); 188 } else { 189 LLVM_DEBUG(dbgs() << "CreateWrapper: return type mismatch calling: " 190 << F->getName() << "\n"); 191 LLVM_DEBUG(dbgs() << "Expected: " << *ExpectedRtnType 192 << " Got: " << *RtnType << "\n"); 193 TypeMismatch = true; 194 } 195 } 196 197 if (TypeMismatch) { 198 new UnreachableInst(M->getContext(), BB); 199 Wrapper->setName(F->getName() + "_bitcast_invalid"); 200 } else if (!WrapperNeeded) { 201 LLVM_DEBUG(dbgs() << "CreateWrapper: no wrapper needed: " << F->getName() 202 << "\n"); 203 Wrapper->eraseFromParent(); 204 return nullptr; 205 } 206 return Wrapper; 207 } 208 209 bool FixFunctionBitcasts::runOnModule(Module &M) { 210 Function *Main = nullptr; 211 CallInst *CallMain = nullptr; 212 SmallVector<std::pair<Use *, Function *>, 0> Uses; 213 SmallPtrSet<Constant *, 2> ConstantBCs; 214 215 // Collect all the places that need wrappers. 216 for (Function &F : M) { 217 FindUses(&F, F, Uses, ConstantBCs); 218 219 // If we have a "main" function, and its type isn't 220 // "int main(int argc, char *argv[])", create an artificial call with it 221 // bitcasted to that type so that we generate a wrapper for it, so that 222 // the C runtime can call it. 223 if (!TemporaryWorkarounds && !F.isDeclaration() && F.getName() == "main") { 224 Main = &F; 225 LLVMContext &C = M.getContext(); 226 Type *MainArgTys[] = { 227 PointerType::get(Type::getInt8PtrTy(C), 0), 228 Type::getInt32Ty(C) 229 }; 230 FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys, 231 /*isVarArg=*/false); 232 if (F.getFunctionType() != MainTy) { 233 Value *Args[] = { 234 UndefValue::get(MainArgTys[0]), 235 UndefValue::get(MainArgTys[1]) 236 }; 237 Value *Casted = ConstantExpr::getBitCast(Main, 238 PointerType::get(MainTy, 0)); 239 CallMain = CallInst::Create(Casted, Args, "call_main"); 240 Use *UseMain = &CallMain->getOperandUse(2); 241 Uses.push_back(std::make_pair(UseMain, &F)); 242 } 243 } 244 } 245 246 DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers; 247 248 for (auto &UseFunc : Uses) { 249 Use *U = UseFunc.first; 250 Function *F = UseFunc.second; 251 PointerType *PTy = cast<PointerType>(U->get()->getType()); 252 FunctionType *Ty = dyn_cast<FunctionType>(PTy->getElementType()); 253 254 // If the function is casted to something like i8* as a "generic pointer" 255 // to be later casted to something else, we can't generate a wrapper for it. 256 // Just ignore such casts for now. 257 if (!Ty) 258 continue; 259 260 auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr)); 261 if (Pair.second) 262 Pair.first->second = CreateWrapper(F, Ty); 263 264 Function *Wrapper = Pair.first->second; 265 if (!Wrapper) 266 continue; 267 268 if (isa<Constant>(U->get())) 269 U->get()->replaceAllUsesWith(Wrapper); 270 else 271 U->set(Wrapper); 272 } 273 274 // If we created a wrapper for main, rename the wrapper so that it's the 275 // one that gets called from startup. 276 if (CallMain) { 277 Main->setName("__original_main"); 278 Function *MainWrapper = 279 cast<Function>(CallMain->getCalledValue()->stripPointerCasts()); 280 MainWrapper->setName("main"); 281 MainWrapper->setLinkage(Main->getLinkage()); 282 MainWrapper->setVisibility(Main->getVisibility()); 283 Main->setLinkage(Function::PrivateLinkage); 284 Main->setVisibility(Function::DefaultVisibility); 285 delete CallMain; 286 } 287 288 return true; 289 } 290