LLVM  10.0.0
WasmEHPrepare.cpp
Go to the documentation of this file.
1 //===-- WasmEHPrepare - Prepare excepton handling for WebAssembly --------===//
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 // This transformation is designed for use by code generators which use
10 // WebAssembly exception handling scheme. This currently supports C++
11 // exceptions.
12 //
13 // WebAssembly exception handling uses Windows exception IR for the middle level
14 // representation. This pass does the following transformation for every
15 // catchpad block:
16 // (In C-style pseudocode)
17 //
18 // - Before:
19 // catchpad ...
20 // exn = wasm.get.exception();
21 // selector = wasm.get.selector();
22 // ...
23 //
24 // - After:
25 // catchpad ...
26 // exn = wasm.extract.exception();
27 // // Only add below in case it's not a single catch (...)
28 // wasm.landingpad.index(index);
29 // __wasm_lpad_context.lpad_index = index;
30 // __wasm_lpad_context.lsda = wasm.lsda();
31 // _Unwind_CallPersonality(exn);
32 // selector = __wasm.landingpad_context.selector;
33 // ...
34 //
35 //
36 // * Background: Direct personality function call
37 // In WebAssembly EH, the VM is responsible for unwinding the stack once an
38 // exception is thrown. After the stack is unwound, the control flow is
39 // transfered to WebAssembly 'catch' instruction.
40 //
41 // Unwinding the stack is not done by libunwind but the VM, so the personality
42 // function in libcxxabi cannot be called from libunwind during the unwinding
43 // process. So after a catch instruction, we insert a call to a wrapper function
44 // in libunwind that in turn calls the real personality function.
45 //
46 // In Itanium EH, if the personality function decides there is no matching catch
47 // clause in a call frame and no cleanup action to perform, the unwinder doesn't
48 // stop there and continues unwinding. But in Wasm EH, the unwinder stops at
49 // every call frame with a catch intruction, after which the personality
50 // function is called from the compiler-generated user code here.
51 //
52 // In libunwind, we have this struct that serves as a communincation channel
53 // between the compiler-generated user code and the personality function in
54 // libcxxabi.
55 //
56 // struct _Unwind_LandingPadContext {
57 // uintptr_t lpad_index;
58 // uintptr_t lsda;
59 // uintptr_t selector;
60 // };
61 // struct _Unwind_LandingPadContext __wasm_lpad_context = ...;
62 //
63 // And this wrapper in libunwind calls the personality function.
64 //
65 // _Unwind_Reason_Code _Unwind_CallPersonality(void *exception_ptr) {
66 // struct _Unwind_Exception *exception_obj =
67 // (struct _Unwind_Exception *)exception_ptr;
68 // _Unwind_Reason_Code ret = __gxx_personality_v0(
69 // 1, _UA_CLEANUP_PHASE, exception_obj->exception_class, exception_obj,
70 // (struct _Unwind_Context *)__wasm_lpad_context);
71 // return ret;
72 // }
73 //
74 // We pass a landing pad index, and the address of LSDA for the current function
75 // to the wrapper function _Unwind_CallPersonality in libunwind, and we retrieve
76 // the selector after it returns.
77 //
78 //===----------------------------------------------------------------------===//
79 
80 #include "llvm/ADT/SetVector.h"
81 #include "llvm/ADT/Statistic.h"
82 #include "llvm/ADT/Triple.h"
83 #include "llvm/CodeGen/Passes.h"
87 #include "llvm/IR/Dominators.h"
88 #include "llvm/IR/IRBuilder.h"
89 #include "llvm/IR/Intrinsics.h"
90 #include "llvm/IR/IntrinsicsWebAssembly.h"
91 #include "llvm/InitializePasses.h"
92 #include "llvm/Pass.h"
94 
95 using namespace llvm;
96 
97 #define DEBUG_TYPE "wasmehprepare"
98 
99 namespace {
100 class WasmEHPrepare : public FunctionPass {
101  Type *LPadContextTy = nullptr; // type of 'struct _Unwind_LandingPadContext'
102  GlobalVariable *LPadContextGV = nullptr; // __wasm_lpad_context
103 
104  // Field addresses of struct _Unwind_LandingPadContext
105  Value *LPadIndexField = nullptr; // lpad_index field
106  Value *LSDAField = nullptr; // lsda field
107  Value *SelectorField = nullptr; // selector
108 
109  Function *ThrowF = nullptr; // wasm.throw() intrinsic
110  Function *LPadIndexF = nullptr; // wasm.landingpad.index() intrinsic
111  Function *LSDAF = nullptr; // wasm.lsda() intrinsic
112  Function *GetExnF = nullptr; // wasm.get.exception() intrinsic
113  Function *ExtractExnF = nullptr; // wasm.extract.exception() intrinsic
114  Function *GetSelectorF = nullptr; // wasm.get.ehselector() intrinsic
115  FunctionCallee CallPersonalityF =
116  nullptr; // _Unwind_CallPersonality() wrapper
117 
118  bool prepareEHPads(Function &F);
119  bool prepareThrows(Function &F);
120 
121  void prepareEHPad(BasicBlock *BB, bool NeedLSDA, unsigned Index = 0);
122  void prepareTerminateCleanupPad(BasicBlock *BB);
123 
124 public:
125  static char ID; // Pass identification, replacement for typeid
126 
127  WasmEHPrepare() : FunctionPass(ID) {}
128 
129  bool doInitialization(Module &M) override;
130  bool runOnFunction(Function &F) override;
131 
132  StringRef getPassName() const override {
133  return "WebAssembly Exception handling preparation";
134  }
135 };
136 } // end anonymous namespace
137 
138 char WasmEHPrepare::ID = 0;
139 INITIALIZE_PASS(WasmEHPrepare, DEBUG_TYPE, "Prepare WebAssembly exceptions",
140  false, false)
141 
142 FunctionPass *llvm::createWasmEHPass() { return new WasmEHPrepare(); }
143 
144 bool WasmEHPrepare::doInitialization(Module &M) {
145  IRBuilder<> IRB(M.getContext());
146  LPadContextTy = StructType::get(IRB.getInt32Ty(), // lpad_index
147  IRB.getInt8PtrTy(), // lsda
148  IRB.getInt32Ty() // selector
149  );
150  return false;
151 }
152 
153 // Erase the specified BBs if the BB does not have any remaining predecessors,
154 // and also all its dead children.
155 template <typename Container>
156 static void eraseDeadBBsAndChildren(const Container &BBs) {
157  SmallVector<BasicBlock *, 8> WL(BBs.begin(), BBs.end());
158  while (!WL.empty()) {
159  auto *BB = WL.pop_back_val();
160  if (pred_begin(BB) != pred_end(BB))
161  continue;
162  WL.append(succ_begin(BB), succ_end(BB));
163  DeleteDeadBlock(BB);
164  }
165 }
166 
168  bool Changed = false;
169  Changed |= prepareThrows(F);
170  Changed |= prepareEHPads(F);
171  return Changed;
172 }
173 
174 bool WasmEHPrepare::prepareThrows(Function &F) {
175  Module &M = *F.getParent();
176  IRBuilder<> IRB(F.getContext());
177  bool Changed = false;
178 
179  // wasm.throw() intinsic, which will be lowered to wasm 'throw' instruction.
180  ThrowF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_throw);
181  // Insert an unreachable instruction after a call to @llvm.wasm.throw and
182  // delete all following instructions within the BB, and delete all the dead
183  // children of the BB as well.
184  for (User *U : ThrowF->users()) {
185  // A call to @llvm.wasm.throw() is only generated from __cxa_throw()
186  // builtin call within libcxxabi, and cannot be an InvokeInst.
187  auto *ThrowI = cast<CallInst>(U);
188  if (ThrowI->getFunction() != &F)
189  continue;
190  Changed = true;
191  auto *BB = ThrowI->getParent();
193  auto &InstList = BB->getInstList();
194  InstList.erase(std::next(BasicBlock::iterator(ThrowI)), InstList.end());
195  IRB.SetInsertPoint(BB);
196  IRB.CreateUnreachable();
198  }
199 
200  return Changed;
201 }
202 
203 bool WasmEHPrepare::prepareEHPads(Function &F) {
204  Module &M = *F.getParent();
205  IRBuilder<> IRB(F.getContext());
206 
208  SmallVector<BasicBlock *, 16> CleanupPads;
209  for (BasicBlock &BB : F) {
210  if (!BB.isEHPad())
211  continue;
212  auto *Pad = BB.getFirstNonPHI();
213  if (isa<CatchPadInst>(Pad))
214  CatchPads.push_back(&BB);
215  else if (isa<CleanupPadInst>(Pad))
216  CleanupPads.push_back(&BB);
217  }
218 
219  if (CatchPads.empty() && CleanupPads.empty())
220  return false;
221  assert(F.hasPersonalityFn() && "Personality function not found");
222 
223  // __wasm_lpad_context global variable
224  LPadContextGV = cast<GlobalVariable>(
225  M.getOrInsertGlobal("__wasm_lpad_context", LPadContextTy));
226  LPadIndexField = IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 0,
227  "lpad_index_gep");
228  LSDAField =
229  IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 1, "lsda_gep");
230  SelectorField = IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 2,
231  "selector_gep");
232 
233  // wasm.landingpad.index() intrinsic, which is to specify landingpad index
234  LPadIndexF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_landingpad_index);
235  // wasm.lsda() intrinsic. Returns the address of LSDA table for the current
236  // function.
237  LSDAF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_lsda);
238  // wasm.get.exception() and wasm.get.ehselector() intrinsics. Calls to these
239  // are generated in clang.
240  GetExnF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_get_exception);
241  GetSelectorF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_get_ehselector);
242 
243  // wasm.extract.exception() is the same as wasm.get.exception() but it does
244  // not take a token argument. This will be lowered down to EXTRACT_EXCEPTION
245  // pseudo instruction in instruction selection, which will be expanded using
246  // 'br_on_exn' instruction later.
247  ExtractExnF =
248  Intrinsic::getDeclaration(&M, Intrinsic::wasm_extract_exception);
249 
250  // _Unwind_CallPersonality() wrapper function, which calls the personality
251  CallPersonalityF = M.getOrInsertFunction(
252  "_Unwind_CallPersonality", IRB.getInt32Ty(), IRB.getInt8PtrTy());
253  if (Function *F = dyn_cast<Function>(CallPersonalityF.getCallee()))
254  F->setDoesNotThrow();
255 
256  unsigned Index = 0;
257  for (auto *BB : CatchPads) {
258  auto *CPI = cast<CatchPadInst>(BB->getFirstNonPHI());
259  // In case of a single catch (...), we don't need to emit LSDA
260  if (CPI->getNumArgOperands() == 1 &&
261  cast<Constant>(CPI->getArgOperand(0))->isNullValue())
262  prepareEHPad(BB, false);
263  else
264  prepareEHPad(BB, true, Index++);
265  }
266 
267  // Cleanup pads don't need LSDA.
268  for (auto *BB : CleanupPads)
269  prepareEHPad(BB, false);
270 
271  return true;
272 }
273 
274 // Prepare an EH pad for Wasm EH handling. If NeedLSDA is false, Index is
275 // ignored.
276 void WasmEHPrepare::prepareEHPad(BasicBlock *BB, bool NeedLSDA,
277  unsigned Index) {
278  assert(BB->isEHPad() && "BB is not an EHPad!");
279  IRBuilder<> IRB(BB->getContext());
280  IRB.SetInsertPoint(&*BB->getFirstInsertionPt());
281 
282  auto *FPI = cast<FuncletPadInst>(BB->getFirstNonPHI());
283  Instruction *GetExnCI = nullptr, *GetSelectorCI = nullptr;
284  for (auto &U : FPI->uses()) {
285  if (auto *CI = dyn_cast<CallInst>(U.getUser())) {
286  if (CI->getCalledValue() == GetExnF)
287  GetExnCI = CI;
288  if (CI->getCalledValue() == GetSelectorF)
289  GetSelectorCI = CI;
290  }
291  }
292 
293  // Cleanup pads w/o __clang_call_terminate call do not have any of
294  // wasm.get.exception() or wasm.get.ehselector() calls. We need to do nothing.
295  if (!GetExnCI) {
296  assert(!GetSelectorCI &&
297  "wasm.get.ehselector() cannot exist w/o wasm.get.exception()");
298  return;
299  }
300 
301  Instruction *ExtractExnCI = IRB.CreateCall(ExtractExnF, {}, "exn");
302  GetExnCI->replaceAllUsesWith(ExtractExnCI);
303  GetExnCI->eraseFromParent();
304 
305  // In case it is a catchpad with single catch (...) or a cleanuppad, we don't
306  // need to call personality function because we don't need a selector.
307  if (!NeedLSDA) {
308  if (GetSelectorCI) {
309  assert(GetSelectorCI->use_empty() &&
310  "wasm.get.ehselector() still has uses!");
311  GetSelectorCI->eraseFromParent();
312  }
313  return;
314  }
315  IRB.SetInsertPoint(ExtractExnCI->getNextNode());
316 
317  // This is to create a map of <landingpad EH label, landingpad index> in
318  // SelectionDAGISel, which is to be used in EHStreamer to emit LSDA tables.
319  // Pseudocode: wasm.landingpad.index(Index);
320  IRB.CreateCall(LPadIndexF, {FPI, IRB.getInt32(Index)});
321 
322  // Pseudocode: __wasm_lpad_context.lpad_index = index;
323  IRB.CreateStore(IRB.getInt32(Index), LPadIndexField);
324 
325  // Store LSDA address only if this catchpad belongs to a top-level
326  // catchswitch. If there is another catchpad that dominates this pad, we don't
327  // need to store LSDA address again, because they are the same throughout the
328  // function and have been already stored before.
329  // TODO Can we not store LSDA address in user function but make libcxxabi
330  // compute it?
331  auto *CPI = cast<CatchPadInst>(FPI);
332  if (isa<ConstantTokenNone>(CPI->getCatchSwitch()->getParentPad()))
333  // Pseudocode: __wasm_lpad_context.lsda = wasm.lsda();
334  IRB.CreateStore(IRB.CreateCall(LSDAF), LSDAField);
335 
336  // Pseudocode: _Unwind_CallPersonality(exn);
337  CallInst *PersCI = IRB.CreateCall(CallPersonalityF, ExtractExnCI,
338  OperandBundleDef("funclet", CPI));
339  PersCI->setDoesNotThrow();
340 
341  // Pseudocode: int selector = __wasm.landingpad_context.selector;
342  Instruction *Selector =
343  IRB.CreateLoad(IRB.getInt32Ty(), SelectorField, "selector");
344 
345  // Replace the return value from wasm.get.ehselector() with the selector value
346  // loaded from __wasm_lpad_context.selector.
347  assert(GetSelectorCI && "wasm.get.ehselector() call does not exist");
348  GetSelectorCI->replaceAllUsesWith(Selector);
349  GetSelectorCI->eraseFromParent();
350 }
351 
353  // If an exception is not caught by a catchpad (i.e., it is a foreign
354  // exception), it will unwind to its parent catchswitch's unwind destination.
355  // We don't record an unwind destination for cleanuppads because every
356  // exception should be caught by it.
357  for (const auto &BB : *F) {
358  if (!BB.isEHPad())
359  continue;
360  const Instruction *Pad = BB.getFirstNonPHI();
361 
362  if (const auto *CatchPad = dyn_cast<CatchPadInst>(Pad)) {
363  const auto *UnwindBB = CatchPad->getCatchSwitch()->getUnwindDest();
364  if (!UnwindBB)
365  continue;
366  const Instruction *UnwindPad = UnwindBB->getFirstNonPHI();
367  if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UnwindPad))
368  // Currently there should be only one handler per a catchswitch.
369  EHInfo.setEHPadUnwindDest(&BB, *CatchSwitch->handlers().begin());
370  else // cleanuppad
371  EHInfo.setEHPadUnwindDest(&BB, UnwindBB);
372  }
373  }
374 }
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:288
This class represents lattice values for constants.
Definition: AllocatorList.h:23
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:170
This class represents a function call, abstracting a target machine&#39;s calling convention.
F(f)
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:32
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:273
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:245
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:346
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:102
static void eraseDeadBBsAndChildren(const Container &BBs)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:430
FunctionPass * createWasmEHPass()
createWasmEHPass - This pass adapts exception handling code to use WebAssembly&#39;s exception handling s...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1112
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:132
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:105
static bool runOnFunction(Function &F, bool PostInlining)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:196
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:223
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
void setEHPadUnwindDest(const BasicBlock *BB, const BasicBlock *Dest)
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:112
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:282
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:115
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:223
Iterator for intrusive lists based on ilist_node.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
OperandBundleDefT< Value * > OperandBundleDef
Definition: InstrTypes.h:1084
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:143
INITIALIZE_PASS(WasmEHPrepare, DEBUG_TYPE, "Prepare WebAssembly exceptions", false, false) FunctionPass *llvm
iterator_range< user_iterator > users()
Definition: Value.h:420
Constant * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
Definition: Module.cpp:204
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
void calculateWasmEHInfo(const Function *F, WasmEHFuncInfo &EHInfo)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition: BasicBlock.h:411
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
LLVM Value Representation.
Definition: Value.h:74
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
#define DEBUG_TYPE
void setDoesNotThrow()
Definition: InstrTypes.h:1720
This file describes how to lower LLVM code to machine code.