blob: 271f3d4568d92274692dba8ec4215da75a5bee19 [file] [log] [blame]
Heejin Ahn99d60e02018-05-31 22:02:34 +00001//===-- WasmEHPrepare - Prepare excepton handling for WebAssembly --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Heejin Ahn99d60e02018-05-31 22:02:34 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This transformation is designed for use by code generators which use
Heejin Ahnd6f48782019-01-30 03:21:57 +000010// WebAssembly exception handling scheme. This currently supports C++
11// exceptions.
Heejin Ahn99d60e02018-05-31 22:02:34 +000012//
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 ...
Heejin Ahnd6f48782019-01-30 03:21:57 +000026// exn = wasm.extract.exception();
Heejin Ahn99d60e02018-05-31 22:02:34 +000027// // Only add below in case it's not a single catch (...)
Heejin Ahnd6f48782019-01-30 03:21:57 +000028// wasm.landingpad.index(index);
Heejin Ahn99d60e02018-05-31 22:02:34 +000029// __wasm_lpad_context.lpad_index = index;
30// __wasm_lpad_context.lsda = wasm.lsda();
31// _Unwind_CallPersonality(exn);
Heejin Ahnd6f48782019-01-30 03:21:57 +000032// selector = __wasm.landingpad_context.selector;
Heejin Ahn99d60e02018-05-31 22:02:34 +000033// ...
34//
Heejin Ahn99d60e02018-05-31 22:02:34 +000035//
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
Heejin Ahnd6f48782019-01-30 03:21:57 +000039// transfered to WebAssembly 'catch' instruction.
Heejin Ahn99d60e02018-05-31 22:02:34 +000040//
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"
84#include "llvm/CodeGen/TargetLowering.h"
85#include "llvm/CodeGen/TargetSubtargetInfo.h"
Heejin Ahn33c3fce2018-06-19 00:26:39 +000086#include "llvm/CodeGen/WasmEHFuncInfo.h"
Heejin Ahn99d60e02018-05-31 22:02:34 +000087#include "llvm/IR/Dominators.h"
88#include "llvm/IR/IRBuilder.h"
89#include "llvm/IR/Intrinsics.h"
90#include "llvm/Pass.h"
91#include "llvm/Transforms/Utils/BasicBlockUtils.h"
92
93using namespace llvm;
94
95#define DEBUG_TYPE "wasmehprepare"
96
97namespace {
98class WasmEHPrepare : public FunctionPass {
99 Type *LPadContextTy = nullptr; // type of 'struct _Unwind_LandingPadContext'
100 GlobalVariable *LPadContextGV = nullptr; // __wasm_lpad_context
101
102 // Field addresses of struct _Unwind_LandingPadContext
103 Value *LPadIndexField = nullptr; // lpad_index field
104 Value *LSDAField = nullptr; // lsda field
105 Value *SelectorField = nullptr; // selector
106
Heejin Ahn095796a2018-11-16 00:47:18 +0000107 Function *ThrowF = nullptr; // wasm.throw() intrinsic
Heejin Ahnd6f48782019-01-30 03:21:57 +0000108 Function *RethrowF = nullptr; // wasm.rethrow() intrinsic
Heejin Ahn99d60e02018-05-31 22:02:34 +0000109 Function *LPadIndexF = nullptr; // wasm.landingpad.index() intrinsic
110 Function *LSDAF = nullptr; // wasm.lsda() intrinsic
111 Function *GetExnF = nullptr; // wasm.get.exception() intrinsic
Heejin Ahnd6f48782019-01-30 03:21:57 +0000112 Function *ExtractExnF = nullptr; // wasm.extract.exception() intrinsic
Heejin Ahn99d60e02018-05-31 22:02:34 +0000113 Function *GetSelectorF = nullptr; // wasm.get.ehselector() intrinsic
James Y Knightfadf2502019-01-31 21:51:58 +0000114 Function *CallPersonalityF = nullptr; // _Unwind_CallPersonality() wrapper
Heejin Ahn99d60e02018-05-31 22:02:34 +0000115
Heejin Ahn095796a2018-11-16 00:47:18 +0000116 bool prepareEHPads(Function &F);
117 bool prepareThrows(Function &F);
118
Heejin Ahnd6f48782019-01-30 03:21:57 +0000119 void prepareEHPad(BasicBlock *BB, bool NeedLSDA, unsigned Index = 0);
Heejin Ahn99d60e02018-05-31 22:02:34 +0000120 void prepareTerminateCleanupPad(BasicBlock *BB);
121
122public:
123 static char ID; // Pass identification, replacement for typeid
124
125 WasmEHPrepare() : FunctionPass(ID) {}
126
127 bool doInitialization(Module &M) override;
128 bool runOnFunction(Function &F) override;
129
130 StringRef getPassName() const override {
131 return "WebAssembly Exception handling preparation";
132 }
133};
134} // end anonymous namespace
135
136char WasmEHPrepare::ID = 0;
137INITIALIZE_PASS(WasmEHPrepare, DEBUG_TYPE, "Prepare WebAssembly exceptions",
Gabor Buella27c96d32018-06-01 07:47:46 +0000138 false, false)
Heejin Ahn99d60e02018-05-31 22:02:34 +0000139
140FunctionPass *llvm::createWasmEHPass() { return new WasmEHPrepare(); }
141
142bool WasmEHPrepare::doInitialization(Module &M) {
143 IRBuilder<> IRB(M.getContext());
144 LPadContextTy = StructType::get(IRB.getInt32Ty(), // lpad_index
145 IRB.getInt8PtrTy(), // lsda
146 IRB.getInt32Ty() // selector
147 );
148 return false;
149}
150
Heejin Ahn095796a2018-11-16 00:47:18 +0000151// Erase the specified BBs if the BB does not have any remaining predecessors,
152// and also all its dead children.
153template <typename Container>
154static void eraseDeadBBsAndChildren(const Container &BBs) {
155 SmallVector<BasicBlock *, 8> WL(BBs.begin(), BBs.end());
156 while (!WL.empty()) {
157 auto *BB = WL.pop_back_val();
158 if (pred_begin(BB) != pred_end(BB))
159 continue;
160 WL.append(succ_begin(BB), succ_end(BB));
161 DeleteDeadBlock(BB);
162 }
163}
164
Heejin Ahn99d60e02018-05-31 22:02:34 +0000165bool WasmEHPrepare::runOnFunction(Function &F) {
Heejin Ahn095796a2018-11-16 00:47:18 +0000166 bool Changed = false;
167 Changed |= prepareThrows(F);
168 Changed |= prepareEHPads(F);
169 return Changed;
170}
171
172bool WasmEHPrepare::prepareThrows(Function &F) {
173 Module &M = *F.getParent();
174 IRBuilder<> IRB(F.getContext());
175 bool Changed = false;
176
177 // wasm.throw() intinsic, which will be lowered to wasm 'throw' instruction.
178 ThrowF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_throw);
Heejin Ahnd6f48782019-01-30 03:21:57 +0000179 // wasm.rethrow() intinsic, which will be lowered to wasm 'rethrow'
180 // instruction.
181 RethrowF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_rethrow);
Heejin Ahn095796a2018-11-16 00:47:18 +0000182
Heejin Ahnd6f48782019-01-30 03:21:57 +0000183 // Insert an unreachable instruction after a call to @llvm.wasm.throw /
184 // @llvm.wasm.rethrow and delete all following instructions within the BB, and
185 // delete all the dead children of the BB as well.
186 for (auto L : {ThrowF->users(), RethrowF->users()}) {
187 for (User *U : L) {
188 // A call to @llvm.wasm.throw() is only generated from __cxa_throw()
189 // builtin call within libcxxabi, and cannot be an InvokeInst.
190 auto *ThrowI = cast<CallInst>(U);
191 if (ThrowI->getFunction() != &F)
192 continue;
193 Changed = true;
194 auto *BB = ThrowI->getParent();
195 SmallVector<BasicBlock *, 4> Succs(succ_begin(BB), succ_end(BB));
196 auto &InstList = BB->getInstList();
197 InstList.erase(std::next(BasicBlock::iterator(ThrowI)), InstList.end());
198 IRB.SetInsertPoint(BB);
199 IRB.CreateUnreachable();
200 eraseDeadBBsAndChildren(Succs);
201 }
Heejin Ahn095796a2018-11-16 00:47:18 +0000202 }
203
204 return Changed;
205}
206
207bool WasmEHPrepare::prepareEHPads(Function &F) {
208 Module &M = *F.getParent();
209 IRBuilder<> IRB(F.getContext());
210
Heejin Ahn99d60e02018-05-31 22:02:34 +0000211 SmallVector<BasicBlock *, 16> CatchPads;
212 SmallVector<BasicBlock *, 16> CleanupPads;
213 for (BasicBlock &BB : F) {
214 if (!BB.isEHPad())
215 continue;
216 auto *Pad = BB.getFirstNonPHI();
217 if (isa<CatchPadInst>(Pad))
218 CatchPads.push_back(&BB);
219 else if (isa<CleanupPadInst>(Pad))
220 CleanupPads.push_back(&BB);
221 }
222
223 if (CatchPads.empty() && CleanupPads.empty())
224 return false;
225 assert(F.hasPersonalityFn() && "Personality function not found");
226
Heejin Ahn99d60e02018-05-31 22:02:34 +0000227 // __wasm_lpad_context global variable
228 LPadContextGV = cast<GlobalVariable>(
229 M.getOrInsertGlobal("__wasm_lpad_context", LPadContextTy));
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
Heejin Ahn99d60e02018-05-31 22:02:34 +0000237 // 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
Heejin Ahnd6f48782019-01-30 03:21:57 +0000247 // wasm.extract.exception() is the same as wasm.get.exception() but it does
248 // not take a token argument. This will be lowered down to EXTRACT_EXCEPTION
249 // pseudo instruction in instruction selection, which will be expanded using
250 // 'br_on_exn' instruction later.
251 ExtractExnF =
252 Intrinsic::getDeclaration(&M, Intrinsic::wasm_extract_exception);
253
Heejin Ahn99d60e02018-05-31 22:02:34 +0000254 // _Unwind_CallPersonality() wrapper function, which calls the personality
James Y Knightfadf2502019-01-31 21:51:58 +0000255 CallPersonalityF = cast<Function>(M.getOrInsertFunction(
256 "_Unwind_CallPersonality", IRB.getInt32Ty(), IRB.getInt8PtrTy()));
257 CallPersonalityF->setDoesNotThrow();
Heejin Ahn99d60e02018-05-31 22:02:34 +0000258
Heejin Ahn99d60e02018-05-31 22:02:34 +0000259 unsigned Index = 0;
260 for (auto *BB : CatchPads) {
261 auto *CPI = cast<CatchPadInst>(BB->getFirstNonPHI());
262 // In case of a single catch (...), we don't need to emit LSDA
263 if (CPI->getNumArgOperands() == 1 &&
264 cast<Constant>(CPI->getArgOperand(0))->isNullValue())
Heejin Ahnd6f48782019-01-30 03:21:57 +0000265 prepareEHPad(BB, false);
Heejin Ahn99d60e02018-05-31 22:02:34 +0000266 else
Heejin Ahnd6f48782019-01-30 03:21:57 +0000267 prepareEHPad(BB, true, Index++);
Heejin Ahn99d60e02018-05-31 22:02:34 +0000268 }
269
Heejin Ahnd6f48782019-01-30 03:21:57 +0000270 // Cleanup pads don't need LSDA.
Heejin Ahn99d60e02018-05-31 22:02:34 +0000271 for (auto *BB : CleanupPads)
Heejin Ahnd6f48782019-01-30 03:21:57 +0000272 prepareEHPad(BB, false);
Heejin Ahn99d60e02018-05-31 22:02:34 +0000273
274 return true;
275}
276
Heejin Ahnd6f48782019-01-30 03:21:57 +0000277// Prepare an EH pad for Wasm EH handling. If NeedLSDA is false, Index is
278// ignored.
279void WasmEHPrepare::prepareEHPad(BasicBlock *BB, bool NeedLSDA,
280 unsigned Index) {
Heejin Ahn99d60e02018-05-31 22:02:34 +0000281 assert(BB->isEHPad() && "BB is not an EHPad!");
282 IRBuilder<> IRB(BB->getContext());
Heejin Ahn99d60e02018-05-31 22:02:34 +0000283 IRB.SetInsertPoint(&*BB->getFirstInsertionPt());
Heejin Ahnd6f48782019-01-30 03:21:57 +0000284
Heejin Ahn99d60e02018-05-31 22:02:34 +0000285 auto *FPI = cast<FuncletPadInst>(BB->getFirstNonPHI());
286 Instruction *GetExnCI = nullptr, *GetSelectorCI = nullptr;
287 for (auto &U : FPI->uses()) {
288 if (auto *CI = dyn_cast<CallInst>(U.getUser())) {
289 if (CI->getCalledValue() == GetExnF)
290 GetExnCI = CI;
Heejin Ahnd6f48782019-01-30 03:21:57 +0000291 if (CI->getCalledValue() == GetSelectorF)
Heejin Ahn99d60e02018-05-31 22:02:34 +0000292 GetSelectorCI = CI;
293 }
294 }
295
Heejin Ahnd6f48782019-01-30 03:21:57 +0000296 // Cleanup pads w/o __clang_call_terminate call do not have any of
297 // wasm.get.exception() or wasm.get.ehselector() calls. We need to do nothing.
298 if (!GetExnCI) {
299 assert(!GetSelectorCI &&
300 "wasm.get.ehselector() cannot exist w/o wasm.get.exception()");
301 return;
302 }
303
304 Instruction *ExtractExnCI = IRB.CreateCall(ExtractExnF, {}, "exn");
305 GetExnCI->replaceAllUsesWith(ExtractExnCI);
Heejin Ahn99d60e02018-05-31 22:02:34 +0000306 GetExnCI->eraseFromParent();
307
308 // In case it is a catchpad with single catch (...) or a cleanuppad, we don't
309 // need to call personality function because we don't need a selector.
Heejin Ahnd6f48782019-01-30 03:21:57 +0000310 if (!NeedLSDA) {
Heejin Ahn99d60e02018-05-31 22:02:34 +0000311 if (GetSelectorCI) {
312 assert(GetSelectorCI->use_empty() &&
313 "wasm.get.ehselector() still has uses!");
314 GetSelectorCI->eraseFromParent();
315 }
316 return;
317 }
Heejin Ahnd6f48782019-01-30 03:21:57 +0000318 IRB.SetInsertPoint(ExtractExnCI->getNextNode());
Heejin Ahn99d60e02018-05-31 22:02:34 +0000319
320 // This is to create a map of <landingpad EH label, landingpad index> in
321 // SelectionDAGISel, which is to be used in EHStreamer to emit LSDA tables.
322 // Pseudocode: wasm.landingpad.index(Index);
Heejin Ahn24faf852018-10-25 23:55:10 +0000323 IRB.CreateCall(LPadIndexF, {FPI, IRB.getInt32(Index)});
Heejin Ahn99d60e02018-05-31 22:02:34 +0000324
325 // Pseudocode: __wasm_lpad_context.lpad_index = index;
326 IRB.CreateStore(IRB.getInt32(Index), LPadIndexField);
327
328 // Store LSDA address only if this catchpad belongs to a top-level
329 // catchswitch. If there is another catchpad that dominates this pad, we don't
330 // need to store LSDA address again, because they are the same throughout the
331 // function and have been already stored before.
332 // TODO Can we not store LSDA address in user function but make libcxxabi
333 // compute it?
334 auto *CPI = cast<CatchPadInst>(FPI);
335 if (isa<ConstantTokenNone>(CPI->getCatchSwitch()->getParentPad()))
336 // Pseudocode: __wasm_lpad_context.lsda = wasm.lsda();
337 IRB.CreateStore(IRB.CreateCall(LSDAF), LSDAField);
338
339 // Pseudocode: _Unwind_CallPersonality(exn);
Heejin Ahnd6f48782019-01-30 03:21:57 +0000340 CallInst *PersCI = IRB.CreateCall(CallPersonalityF, ExtractExnCI,
341 OperandBundleDef("funclet", CPI));
Heejin Ahn99d60e02018-05-31 22:02:34 +0000342 PersCI->setDoesNotThrow();
343
344 // Pseudocode: int selector = __wasm.landingpad_context.selector;
345 Instruction *Selector = IRB.CreateLoad(SelectorField, "selector");
346
347 // Replace the return value from wasm.get.ehselector() with the selector value
348 // loaded from __wasm_lpad_context.selector.
349 assert(GetSelectorCI && "wasm.get.ehselector() call does not exist");
350 GetSelectorCI->replaceAllUsesWith(Selector);
351 GetSelectorCI->eraseFromParent();
352}
Heejin Ahn33c3fce2018-06-19 00:26:39 +0000353
354void llvm::calculateWasmEHInfo(const Function *F, WasmEHFuncInfo &EHInfo) {
Heejin Ahnd6f48782019-01-30 03:21:57 +0000355 // If an exception is not caught by a catchpad (i.e., it is a foreign
356 // exception), it will unwind to its parent catchswitch's unwind destination.
357 // We don't record an unwind destination for cleanuppads because every
358 // exception should be caught by it.
Heejin Ahn33c3fce2018-06-19 00:26:39 +0000359 for (const auto &BB : *F) {
360 if (!BB.isEHPad())
361 continue;
362 const Instruction *Pad = BB.getFirstNonPHI();
363
Heejin Ahn33c3fce2018-06-19 00:26:39 +0000364 if (const auto *CatchPad = dyn_cast<CatchPadInst>(Pad)) {
365 const auto *UnwindBB = CatchPad->getCatchSwitch()->getUnwindDest();
366 if (!UnwindBB)
367 continue;
368 const Instruction *UnwindPad = UnwindBB->getFirstNonPHI();
369 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UnwindPad))
370 // Currently there should be only one handler per a catchswitch.
371 EHInfo.setEHPadUnwindDest(&BB, *CatchSwitch->handlers().begin());
372 else // cleanuppad
373 EHInfo.setEHPadUnwindDest(&BB, UnwindBB);
374 }
375 }
376
377 // Record the unwind destination for invoke and cleanupret instructions.
378 for (const auto &BB : *F) {
379 const Instruction *TI = BB.getTerminator();
380 BasicBlock *UnwindBB = nullptr;
381 if (const auto *Invoke = dyn_cast<InvokeInst>(TI))
382 UnwindBB = Invoke->getUnwindDest();
383 else if (const auto *CleanupRet = dyn_cast<CleanupReturnInst>(TI))
384 UnwindBB = CleanupRet->getUnwindDest();
385 if (!UnwindBB)
386 continue;
387 const Instruction *UnwindPad = UnwindBB->getFirstNonPHI();
388 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UnwindPad))
389 // Currently there should be only one handler per a catchswitch.
390 EHInfo.setThrowUnwindDest(&BB, *CatchSwitch->handlers().begin());
391 else // cleanuppad
392 EHInfo.setThrowUnwindDest(&BB, UnwindBB);
393 }
394}