1//===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Fix bitcasted functions.
11///
12/// WebAssembly requires caller and callee signatures to match, however in LLVM,
13/// some amount of slop is vaguely permitted. Detect mismatch by looking for
14/// bitcasts of functions and rewrite them to use wrapper functions instead.
15///
16/// This doesn't catch all cases, such as when a function's address is taken in
17/// one place and casted in another, but it works for many common cases.
18///
19/// Note that LLVM already optimizes away function bitcasts in common cases by
20/// dropping arguments as needed, so this pass only ends up getting used in less
21/// common cases.
22///
23//===----------------------------------------------------------------------===//
24
25#include "WebAssembly.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/Module.h"
30#include "llvm/IR/Operator.h"
31#include "llvm/Pass.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/raw_ostream.h"
34using namespace llvm;
35
36#define DEBUG_TYPE "wasm-fix-function-bitcasts"
37
38namespace {
39class FixFunctionBitcasts final : public ModulePass {
40 StringRef getPassName() const override {
41 return "WebAssembly Fix Function Bitcasts";
42 }
43
44 void getAnalysisUsage(AnalysisUsage &AU) const override {
45 AU.setPreservesCFG();
46 ModulePass::getAnalysisUsage(AU);
47 }
48
49 bool runOnModule(Module &M) override;
50
51public:
52 static char ID;
53 FixFunctionBitcasts() : ModulePass(ID) {}
54};
55} // End anonymous namespace
56
57char FixFunctionBitcasts::ID = 0;
58INITIALIZE_PASS(FixFunctionBitcasts, DEBUG_TYPE,
59 "Fix mismatching bitcasts for WebAssembly", false, false)
60
61ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
62 return new FixFunctionBitcasts();
63}
64
65// Recursively descend the def-use lists from V to find non-bitcast users of
66// bitcasts of V.
67static void findUses(Value *V, Function &F,
68 SmallVectorImpl<std::pair<CallBase *, Function *>> &Uses) {
69 for (User *U : V->users()) {
70 if (auto *BC = dyn_cast<BitCastOperator>(Val: U))
71 findUses(V: BC, F, Uses);
72 else if (auto *A = dyn_cast<GlobalAlias>(Val: U))
73 findUses(V: A, F, Uses);
74 else if (auto *CB = dyn_cast<CallBase>(Val: U)) {
75 Value *Callee = CB->getCalledOperand();
76 if (Callee != V)
77 // Skip calls where the function isn't the callee
78 continue;
79 if (CB->getFunctionType() == F.getFunctionType())
80 // Skip uses that are immediately called
81 continue;
82 Uses.push_back(Elt: std::make_pair(x&: CB, y: &F));
83 }
84 }
85}
86
87// Create a wrapper function with type Ty that calls F (which may have a
88// different type). Attempt to support common bitcasted function idioms:
89// - Call with more arguments than needed: arguments are dropped
90// - Call with fewer arguments than needed: arguments are filled in with poison
91// - Return value is not needed: drop it
92// - Return value needed but not present: supply a poison value
93//
94// If the all the argument types of trivially castable to one another (i.e.
95// I32 vs pointer type) then we don't create a wrapper at all (return nullptr
96// instead).
97//
98// If there is a type mismatch that we know would result in an invalid wasm
99// module then generate wrapper that contains unreachable (i.e. abort at
100// runtime). Such programs are deep into undefined behaviour territory,
101// but we choose to fail at runtime rather than generate and invalid module
102// or fail at compiler time. The reason we delay the error is that we want
103// to support the CMake which expects to be able to compile and link programs
104// that refer to functions with entirely incorrect signatures (this is how
105// CMake detects the existence of a function in a toolchain).
106//
107// For bitcasts that involve struct types we don't know at this stage if they
108// would be equivalent at the wasm level and so we can't know if we need to
109// generate a wrapper.
110static Function *createWrapper(Function *F, FunctionType *Ty) {
111 Module *M = F->getParent();
112
113 Function *Wrapper = Function::Create(Ty, Linkage: Function::PrivateLinkage,
114 N: F->getName() + "_bitcast", M);
115 Wrapper->setAttributes(F->getAttributes());
116 BasicBlock *BB = BasicBlock::Create(Context&: M->getContext(), Name: "body", Parent: Wrapper);
117 const DataLayout &DL = BB->getDataLayout();
118 IRBuilder<> Builder(BB);
119
120 // Determine what arguments to pass.
121 SmallVector<Value *, 4> Args;
122 Function::arg_iterator AI = Wrapper->arg_begin();
123 Function::arg_iterator AE = Wrapper->arg_end();
124 FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
125 FunctionType::param_iterator PE = F->getFunctionType()->param_end();
126 bool TypeMismatch = false;
127 bool WrapperNeeded = false;
128
129 Type *ExpectedRtnType = F->getFunctionType()->getReturnType();
130 Type *RtnType = Ty->getReturnType();
131
132 if ((F->getFunctionType()->getNumParams() != Ty->getNumParams()) ||
133 (F->getFunctionType()->isVarArg() != Ty->isVarArg()) ||
134 (ExpectedRtnType != RtnType))
135 WrapperNeeded = true;
136
137 for (; AI != AE && PI != PE; ++AI, ++PI) {
138 Type *ArgType = AI->getType();
139 Type *ParamType = *PI;
140
141 if (ArgType == ParamType) {
142 Args.push_back(Elt: &*AI);
143 } else {
144 if (CastInst::isBitOrNoopPointerCastable(SrcTy: ArgType, DestTy: ParamType, DL)) {
145 Args.push_back(Elt: Builder.CreateBitOrPointerCast(V: AI, DestTy: ParamType, Name: "cast"));
146 } else if (ArgType->isStructTy() || ParamType->isStructTy()) {
147 LLVM_DEBUG(dbgs() << "createWrapper: struct param type in bitcast: "
148 << F->getName() << "\n");
149 WrapperNeeded = false;
150 } else {
151 LLVM_DEBUG(dbgs() << "createWrapper: arg type mismatch calling: "
152 << F->getName() << "\n");
153 LLVM_DEBUG(dbgs() << "Arg[" << Args.size() << "] Expected: "
154 << *ParamType << " Got: " << *ArgType << "\n");
155 TypeMismatch = true;
156 break;
157 }
158 }
159 }
160
161 if (WrapperNeeded && !TypeMismatch) {
162 for (; PI != PE; ++PI)
163 Args.push_back(Elt: PoisonValue::get(T: *PI));
164 if (F->isVarArg())
165 for (; AI != AE; ++AI)
166 Args.push_back(Elt: &*AI);
167
168 CallInst *Call = Builder.CreateCall(Callee: F, Args);
169
170 // Determine what value to return.
171 if (RtnType->isVoidTy()) {
172 Builder.CreateRetVoid();
173 } else if (ExpectedRtnType->isVoidTy()) {
174 LLVM_DEBUG(dbgs() << "Creating dummy return: " << *RtnType << "\n");
175 Builder.CreateRet(V: PoisonValue::get(T: RtnType));
176 } else if (RtnType == ExpectedRtnType) {
177 Builder.CreateRet(V: Call);
178 } else if (CastInst::isBitOrNoopPointerCastable(SrcTy: ExpectedRtnType, DestTy: RtnType,
179 DL)) {
180 Builder.CreateRet(V: Builder.CreateBitOrPointerCast(V: Call, DestTy: RtnType, Name: "cast"));
181 } else if (RtnType->isStructTy() || ExpectedRtnType->isStructTy()) {
182 LLVM_DEBUG(dbgs() << "createWrapper: struct return type in bitcast: "
183 << F->getName() << "\n");
184 WrapperNeeded = false;
185 } else {
186 LLVM_DEBUG(dbgs() << "createWrapper: return type mismatch calling: "
187 << F->getName() << "\n");
188 LLVM_DEBUG(dbgs() << "Expected: " << *ExpectedRtnType
189 << " Got: " << *RtnType << "\n");
190 TypeMismatch = true;
191 }
192 }
193
194 if (TypeMismatch) {
195 // Create a new wrapper that simply contains `unreachable`.
196 Wrapper->eraseFromParent();
197 Wrapper = Function::Create(Ty, Linkage: Function::PrivateLinkage,
198 N: F->getName() + "_bitcast_invalid", M);
199 Wrapper->setAttributes(F->getAttributes());
200 IRBuilder<> Builder(BasicBlock::Create(Context&: M->getContext(), Name: "body", Parent: Wrapper));
201 Builder.CreateUnreachable();
202 } else if (!WrapperNeeded) {
203 LLVM_DEBUG(dbgs() << "createWrapper: no wrapper needed: " << F->getName()
204 << "\n");
205 Wrapper->eraseFromParent();
206 return nullptr;
207 }
208 LLVM_DEBUG(dbgs() << "createWrapper: " << F->getName() << "\n");
209 return Wrapper;
210}
211
212// Test whether a main function with type FuncTy should be rewritten to have
213// type MainTy.
214static bool shouldFixMainFunction(FunctionType *FuncTy, FunctionType *MainTy) {
215 // Only fix the main function if it's the standard zero-arg form. That way,
216 // the standard cases will work as expected, and users will see signature
217 // mismatches from the linker for non-standard cases.
218 return FuncTy->getReturnType() == MainTy->getReturnType() &&
219 FuncTy->getNumParams() == 0 &&
220 !FuncTy->isVarArg();
221}
222
223bool FixFunctionBitcasts::runOnModule(Module &M) {
224 LLVM_DEBUG(dbgs() << "********** Fix Function Bitcasts **********\n");
225
226 Function *Main = nullptr;
227 CallInst *CallMain = nullptr;
228 SmallVector<std::pair<CallBase *, Function *>, 0> Uses;
229
230 // Collect all the places that need wrappers.
231 for (Function &F : M) {
232 // Skip to fix when the function is swiftcc because swiftcc allows
233 // bitcast type difference for swiftself and swifterror.
234 if (F.getCallingConv() == CallingConv::Swift)
235 continue;
236 findUses(V: &F, F, Uses);
237
238 // If we have a "main" function, and its type isn't
239 // "int main(int argc, char *argv[])", create an artificial call with it
240 // bitcasted to that type so that we generate a wrapper for it, so that
241 // the C runtime can call it.
242 if (F.getName() == "main") {
243 Main = &F;
244 LLVMContext &C = M.getContext();
245 Type *MainArgTys[] = {Type::getInt32Ty(C), PointerType::get(C, AddressSpace: 0)};
246 FunctionType *MainTy = FunctionType::get(Result: Type::getInt32Ty(C), Params: MainArgTys,
247 /*isVarArg=*/false);
248 if (shouldFixMainFunction(FuncTy: F.getFunctionType(), MainTy)) {
249 LLVM_DEBUG(dbgs() << "Found `main` function with incorrect type: "
250 << *F.getFunctionType() << "\n");
251 Value *Args[] = {PoisonValue::get(T: MainArgTys[0]),
252 PoisonValue::get(T: MainArgTys[1])};
253 CallMain = CallInst::Create(Ty: MainTy, Func: Main, Args, NameStr: "call_main");
254 Uses.push_back(Elt: std::make_pair(x&: CallMain, y: &F));
255 }
256 }
257 }
258
259 DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
260
261 for (auto &UseFunc : Uses) {
262 CallBase *CB = UseFunc.first;
263 Function *F = UseFunc.second;
264 FunctionType *Ty = CB->getFunctionType();
265
266 auto Pair = Wrappers.try_emplace(Key: std::make_pair(x&: F, y&: Ty));
267 if (Pair.second)
268 Pair.first->second = createWrapper(F, Ty);
269
270 Function *Wrapper = Pair.first->second;
271 if (!Wrapper)
272 continue;
273
274 CB->setCalledOperand(Wrapper);
275 }
276
277 // If we created a wrapper for main, rename the wrapper so that it's the
278 // one that gets called from startup.
279 if (CallMain) {
280 Main->setName("__original_main");
281 auto *MainWrapper =
282 cast<Function>(Val: CallMain->getCalledOperand()->stripPointerCasts());
283 delete CallMain;
284 if (Main->isDeclaration()) {
285 // The wrapper is not needed in this case as we don't need to export
286 // it to anyone else.
287 MainWrapper->eraseFromParent();
288 } else {
289 // Otherwise give the wrapper the same linkage as the original main
290 // function, so that it can be called from the same places.
291 MainWrapper->setName("main");
292 MainWrapper->setLinkage(Main->getLinkage());
293 MainWrapper->setVisibility(Main->getVisibility());
294 }
295 }
296
297 return true;
298}
299