llvm.org GIT mirror llvm / 91f4652
[WebAssembly] Add a pass to create wrappers for function bitcasts. WebAssembly requires caller and callee signatures to match exactly. In LLVM, there are a variety of circumstances where signatures may be mismatched in practice, and one can bitcast a function address to another type to call it as that type. This patch adds a pass which replaces bitcasted function addresses with wrappers to replace the bitcasts. This doesn't catch everything, but it does match many common cases. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@291315 91177308-0d34-0410-b5e6-96231b3b80d8 Dan Gohman 3 years ago
5 changed file(s) with 210 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
1616 WebAssemblyExplicitLocals.cpp
1717 WebAssemblyFastISel.cpp
1818 WebAssemblyFixIrreducibleControlFlow.cpp
19 WebAssemblyFixFunctionBitcasts.cpp
1920 WebAssemblyFrameLowering.cpp
2021 WebAssemblyISelDAGToDAG.cpp
2122 WebAssemblyISelLowering.cpp
2727 // LLVM IR passes.
2828 ModulePass *createWebAssemblyLowerEmscriptenEHSjLj(bool DoEH, bool DoSjLj);
2929 void initializeWebAssemblyLowerEmscriptenEHSjLjPass(PassRegistry &);
30 ModulePass *createWebAssemblyFixFunctionBitcasts();
3031 FunctionPass *createWebAssemblyOptimizeReturned();
3132
3233 // ISel and immediate followup passes.
0 //===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// \brief 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/Instructions.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 using namespace llvm;
34
35 #define DEBUG_TYPE "wasm-fix-function-bitcasts"
36
37 namespace {
38 class FixFunctionBitcasts final : public ModulePass {
39 StringRef getPassName() const override {
40 return "WebAssembly Fix Function Bitcasts";
41 }
42
43 void getAnalysisUsage(AnalysisUsage &AU) const override {
44 AU.setPreservesCFG();
45 ModulePass::getAnalysisUsage(AU);
46 }
47
48 bool runOnModule(Module &M) override;
49
50 SmallVector, 0> Uses;
51
52 public:
53 static char ID;
54 FixFunctionBitcasts() : ModulePass(ID) {}
55 };
56 } // End anonymous namespace
57
58 char FixFunctionBitcasts::ID = 0;
59 ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
60 return new FixFunctionBitcasts();
61 }
62
63 // Recursively descend the def-use lists from V to find non-bitcast users of
64 // bitcasts of V.
65 static void FindUses(Value *V, Function &F,
66 SmallVectorImpl> &Uses) {
67 for (Use &U : V->uses()) {
68 if (BitCastOperator *BC = dyn_cast(U.getUser()))
69 FindUses(BC, F, Uses);
70 else if (U.get()->getType() != F.getType())
71 Uses.push_back(std::make_pair(&U, &F));
72 }
73 }
74
75 // Create a wrapper function with type Ty that calls F (which may have a
76 // different type). Attempt to support common bitcasted function idioms:
77 // - Call with more arguments than needed: arguments are dropped
78 // - Call with fewer arguments than needed: arguments are filled in with undef
79 // - Return value is not needed: drop it
80 // - Return value needed but not present: supply an undef
81 static Function *CreateWrapper(Function *F, FunctionType *Ty) {
82 Module *M = F->getParent();
83
84 Function *Wrapper =
85 Function::Create(Ty, Function::PrivateLinkage, "bitcast", M);
86 BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
87
88 // Determine what arguments to pass.
89 SmallVector Args;
90 Function::arg_iterator AI = Wrapper->arg_begin();
91 FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
92 FunctionType::param_iterator PE = F->getFunctionType()->param_end();
93 for (; AI != Wrapper->arg_end() && PI != PE; ++AI, ++PI) {
94 assert(AI->getType() == *PI &&
95 "mismatched argument types not supported yet");
96 Args.push_back(&*AI);
97 }
98 for (; PI != PE; ++PI)
99 Args.push_back(UndefValue::get(*PI));
100
101 CallInst *Call = CallInst::Create(F, Args, "", BB);
102
103 // Determine what value to return.
104 if (Ty->getReturnType()->isVoidTy())
105 ReturnInst::Create(M->getContext(), BB);
106 else if (F->getFunctionType()->getReturnType()->isVoidTy())
107 ReturnInst::Create(M->getContext(), UndefValue::get(Ty->getReturnType()),
108 BB);
109 else if (F->getFunctionType()->getReturnType() == Ty->getReturnType())
110 ReturnInst::Create(M->getContext(), Call, BB);
111 else
112 llvm_unreachable("mismatched return types not supported yet");
113
114 return Wrapper;
115 }
116
117 bool FixFunctionBitcasts::runOnModule(Module &M) {
118 // Collect all the places that need wrappers.
119 for (Function &F : M)
120 FindUses(&F, F, Uses);
121
122 DenseMap, Function *> Wrappers;
123
124 for (auto &UseFunc : Uses) {
125 Use *U = UseFunc.first;
126 Function *F = UseFunc.second;
127 PointerType *PTy = cast(U->get()->getType());
128 FunctionType *Ty = dyn_cast(PTy->getElementType());
129
130 // If the function is casted to something like i8* as a "generic pointer"
131 // to be later casted to something else, we can't generate a wrapper for it.
132 // Just ignore such casts for now.
133 if (!Ty)
134 continue;
135
136 auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
137 if (Pair.second)
138 Pair.first->second = CreateWrapper(F, Ty);
139
140 if (isa(U->get()))
141 U->get()->replaceAllUsesWith(Pair.first->second);
142 else
143 U->set(Pair.first->second);
144 }
145
146 return true;
147 }
162162 // control specifically what gets lowered.
163163 addPass(createAtomicExpandPass(TM));
164164
165 // Fix function bitcasts, as WebAssembly requires caller and callee signatures
166 // to match.
167 addPass(createWebAssemblyFixFunctionBitcasts());
168
165169 // Optimize "returned" function attributes.
166170 if (getOptLevel() != CodeGenOpt::None)
167171 addPass(createWebAssemblyOptimizeReturned());
0 ; RUN: llc < %s -asm-verbose=false | FileCheck %s
1
2 ; Test that function pointer casts are replaced with wrappers.
3
4 target datalayout = "e-m:e-p:32:32-i64:64-n32:64-S128"
5 target triple = "wasm32-unknown-unknown"
6
7 ; CHECK-LABEL: test:
8 ; CHECK-NEXT: call .Lbitcast@FUNCTION{{$}}
9 ; CHECK-NEXT: call .Lbitcast.1@FUNCTION{{$}}
10 ; CHECK-NEXT: i32.const $push[[L0:[0-9]*]]=, 0
11 ; CHECK-NEXT: call .Lbitcast.2@FUNCTION, $pop[[L0]]{{$}}
12 ; CHECK-NEXT: i32.call $drop=, .Lbitcast.3@FUNCTION{{$}}
13 ; CHECK-NEXT: call foo2@FUNCTION{{$}}
14 ; CHECK-NEXT: call foo3@FUNCTION{{$}}
15 ; CHECK-NEXT: .endfunc
16
17 ; CHECK-LABEL: .Lbitcast:
18 ; CHECK-NEXT: .local i32
19 ; CHECK-NEXT: call has_i32_arg@FUNCTION, $0{{$}}
20 ; CHECK-NEXT: .endfunc
21
22 ; CHECK-LABEL: .Lbitcast.1:
23 ; CHECK-NEXT: call $drop=, has_i32_ret@FUNCTION{{$}}
24 ; CHECK-NEXT: .endfunc
25
26 ; CHECK-LABEL: .Lbitcast.2:
27 ; CHECK-NEXT: .param i32
28 ; CHECK-NEXT: call foo0@FUNCTION{{$}}
29 ; CHECK-NEXT: .endfunc
30
31 ; CHECK-LABEL: .Lbitcast.3:
32 ; CHECK-NEXT: .result i32
33 ; CHECK-NEXT: .local i32
34 ; CHECK-NEXT: call foo1@FUNCTION{{$}}
35 ; CHECK-NEXT: copy_local $push0=, $0
36 ; CHECK-NEXT: .endfunc
37
38 declare void @has_i32_arg(i32)
39 declare i32 @has_i32_ret()
40
41 declare void @foo0()
42 declare void @foo1()
43 declare void @foo2()
44 declare void @foo3()
45
46 define void @test() {
47 entry:
48 call void bitcast (void (i32)* @has_i32_arg to void ()*)()
49 call void bitcast (i32 ()* @has_i32_ret to void ()*)()
50 call void bitcast (void ()* @foo0 to void (i32)*)(i32 0)
51 %t = call i32 bitcast (void ()* @foo1 to i32 ()*)()
52 call void bitcast (void ()* @foo2 to void ()*)()
53 call void @foo3()
54 ret void
55 }