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.catch(WebAssembly::CPP_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_lpad_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/CodeGen/MachineBasicBlock.h"
81 #include "llvm/CodeGen/Passes.h"
82 #include "llvm/CodeGen/WasmEHFuncInfo.h"
83 #include "llvm/IR/EHPersonalities.h"
84 #include "llvm/IR/IRBuilder.h"
85 #include "llvm/IR/IntrinsicsWebAssembly.h"
86 #include "llvm/InitializePasses.h"
87 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "wasmehprepare"
92 
93 namespace {
94 class WasmEHPrepare : public FunctionPass {
95   Type *LPadContextTy = nullptr; // type of 'struct _Unwind_LandingPadContext'
96   GlobalVariable *LPadContextGV = nullptr; // __wasm_lpad_context
97 
98   // Field addresses of struct _Unwind_LandingPadContext
99   Value *LPadIndexField = nullptr; // lpad_index field
100   Value *LSDAField = nullptr;      // lsda field
101   Value *SelectorField = nullptr;  // selector
102 
103   Function *ThrowF = nullptr;       // wasm.throw() intrinsic
104   Function *LPadIndexF = nullptr;   // wasm.landingpad.index() intrinsic
105   Function *LSDAF = nullptr;        // wasm.lsda() intrinsic
106   Function *GetExnF = nullptr;      // wasm.get.exception() intrinsic
107   Function *CatchF = nullptr;       // wasm.catch() intrinsic
108   Function *GetSelectorF = nullptr; // wasm.get.ehselector() intrinsic
109   FunctionCallee CallPersonalityF =
110       nullptr; // _Unwind_CallPersonality() wrapper
111 
112   bool prepareThrows(Function &F);
113   bool prepareEHPads(Function &F);
114   void prepareEHPad(BasicBlock *BB, bool NeedPersonality, unsigned Index = 0);
115 
116 public:
117   static char ID; // Pass identification, replacement for typeid
118 
119   WasmEHPrepare() : FunctionPass(ID) {}
120   bool doInitialization(Module &M) override;
121   bool runOnFunction(Function &F) override;
122 
123   StringRef getPassName() const override {
124     return "WebAssembly Exception handling preparation";
125   }
126 };
127 } // end anonymous namespace
128 
129 char WasmEHPrepare::ID = 0;
130 INITIALIZE_PASS_BEGIN(WasmEHPrepare, DEBUG_TYPE,
131                       "Prepare WebAssembly exceptions", false, false)
132 INITIALIZE_PASS_END(WasmEHPrepare, DEBUG_TYPE, "Prepare WebAssembly exceptions",
133                     false, false)
134 
135 FunctionPass *llvm::createWasmEHPass() { return new WasmEHPrepare(); }
136 
137 bool WasmEHPrepare::doInitialization(Module &M) {
138   IRBuilder<> IRB(M.getContext());
139   LPadContextTy = StructType::get(IRB.getInt32Ty(),   // lpad_index
140                                   IRB.getInt8PtrTy(), // lsda
141                                   IRB.getInt32Ty()    // selector
142   );
143   return false;
144 }
145 
146 // Erase the specified BBs if the BB does not have any remaining predecessors,
147 // and also all its dead children.
148 template <typename Container>
149 static void eraseDeadBBsAndChildren(const Container &BBs) {
150   SmallVector<BasicBlock *, 8> WL(BBs.begin(), BBs.end());
151   while (!WL.empty()) {
152     auto *BB = WL.pop_back_val();
153     if (!pred_empty(BB))
154       continue;
155     WL.append(succ_begin(BB), succ_end(BB));
156     DeleteDeadBlock(BB);
157   }
158 }
159 
160 bool WasmEHPrepare::runOnFunction(Function &F) {
161   bool Changed = false;
162   Changed |= prepareThrows(F);
163   Changed |= prepareEHPads(F);
164   return Changed;
165 }
166 
167 bool WasmEHPrepare::prepareThrows(Function &F) {
168   Module &M = *F.getParent();
169   IRBuilder<> IRB(F.getContext());
170   bool Changed = false;
171 
172   // wasm.throw() intinsic, which will be lowered to wasm 'throw' instruction.
173   ThrowF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_throw);
174   // Insert an unreachable instruction after a call to @llvm.wasm.throw and
175   // delete all following instructions within the BB, and delete all the dead
176   // children of the BB as well.
177   for (User *U : ThrowF->users()) {
178     // A call to @llvm.wasm.throw() is only generated from __cxa_throw()
179     // builtin call within libcxxabi, and cannot be an InvokeInst.
180     auto *ThrowI = cast<CallInst>(U);
181     if (ThrowI->getFunction() != &F)
182       continue;
183     Changed = true;
184     auto *BB = ThrowI->getParent();
185     SmallVector<BasicBlock *, 4> Succs(successors(BB));
186     BB->erase(std::next(BasicBlock::iterator(ThrowI)), BB->end());
187     IRB.SetInsertPoint(BB);
188     IRB.CreateUnreachable();
189     eraseDeadBBsAndChildren(Succs);
190   }
191 
192   return Changed;
193 }
194 
195 bool WasmEHPrepare::prepareEHPads(Function &F) {
196   Module &M = *F.getParent();
197   IRBuilder<> IRB(F.getContext());
198 
199   SmallVector<BasicBlock *, 16> CatchPads;
200   SmallVector<BasicBlock *, 16> CleanupPads;
201   for (BasicBlock &BB : F) {
202     if (!BB.isEHPad())
203       continue;
204     auto *Pad = BB.getFirstNonPHI();
205     if (isa<CatchPadInst>(Pad))
206       CatchPads.push_back(&BB);
207     else if (isa<CleanupPadInst>(Pad))
208       CleanupPads.push_back(&BB);
209   }
210   if (CatchPads.empty() && CleanupPads.empty())
211     return false;
212 
213   if (!F.hasPersonalityFn() ||
214       !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) {
215     report_fatal_error("Function '" + F.getName() +
216                        "' does not have a correct Wasm personality function "
217                        "'__gxx_wasm_personality_v0'");
218   }
219   assert(F.hasPersonalityFn() && "Personality function not found");
220 
221   // __wasm_lpad_context global variable.
222   // This variable should be thread local. If the target does not support TLS,
223   // we depend on CoalesceFeaturesAndStripAtomics to downgrade it to
224   // non-thread-local ones, in which case we don't allow this object to be
225   // linked with other objects using shared memory.
226   LPadContextGV = cast<GlobalVariable>(
227       M.getOrInsertGlobal("__wasm_lpad_context", LPadContextTy));
228   LPadContextGV->setThreadLocalMode(GlobalValue::GeneralDynamicTLSModel);
229 
230   LPadIndexField = IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 0,
231                                           "lpad_index_gep");
232   LSDAField =
233       IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 1, "lsda_gep");
234   SelectorField = IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 2,
235                                          "selector_gep");
236 
237   // wasm.landingpad.index() intrinsic, which is to specify landingpad index
238   LPadIndexF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_landingpad_index);
239   // wasm.lsda() intrinsic. Returns the address of LSDA table for the current
240   // function.
241   LSDAF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_lsda);
242   // wasm.get.exception() and wasm.get.ehselector() intrinsics. Calls to these
243   // are generated in clang.
244   GetExnF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_get_exception);
245   GetSelectorF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_get_ehselector);
246 
247   // wasm.catch() will be lowered down to wasm 'catch' instruction in
248   // instruction selection.
249   CatchF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_catch);
250 
251   // _Unwind_CallPersonality() wrapper function, which calls the personality
252   CallPersonalityF = M.getOrInsertFunction(
253       "_Unwind_CallPersonality", IRB.getInt32Ty(), IRB.getInt8PtrTy());
254   if (Function *F = dyn_cast<Function>(CallPersonalityF.getCallee()))
255     F->setDoesNotThrow();
256 
257   unsigned Index = 0;
258   for (auto *BB : CatchPads) {
259     auto *CPI = cast<CatchPadInst>(BB->getFirstNonPHI());
260     // In case of a single catch (...), we don't need to emit a personalify
261     // function call
262     if (CPI->arg_size() == 1 &&
263         cast<Constant>(CPI->getArgOperand(0))->isNullValue())
264       prepareEHPad(BB, false);
265     else
266       prepareEHPad(BB, true, Index++);
267   }
268 
269   // Cleanup pads don't need a personality function call.
270   for (auto *BB : CleanupPads)
271     prepareEHPad(BB, false);
272 
273   return true;
274 }
275 
276 // Prepare an EH pad for Wasm EH handling. If NeedPersonality is false, Index is
277 // ignored.
278 void WasmEHPrepare::prepareEHPad(BasicBlock *BB, bool NeedPersonality,
279                                  unsigned Index) {
280   assert(BB->isEHPad() && "BB is not an EHPad!");
281   IRBuilder<> IRB(BB->getContext());
282   IRB.SetInsertPoint(&*BB->getFirstInsertionPt());
283 
284   auto *FPI = cast<FuncletPadInst>(BB->getFirstNonPHI());
285   Instruction *GetExnCI = nullptr, *GetSelectorCI = nullptr;
286   for (auto &U : FPI->uses()) {
287     if (auto *CI = dyn_cast<CallInst>(U.getUser())) {
288       if (CI->getCalledOperand() == GetExnF)
289         GetExnCI = CI;
290       if (CI->getCalledOperand() == GetSelectorF)
291         GetSelectorCI = CI;
292     }
293   }
294 
295   // Cleanup pads do not have any of wasm.get.exception() or
296   // wasm.get.ehselector() calls. We need to do nothing.
297   if (!GetExnCI) {
298     assert(!GetSelectorCI &&
299            "wasm.get.ehselector() cannot exist w/o wasm.get.exception()");
300     return;
301   }
302 
303   // Replace wasm.get.exception intrinsic with wasm.catch intrinsic, which will
304   // be lowered to wasm 'catch' instruction. We do this mainly because
305   // instruction selection cannot handle wasm.get.exception intrinsic's token
306   // argument.
307   Instruction *CatchCI =
308       IRB.CreateCall(CatchF, {IRB.getInt32(WebAssembly::CPP_EXCEPTION)}, "exn");
309   GetExnCI->replaceAllUsesWith(CatchCI);
310   GetExnCI->eraseFromParent();
311 
312   // In case it is a catchpad with single catch (...) or a cleanuppad, we don't
313   // need to call personality function because we don't need a selector.
314   if (!NeedPersonality) {
315     if (GetSelectorCI) {
316       assert(GetSelectorCI->use_empty() &&
317              "wasm.get.ehselector() still has uses!");
318       GetSelectorCI->eraseFromParent();
319     }
320     return;
321   }
322   IRB.SetInsertPoint(CatchCI->getNextNode());
323 
324   // This is to create a map of <landingpad EH label, landingpad index> in
325   // SelectionDAGISel, which is to be used in EHStreamer to emit LSDA tables.
326   // Pseudocode: wasm.landingpad.index(Index);
327   IRB.CreateCall(LPadIndexF, {FPI, IRB.getInt32(Index)});
328 
329   // Pseudocode: __wasm_lpad_context.lpad_index = index;
330   IRB.CreateStore(IRB.getInt32(Index), LPadIndexField);
331 
332   auto *CPI = cast<CatchPadInst>(FPI);
333   // TODO Sometimes storing the LSDA address every time is not necessary, in
334   // case it is already set in a dominating EH pad and there is no function call
335   // between from that EH pad to here. Consider optimizing those cases.
336   // Pseudocode: __wasm_lpad_context.lsda = wasm.lsda();
337   IRB.CreateStore(IRB.CreateCall(LSDAF), LSDAField);
338 
339   // Pseudocode: _Unwind_CallPersonality(exn);
340   CallInst *PersCI = IRB.CreateCall(CallPersonalityF, CatchCI,
341                                     OperandBundleDef("funclet", CPI));
342   PersCI->setDoesNotThrow();
343 
344   // Pseudocode: int selector = __wasm_lpad_context.selector;
345   Instruction *Selector =
346       IRB.CreateLoad(IRB.getInt32Ty(), SelectorField, "selector");
347 
348   // Replace the return value from wasm.get.ehselector() with the selector value
349   // loaded from __wasm_lpad_context.selector.
350   assert(GetSelectorCI && "wasm.get.ehselector() call does not exist");
351   GetSelectorCI->replaceAllUsesWith(Selector);
352   GetSelectorCI->eraseFromParent();
353 }
354 
355 void llvm::calculateWasmEHInfo(const Function *F, WasmEHFuncInfo &EHInfo) {
356   // If an exception is not caught by a catchpad (i.e., it is a foreign
357   // exception), it will unwind to its parent catchswitch's unwind destination.
358   // We don't record an unwind destination for cleanuppads because every
359   // exception should be caught by it.
360   for (const auto &BB : *F) {
361     if (!BB.isEHPad())
362       continue;
363     const Instruction *Pad = BB.getFirstNonPHI();
364 
365     if (const auto *CatchPad = dyn_cast<CatchPadInst>(Pad)) {
366       const auto *UnwindBB = CatchPad->getCatchSwitch()->getUnwindDest();
367       if (!UnwindBB)
368         continue;
369       const Instruction *UnwindPad = UnwindBB->getFirstNonPHI();
370       if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UnwindPad))
371         // Currently there should be only one handler per a catchswitch.
372         EHInfo.setUnwindDest(&BB, *CatchSwitch->handlers().begin());
373       else // cleanuppad
374         EHInfo.setUnwindDest(&BB, UnwindBB);
375     }
376   }
377 }
378