LLVM 24.0.0git
WebAssemblyFixFunctionBitcasts.cpp
Go to the documentation of this file.
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/Analysis.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/Module.h"
31#include "llvm/IR/Operator.h"
32#include "llvm/IR/PassManager.h"
33#include "llvm/Pass.h"
34#include "llvm/Support/Debug.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "wasm-fix-function-bitcasts"
39
40namespace {
41class WebAssemblyFixFunctionBitcastsLegacy final : public ModulePass {
42 StringRef getPassName() const override {
43 return "WebAssembly Fix Function Bitcasts";
44 }
45
46 void getAnalysisUsage(AnalysisUsage &AU) const override {
47 AU.setPreservesCFG();
49 }
50
51 bool runOnModule(Module &M) override;
52
53public:
54 static char ID;
55 WebAssemblyFixFunctionBitcastsLegacy() : ModulePass(ID) {}
56};
57} // End anonymous namespace
58
59char WebAssemblyFixFunctionBitcastsLegacy::ID = 0;
60INITIALIZE_PASS(WebAssemblyFixFunctionBitcastsLegacy, DEBUG_TYPE,
61 "Fix mismatching bitcasts for WebAssembly", false, false)
62
64 return new WebAssemblyFixFunctionBitcastsLegacy();
65}
66
67// Recursively descend the def-use lists from V to find non-bitcast users of
68// bitcasts of V.
69static void findUses(Value *V, Function &F,
70 SmallVectorImpl<std::pair<CallBase *, Function *>> &Uses) {
71 for (User *U : V->users()) {
72 if (auto *BC = dyn_cast<BitCastOperator>(U))
73 findUses(BC, F, Uses);
74 else if (auto *A = dyn_cast<GlobalAlias>(U))
75 findUses(A, F, Uses);
76 else if (auto *CB = dyn_cast<CallBase>(U)) {
77 Value *Callee = CB->getCalledOperand();
78 if (Callee != V)
79 // Skip calls where the function isn't the callee
80 continue;
81 if (CB->getFunctionType() == F.getFunctionType())
82 // Skip uses that are immediately called
83 continue;
84 Uses.push_back(std::make_pair(CB, &F));
85 }
86 }
87}
88
89// Create a wrapper function with type Ty that calls F (which may have a
90// different type). Attempt to support common bitcasted function idioms:
91// - Call with more arguments than needed: arguments are dropped
92// - Call with fewer arguments than needed: arguments are filled in with poison
93// - Return value is not needed: drop it
94// - Return value needed but not present: supply a poison value
95//
96// If the all the argument types of trivially castable to one another (i.e.
97// I32 vs pointer type) then we don't create a wrapper at all (return nullptr
98// instead).
99//
100// If there is a type mismatch that we know would result in an invalid wasm
101// module then generate wrapper that contains unreachable (i.e. abort at
102// runtime). Such programs are deep into undefined behaviour territory,
103// but we choose to fail at runtime rather than generate and invalid module
104// or fail at compiler time. The reason we delay the error is that we want
105// to support the CMake which expects to be able to compile and link programs
106// that refer to functions with entirely incorrect signatures (this is how
107// CMake detects the existence of a function in a toolchain).
108//
109// For bitcasts that involve struct types we don't know at this stage if they
110// would be equivalent at the wasm level and so we can't know if we need to
111// generate a wrapper.
113 Module *M = F->getParent();
114
116 F->getName() + "_bitcast", M);
117 Wrapper->setAttributes(F->getAttributes());
118 BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
119 const DataLayout &DL = BB->getDataLayout();
120 IRBuilder<> Builder(BB);
121
122 // Determine what arguments to pass.
124 Function::arg_iterator AI = Wrapper->arg_begin();
125 Function::arg_iterator AE = Wrapper->arg_end();
126 FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
127 FunctionType::param_iterator PE = F->getFunctionType()->param_end();
128 bool TypeMismatch = false;
129 bool WrapperNeeded = false;
130
131 Type *ExpectedRtnType = F->getFunctionType()->getReturnType();
132 Type *RtnType = Ty->getReturnType();
133
134 if ((F->getFunctionType()->getNumParams() != Ty->getNumParams()) ||
135 (F->getFunctionType()->isVarArg() != Ty->isVarArg()) ||
136 (ExpectedRtnType != RtnType))
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 Args.push_back(Builder.CreateBitOrPointerCast(AI, ParamType, "cast"));
148 } else if (ArgType->isStructTy() || ParamType->isStructTy()) {
149 LLVM_DEBUG(dbgs() << "createWrapper: struct param type in bitcast: "
150 << F->getName() << "\n");
151 WrapperNeeded = false;
152 } else {
153 LLVM_DEBUG(dbgs() << "createWrapper: arg type mismatch calling: "
154 << F->getName() << "\n");
155 LLVM_DEBUG(dbgs() << "Arg[" << Args.size() << "] Expected: "
156 << *ParamType << " Got: " << *ArgType << "\n");
157 TypeMismatch = true;
158 break;
159 }
160 }
161 }
162
163 if (WrapperNeeded && !TypeMismatch) {
164 for (; PI != PE; ++PI)
165 Args.push_back(PoisonValue::get(*PI));
166 if (F->isVarArg())
167 for (; AI != AE; ++AI)
168 Args.push_back(&*AI);
169
170 CallInst *Call = Builder.CreateCall(F, Args);
171
172 // Determine what value to return.
173 if (RtnType->isVoidTy()) {
174 Builder.CreateRetVoid();
175 } else if (ExpectedRtnType->isVoidTy()) {
176 LLVM_DEBUG(dbgs() << "Creating dummy return: " << *RtnType << "\n");
177 Builder.CreateRet(PoisonValue::get(RtnType));
178 } else if (RtnType == ExpectedRtnType) {
179 Builder.CreateRet(Call);
180 } else if (CastInst::isBitOrNoopPointerCastable(ExpectedRtnType, RtnType,
181 DL)) {
182 Builder.CreateRet(Builder.CreateBitOrPointerCast(Call, RtnType, "cast"));
183 } else if (RtnType->isStructTy() || ExpectedRtnType->isStructTy()) {
184 LLVM_DEBUG(dbgs() << "createWrapper: struct return type in bitcast: "
185 << F->getName() << "\n");
186 WrapperNeeded = false;
187 } else {
188 LLVM_DEBUG(dbgs() << "createWrapper: return type mismatch calling: "
189 << F->getName() << "\n");
190 LLVM_DEBUG(dbgs() << "Expected: " << *ExpectedRtnType
191 << " Got: " << *RtnType << "\n");
192 TypeMismatch = true;
193 }
194 }
195
196 if (TypeMismatch) {
197 // Create a new wrapper that simply contains `unreachable`.
198 Wrapper->eraseFromParent();
200 F->getName() + "_bitcast_invalid", M);
201 Wrapper->setAttributes(F->getAttributes());
202 IRBuilder<> Builder(BasicBlock::Create(M->getContext(), "body", Wrapper));
203 Builder.CreateUnreachable();
204 } else if (!WrapperNeeded) {
205 LLVM_DEBUG(dbgs() << "createWrapper: no wrapper needed: " << F->getName()
206 << "\n");
207 Wrapper->eraseFromParent();
208 return nullptr;
209 }
210 LLVM_DEBUG(dbgs() << "createWrapper: " << F->getName() << "\n");
211 return Wrapper;
212}
213
214// Test whether a main function with type FuncTy should be rewritten to have
215// type MainTy.
216static bool shouldFixMainFunction(FunctionType *FuncTy, FunctionType *MainTy) {
217 // Only fix the main function if it's the standard zero-arg form. That way,
218 // the standard cases will work as expected, and users will see signature
219 // mismatches from the linker for non-standard cases.
220 return FuncTy->getReturnType() == MainTy->getReturnType() &&
221 FuncTy->getNumParams() == 0 &&
222 !FuncTy->isVarArg();
223}
224
226 LLVM_DEBUG(dbgs() << "********** Fix Function Bitcasts **********\n");
227
228 Function *Main = nullptr;
229 CallInst *CallMain = nullptr;
231
232 // Collect all the places that need wrappers.
233 for (Function &F : M) {
234 // Skip to fix when the function is swiftcc or swifttailcc because these
235 // calling conventions allow bitcast type difference for swiftself,
236 // swifterror, and swiftasync.
237 if (F.getCallingConv() == CallingConv::Swift ||
238 F.getCallingConv() == CallingConv::SwiftTail)
239 continue;
240 findUses(&F, F, Uses);
241
242 // If we have a "main" function, and its type isn't
243 // "int main(int argc, char *argv[])", create an artificial call with it
244 // bitcasted to that type so that we generate a wrapper for it, so that
245 // the C runtime can call it.
246 if (F.getName() == "main") {
247 Main = &F;
248 LLVMContext &C = M.getContext();
249 Type *MainArgTys[] = {Type::getInt32Ty(C), PointerType::get(C, 0)};
250 FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys,
251 /*isVarArg=*/false);
252 if (shouldFixMainFunction(F.getFunctionType(), MainTy)) {
253 LLVM_DEBUG(dbgs() << "Found `main` function with incorrect type: "
254 << *F.getFunctionType() << "\n");
255 Value *Args[] = {PoisonValue::get(MainArgTys[0]),
256 PoisonValue::get(MainArgTys[1])};
257 CallMain = CallInst::Create(MainTy, Main, Args, "call_main");
258 Uses.push_back(std::make_pair(CallMain, &F));
259 }
260 }
261 }
262
264
265 for (auto &UseFunc : Uses) {
266 CallBase *CB = UseFunc.first;
267 Function *F = UseFunc.second;
268 FunctionType *Ty = CB->getFunctionType();
269
270 auto Pair = Wrappers.try_emplace(std::make_pair(F, Ty));
271 if (Pair.second)
272 Pair.first->second = createWrapper(F, Ty);
273
274 Function *Wrapper = Pair.first->second;
275 if (!Wrapper)
276 continue;
277
279 }
280
281 // If we created a wrapper for main, rename the wrapper so that it's the
282 // one that gets called from startup.
283 if (CallMain) {
284 Main->setName("__original_main");
285 auto *MainWrapper =
287 delete CallMain;
288 if (Main->isDeclaration()) {
289 // The wrapper is not needed in this case as we don't need to export
290 // it to anyone else.
291 MainWrapper->eraseFromParent();
292 } else {
293 // Otherwise give the wrapper the same linkage as the original main
294 // function, so that it can be called from the same places.
295 MainWrapper->setName("main");
296 MainWrapper->setLinkage(Main->getLinkage());
297 MainWrapper->setVisibility(Main->getVisibility());
298 }
299 }
300
301 return true;
302}
303
304bool WebAssemblyFixFunctionBitcastsLegacy::runOnModule(Module &M) {
305 return fixFunctionBitcasts(M);
306}
307
308PreservedAnalyses
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
Remove Loads Into Fake Uses
#define LLVM_DEBUG(...)
Definition Debug.h:119
static void findUses(Value *V, Function &F, SmallVectorImpl< std::pair< CallBase *, Function * > > &Uses)
static bool shouldFixMainFunction(FunctionType *FuncTy, FunctionType *MainTy)
static Function * createWrapper(Function *F, FunctionType *Ty)
static bool fixFunctionBitcasts(Module &M)
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Value * getCalledOperand() const
FunctionType * getFunctionType() const
void setCalledOperand(Value *V)
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
Type::subtype_iterator param_iterator
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
Argument * arg_iterator
Definition Function.h:73
VisibilityTypes getVisibility() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
LinkageTypes getLinkage() const
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition Pass.cpp:112
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:276
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
CallInst * Call
Pass manager infrastructure for declaring and invalidating analyses.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
ModulePass * createWebAssemblyFixFunctionBitcastsLegacyPass()
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39