blob: d5e47ee82513772e08f6bffbc7a8af3f8d84781b [file] [log] [blame]
Dan Gohman1b637452017-01-07 00:34:54 +00001//===-- 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000011/// Fix bitcasted functions.
Dan Gohman1b637452017-01-07 00:34:54 +000012///
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"
Jacob Gravelle37af00e2017-10-10 16:20:18 +000027#include "llvm/IR/CallSite.h"
Dan Gohman1b637452017-01-07 00:34:54 +000028#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"
35using namespace llvm;
36
37#define DEBUG_TYPE "wasm-fix-function-bitcasts"
38
Dan Gohman6736f592017-12-08 21:18:21 +000039static cl::opt<bool> TemporaryWorkarounds(
40 "wasm-temporary-workarounds",
41 cl::desc("Apply certain temporary workarounds"),
42 cl::init(true), cl::Hidden);
43
Dan Gohman1b637452017-01-07 00:34:54 +000044namespace {
45class 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
Dan Gohman1b637452017-01-07 00:34:54 +000057public:
58 static char ID;
59 FixFunctionBitcasts() : ModulePass(ID) {}
60};
61} // End anonymous namespace
62
63char FixFunctionBitcasts::ID = 0;
Jacob Gravelle40926452018-03-30 20:36:58 +000064INITIALIZE_PASS(FixFunctionBitcasts, DEBUG_TYPE,
65 "Fix mismatching bitcasts for WebAssembly", false, false)
66
Dan Gohman1b637452017-01-07 00:34:54 +000067ModulePass *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.
73static void FindUses(Value *V, Function &F,
Derek Schuff7acb42a2017-01-10 21:59:53 +000074 SmallVectorImpl<std::pair<Use *, Function *>> &Uses,
75 SmallPtrSetImpl<Constant *> &ConstantBCs) {
Dan Gohman1b637452017-01-07 00:34:54 +000076 for (Use &U : V->uses()) {
77 if (BitCastOperator *BC = dyn_cast<BitCastOperator>(U.getUser()))
Derek Schuff7acb42a2017-01-10 21:59:53 +000078 FindUses(BC, F, Uses, ConstantBCs);
79 else if (U.get()->getType() != F.getType()) {
Jacob Gravelle37af00e2017-10-10 16:20:18 +000080 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;
Derek Schuff7acb42a2017-01-10 21:59:53 +000088 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()));
Jacob Gravelle37af00e2017-10-10 16:20:18 +000091 if (!c.second)
92 continue;
Derek Schuff7acb42a2017-01-10 21:59:53 +000093 }
Dan Gohman1b637452017-01-07 00:34:54 +000094 Uses.push_back(std::make_pair(&U, &F));
Derek Schuff7acb42a2017-01-10 21:59:53 +000095 }
Dan Gohman1b637452017-01-07 00:34:54 +000096 }
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
Dan Gohmand37dc2f2017-02-27 22:41:39 +0000105//
Dan Gohman0e2ceb82017-01-07 01:50:01 +0000106// For now, return nullptr without creating a wrapper if the wrapper cannot
107// be generated due to incompatible types.
Dan Gohman1b637452017-01-07 00:34:54 +0000108static Function *CreateWrapper(Function *F, FunctionType *Ty) {
109 Module *M = F->getParent();
110
111 Function *Wrapper =
112 Function::Create(Ty, Function::PrivateLinkage, "bitcast", M);
113 BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
114
115 // Determine what arguments to pass.
116 SmallVector<Value *, 4> Args;
117 Function::arg_iterator AI = Wrapper->arg_begin();
Dan Gohman2803bfa2017-11-28 17:15:03 +0000118 Function::arg_iterator AE = Wrapper->arg_end();
Dan Gohman1b637452017-01-07 00:34:54 +0000119 FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
120 FunctionType::param_iterator PE = F->getFunctionType()->param_end();
Dan Gohman2803bfa2017-11-28 17:15:03 +0000121 for (; AI != AE && PI != PE; ++AI, ++PI) {
Dan Gohman0e2ceb82017-01-07 01:50:01 +0000122 if (AI->getType() != *PI) {
123 Wrapper->eraseFromParent();
124 return nullptr;
125 }
Dan Gohman1b637452017-01-07 00:34:54 +0000126 Args.push_back(&*AI);
127 }
128 for (; PI != PE; ++PI)
129 Args.push_back(UndefValue::get(*PI));
Dan Gohman2803bfa2017-11-28 17:15:03 +0000130 if (F->isVarArg())
131 for (; AI != AE; ++AI)
132 Args.push_back(&*AI);
Dan Gohman1b637452017-01-07 00:34:54 +0000133
134 CallInst *Call = CallInst::Create(F, Args, "", BB);
135
136 // Determine what value to return.
137 if (Ty->getReturnType()->isVoidTy())
138 ReturnInst::Create(M->getContext(), BB);
139 else if (F->getFunctionType()->getReturnType()->isVoidTy())
140 ReturnInst::Create(M->getContext(), UndefValue::get(Ty->getReturnType()),
141 BB);
142 else if (F->getFunctionType()->getReturnType() == Ty->getReturnType())
143 ReturnInst::Create(M->getContext(), Call, BB);
Dan Gohman0e2ceb82017-01-07 01:50:01 +0000144 else {
145 Wrapper->eraseFromParent();
146 return nullptr;
147 }
Dan Gohman1b637452017-01-07 00:34:54 +0000148
149 return Wrapper;
150}
151
152bool FixFunctionBitcasts::runOnModule(Module &M) {
Dan Gohman6736f592017-12-08 21:18:21 +0000153 Function *Main = nullptr;
154 CallInst *CallMain = nullptr;
Dan Gohmand5eda352017-01-07 01:31:18 +0000155 SmallVector<std::pair<Use *, Function *>, 0> Uses;
Derek Schuff7acb42a2017-01-10 21:59:53 +0000156 SmallPtrSet<Constant *, 2> ConstantBCs;
Dan Gohmand5eda352017-01-07 01:31:18 +0000157
Dan Gohman1b637452017-01-07 00:34:54 +0000158 // Collect all the places that need wrappers.
Dan Gohman6736f592017-12-08 21:18:21 +0000159 for (Function &F : M) {
160 FindUses(&F, F, Uses, ConstantBCs);
161
162 // If we have a "main" function, and its type isn't
163 // "int main(int argc, char *argv[])", create an artificial call with it
164 // bitcasted to that type so that we generate a wrapper for it, so that
165 // the C runtime can call it.
166 if (!TemporaryWorkarounds && !F.isDeclaration() && F.getName() == "main") {
167 Main = &F;
168 LLVMContext &C = M.getContext();
169 Type *MainArgTys[] = {
170 PointerType::get(Type::getInt8PtrTy(C), 0),
171 Type::getInt32Ty(C)
172 };
173 FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys,
174 /*isVarArg=*/false);
175 if (F.getFunctionType() != MainTy) {
176 Value *Args[] = {
177 UndefValue::get(MainArgTys[0]),
178 UndefValue::get(MainArgTys[1])
179 };
180 Value *Casted = ConstantExpr::getBitCast(Main,
181 PointerType::get(MainTy, 0));
182 CallMain = CallInst::Create(Casted, Args, "call_main");
183 Use *UseMain = &CallMain->getOperandUse(2);
184 Uses.push_back(std::make_pair(UseMain, &F));
185 }
186 }
187 }
Dan Gohman1b637452017-01-07 00:34:54 +0000188
189 DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
190
191 for (auto &UseFunc : Uses) {
192 Use *U = UseFunc.first;
193 Function *F = UseFunc.second;
194 PointerType *PTy = cast<PointerType>(U->get()->getType());
195 FunctionType *Ty = dyn_cast<FunctionType>(PTy->getElementType());
196
197 // If the function is casted to something like i8* as a "generic pointer"
198 // to be later casted to something else, we can't generate a wrapper for it.
199 // Just ignore such casts for now.
200 if (!Ty)
201 continue;
202
Dan Gohman78c19d62017-11-30 18:16:49 +0000203 // Bitcasted vararg functions occur in Emscripten's implementation of
204 // EM_ASM, so suppress wrappers for them for now.
Dan Gohman3a762bf2017-12-08 21:27:00 +0000205 if (TemporaryWorkarounds && (Ty->isVarArg() || F->isVarArg()))
Dan Gohman78c19d62017-11-30 18:16:49 +0000206 continue;
207
Dan Gohman1b637452017-01-07 00:34:54 +0000208 auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
209 if (Pair.second)
210 Pair.first->second = CreateWrapper(F, Ty);
211
Dan Gohman0e2ceb82017-01-07 01:50:01 +0000212 Function *Wrapper = Pair.first->second;
213 if (!Wrapper)
214 continue;
215
Dan Gohman1b637452017-01-07 00:34:54 +0000216 if (isa<Constant>(U->get()))
Dan Gohman0e2ceb82017-01-07 01:50:01 +0000217 U->get()->replaceAllUsesWith(Wrapper);
Dan Gohman1b637452017-01-07 00:34:54 +0000218 else
Dan Gohman0e2ceb82017-01-07 01:50:01 +0000219 U->set(Wrapper);
Dan Gohman1b637452017-01-07 00:34:54 +0000220 }
221
Dan Gohman6736f592017-12-08 21:18:21 +0000222 // If we created a wrapper for main, rename the wrapper so that it's the
223 // one that gets called from startup.
224 if (CallMain) {
225 Main->setName("__original_main");
226 Function *MainWrapper =
227 cast<Function>(CallMain->getCalledValue()->stripPointerCasts());
228 MainWrapper->setName("main");
229 MainWrapper->setLinkage(Main->getLinkage());
230 MainWrapper->setVisibility(Main->getVisibility());
231 Main->setLinkage(Function::PrivateLinkage);
232 Main->setVisibility(Function::DefaultVisibility);
233 delete CallMain;
234 }
235
Dan Gohman1b637452017-01-07 00:34:54 +0000236 return true;
237}