1 //===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Fix bitcasted functions.
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.
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.
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
24 //===----------------------------------------------------------------------===//
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"
37 #define DEBUG_TYPE "wasm-fix-function-bitcasts"
39 static cl::opt<bool> TemporaryWorkarounds(
40 "wasm-temporary-workarounds",
41 cl::desc("Apply certain temporary workarounds"),
42 cl::init(true), cl::Hidden);
45 class FixFunctionBitcasts final : public ModulePass {
46 StringRef getPassName() const override {
47 return "WebAssembly Fix Function Bitcasts";
50 void getAnalysisUsage(AnalysisUsage &AU) const override {
52 ModulePass::getAnalysisUsage(AU);
55 bool runOnModule(Module &M) override;
59 FixFunctionBitcasts() : ModulePass(ID) {}
61 } // End anonymous namespace
63 char FixFunctionBitcasts::ID = 0;
64 ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
65 return new FixFunctionBitcasts();
68 // Recursively descend the def-use lists from V to find non-bitcast users of
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());
79 // Skip uses that aren't immediately called
81 Value *Callee = CS.getCalledValue();
83 // Skip calls where the function isn't the callee
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()));
91 Uses.push_back(std::make_pair(&U, &F));
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
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();
109 Function::Create(Ty, Function::PrivateLinkage, "bitcast", M);
110 BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
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();
123 Args.push_back(&*AI);
125 for (; PI != PE; ++PI)
126 Args.push_back(UndefValue::get(*PI));
128 for (; AI != AE; ++AI)
129 Args.push_back(&*AI);
131 CallInst *Call = CallInst::Create(F, Args, "", BB);
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()),
139 else if (F->getFunctionType()->getReturnType() == Ty->getReturnType())
140 ReturnInst::Create(M->getContext(), Call, BB);
142 Wrapper->eraseFromParent();
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;
155 // Collect all the places that need wrappers.
156 for (Function &F : M) {
157 FindUses(&F, F, Uses, ConstantBCs);
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") {
165 LLVMContext &C = M.getContext();
166 Type *MainArgTys[] = {
167 PointerType::get(Type::getInt8PtrTy(C), 0),
170 FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys,
172 if (F.getFunctionType() != MainTy) {
174 UndefValue::get(MainArgTys[0]),
175 UndefValue::get(MainArgTys[1])
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));
186 DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
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());
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.
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()))
205 auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
207 Pair.first->second = CreateWrapper(F, Ty);
209 Function *Wrapper = Pair.first->second;
213 if (isa<Constant>(U->get()))
214 U->get()->replaceAllUsesWith(Wrapper);
219 // If we created a wrapper for main, rename the wrapper so that it's the
220 // one that gets called from startup.
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);