blob: 1cf397dd060bb67cf53644782cbae92e7e9f9202 [file] [log] [blame]
Derek Schuffccdceda2016-08-18 15:27:25 +00001//=== WebAssemblyLowerEmscriptenEHSjLj.cpp - Lower exceptions for Emscripten =//
Derek Schufff41f67d2016-08-01 21:34:04 +00002//
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
Derek Schufff41f67d2016-08-01 21:34:04 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010/// This file lowers exception-related instructions and setjmp/longjmp
Heejin Ahnc0f18172016-09-01 21:05:15 +000011/// function calls in order to use Emscripten's JavaScript try and catch
12/// mechanism.
Derek Schufff41f67d2016-08-01 21:34:04 +000013///
Heejin Ahnc0f18172016-09-01 21:05:15 +000014/// To handle exceptions and setjmp/longjmps, this scheme relies on JavaScript's
15/// try and catch syntax and relevant exception-related libraries implemented
16/// in JavaScript glue code that will be produced by Emscripten. This is similar
17/// to the current Emscripten asm.js exception handling in fastcomp. For
18/// fastcomp's EH / SjLj scheme, see these files in fastcomp LLVM branch:
Derek Schufff41f67d2016-08-01 21:34:04 +000019/// (Location: https://github.com/kripken/emscripten-fastcomp)
20/// lib/Target/JSBackend/NaCl/LowerEmExceptionsPass.cpp
Heejin Ahnc0f18172016-09-01 21:05:15 +000021/// lib/Target/JSBackend/NaCl/LowerEmSetjmp.cpp
Derek Schufff41f67d2016-08-01 21:34:04 +000022/// lib/Target/JSBackend/JSBackend.cpp
23/// lib/Target/JSBackend/CallHandlers.h
24///
Heejin Ahnc0f18172016-09-01 21:05:15 +000025/// * Exception handling
26/// This pass lowers invokes and landingpads into library functions in JS glue
27/// code. Invokes are lowered into function wrappers called invoke wrappers that
28/// exist in JS side, which wraps the original function call with JS try-catch.
29/// If an exception occurred, cxa_throw() function in JS side sets some
30/// variables (see below) so we can check whether an exception occurred from
31/// wasm code and handle it appropriately.
Derek Schufff41f67d2016-08-01 21:34:04 +000032///
Heejin Ahnc0f18172016-09-01 21:05:15 +000033/// * Setjmp-longjmp handling
34/// This pass lowers setjmp to a reasonably-performant approach for emscripten.
35/// The idea is that each block with a setjmp is broken up into two parts: the
36/// part containing setjmp and the part right after the setjmp. The latter part
37/// is either reached from the setjmp, or later from a longjmp. To handle the
38/// longjmp, all calls that might longjmp are also called using invoke wrappers
39/// and thus JS / try-catch. JS longjmp() function also sets some variables so
40/// we can check / whether a longjmp occurred from wasm code. Each block with a
41/// function call that might longjmp is also split up after the longjmp call.
42/// After the longjmp call, we check whether a longjmp occurred, and if it did,
43/// which setjmp it corresponds to, and jump to the right post-setjmp block.
44/// We assume setjmp-longjmp handling always run after EH handling, which means
45/// we don't expect any exception-related instructions when SjLj runs.
46/// FIXME Currently this scheme does not support indirect call of setjmp,
47/// because of the limitation of the scheme itself. fastcomp does not support it
48/// either.
49///
50/// In detail, this pass does following things:
51///
Sam Clegg4791a662018-11-20 19:25:07 +000052/// 1) Assumes the existence of global variables: __THREW__, __threwValue
53/// __THREW__ and __threwValue will be set in invoke wrappers
Heejin Ahnc0f18172016-09-01 21:05:15 +000054/// in JS glue code. For what invoke wrappers are, refer to 3). These
55/// variables are used for both exceptions and setjmp/longjmps.
56/// __THREW__ indicates whether an exception or a longjmp occurred or not. 0
57/// means nothing occurred, 1 means an exception occurred, and other numbers
Heejin Ahn99bd16b2016-09-10 02:33:47 +000058/// mean a longjmp occurred. In the case of longjmp, __threwValue variable
Heejin Ahnc0f18172016-09-01 21:05:15 +000059/// indicates the corresponding setjmp buffer the longjmp corresponds to.
Heejin Ahnc0f18172016-09-01 21:05:15 +000060///
61/// * Exception handling
Derek Schufff41f67d2016-08-01 21:34:04 +000062///
Sam Clegg4791a662018-11-20 19:25:07 +000063/// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions
64/// at link time.
Sam Cleggb2486f12018-10-02 22:12:15 +000065/// The global variables in 1) will exist in wasm address space,
66/// but their values should be set in JS code, so these functions
Derek Schufff41f67d2016-08-01 21:34:04 +000067/// as interfaces to JS glue code. These functions are equivalent to the
68/// following JS functions, which actually exist in asm.js version of JS
69/// library.
70///
71/// function setThrew(threw, value) {
72/// if (__THREW__ == 0) {
73/// __THREW__ = threw;
Derek Schuffccdceda2016-08-18 15:27:25 +000074/// __threwValue = value;
Derek Schufff41f67d2016-08-01 21:34:04 +000075/// }
76/// }
Sam Clegg4791a662018-11-20 19:25:07 +000077//
78/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +000079///
Sam Clegg4791a662018-11-20 19:25:07 +000080/// In exception handling, getTempRet0 indicates the type of an exception
81/// caught, and in setjmp/longjmp, it means the second argument to longjmp
82/// function.
Derek Schufff41f67d2016-08-01 21:34:04 +000083///
84/// 3) Lower
85/// invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
86/// into
87/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +000088/// call @__invoke_SIG(func, arg1, arg2)
Derek Schufff41f67d2016-08-01 21:34:04 +000089/// %__THREW__.val = __THREW__;
90/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +000091/// if (%__THREW__.val == 1)
92/// goto %lpad
93/// else
94/// goto %invoke.cont
Derek Schufff41f67d2016-08-01 21:34:04 +000095/// SIG is a mangled string generated based on the LLVM IR-level function
96/// signature. After LLVM IR types are lowered to the target wasm types,
97/// the names for these wrappers will change based on wasm types as well,
98/// as in invoke_vi (function takes an int and returns void). The bodies of
99/// these wrappers will be generated in JS glue code, and inside those
100/// wrappers we use JS try-catch to generate actual exception effects. It
101/// also calls the original callee function. An example wrapper in JS code
102/// would look like this:
103/// function invoke_vi(index,a1) {
104/// try {
105/// Module["dynCall_vi"](index,a1); // This calls original callee
106/// } catch(e) {
107/// if (typeof e !== 'number' && e !== 'longjmp') throw e;
108/// asm["setThrew"](1, 0); // setThrew is called here
109/// }
110/// }
111/// If an exception is thrown, __THREW__ will be set to true in a wrapper,
112/// so we can jump to the right BB based on this value.
113///
114/// 4) Lower
115/// %val = landingpad catch c1 catch c2 catch c3 ...
116/// ... use %val ...
117/// into
Derek Schuff53b9af02016-08-09 00:29:55 +0000118/// %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
Sam Clegg4791a662018-11-20 19:25:07 +0000119/// %val = {%fmc, getTempRet0()}
Derek Schufff41f67d2016-08-01 21:34:04 +0000120/// ... use %val ...
121/// Here N is a number calculated based on the number of clauses.
Sam Clegg4791a662018-11-20 19:25:07 +0000122/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +0000123///
124/// 5) Lower
125/// resume {%a, %b}
126/// into
Derek Schuff53b9af02016-08-09 00:29:55 +0000127/// call @__resumeException(%a)
128/// where __resumeException() is a function in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +0000129///
Derek Schuff53b9af02016-08-09 00:29:55 +0000130/// 6) Lower
131/// call @llvm.eh.typeid.for(type) (intrinsic)
132/// into
133/// call @llvm_eh_typeid_for(type)
134/// llvm_eh_typeid_for function will be generated in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +0000135///
Heejin Ahnc0f18172016-09-01 21:05:15 +0000136/// * Setjmp / Longjmp handling
137///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000138/// In case calls to longjmp() exists
139///
140/// 1) Lower
141/// longjmp(buf, value)
142/// into
143/// emscripten_longjmp_jmpbuf(buf, value)
144/// emscripten_longjmp_jmpbuf will be lowered to emscripten_longjmp later.
145///
146/// In case calls to setjmp() exists
147///
148/// 2) In the function entry that calls setjmp, initialize setjmpTable and
Heejin Ahnc0f18172016-09-01 21:05:15 +0000149/// sejmpTableSize as follows:
150/// setjmpTableSize = 4;
151/// setjmpTable = (int *) malloc(40);
152/// setjmpTable[0] = 0;
153/// setjmpTable and setjmpTableSize are used in saveSetjmp() function in JS
154/// code.
155///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000156/// 3) Lower
Heejin Ahnc0f18172016-09-01 21:05:15 +0000157/// setjmp(buf)
158/// into
159/// setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
Sam Clegg4791a662018-11-20 19:25:07 +0000160/// setjmpTableSize = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000161/// For each dynamic setjmp call, setjmpTable stores its ID (a number which
162/// is incrementally assigned from 0) and its label (a unique number that
163/// represents each callsite of setjmp). When we need more entries in
164/// setjmpTable, it is reallocated in saveSetjmp() in JS code and it will
165/// return the new table address, and assign the new table size in
Sam Clegg4791a662018-11-20 19:25:07 +0000166/// setTempRet0(). saveSetjmp also stores the setjmp's ID into the buffer
167/// buf. A BB with setjmp is split into two after setjmp call in order to
168/// make the post-setjmp BB the possible destination of longjmp BB.
Heejin Ahnc0f18172016-09-01 21:05:15 +0000169///
Heejin Ahnc0f18172016-09-01 21:05:15 +0000170///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000171/// 4) Lower every call that might longjmp into
Heejin Ahnc0f18172016-09-01 21:05:15 +0000172/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000173/// call @__invoke_SIG(func, arg1, arg2)
Heejin Ahnc0f18172016-09-01 21:05:15 +0000174/// %__THREW__.val = __THREW__;
175/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000176/// if (%__THREW__.val != 0 & __threwValue != 0) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000177/// %label = testSetjmp(mem[%__THREW__.val], setjmpTable,
178/// setjmpTableSize);
179/// if (%label == 0)
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000180/// emscripten_longjmp(%__THREW__.val, __threwValue);
Sam Clegg4791a662018-11-20 19:25:07 +0000181/// setTempRet0(__threwValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000182/// } else {
183/// %label = -1;
184/// }
Sam Clegg4791a662018-11-20 19:25:07 +0000185/// longjmp_result = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000186/// switch label {
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000187/// label 1: goto post-setjmp BB 1
188/// label 2: goto post-setjmp BB 2
Heejin Ahnc0f18172016-09-01 21:05:15 +0000189/// ...
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000190/// default: goto splitted next BB
Heejin Ahnc0f18172016-09-01 21:05:15 +0000191/// }
Heejin Ahn0c68a872018-11-08 22:56:26 +0000192/// testSetjmp examines setjmpTable to see if there is a matching setjmp
193/// call. After calling an invoke wrapper, if a longjmp occurred, __THREW__
194/// will be the address of matching jmp_buf buffer and __threwValue be the
195/// second argument to longjmp. mem[__THREW__.val] is a setjmp ID that is
196/// stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to
197/// each setjmp callsite. Label 0 means this longjmp buffer does not
198/// correspond to one of the setjmp callsites in this function, so in this
199/// case we just chain the longjmp to the caller. (Here we call
200/// emscripten_longjmp, which is different from emscripten_longjmp_jmpbuf.
201/// emscripten_longjmp_jmpbuf takes jmp_buf as its first argument, while
202/// emscripten_longjmp takes an int. Both of them will eventually be lowered
203/// to emscripten_longjmp in s2wasm, but here we need two signatures - we
204/// can't translate an int value to a jmp_buf.)
205/// Label -1 means no longjmp occurred. Otherwise we jump to the right
206/// post-setjmp BB based on the label.
Heejin Ahnc0f18172016-09-01 21:05:15 +0000207///
Derek Schufff41f67d2016-08-01 21:34:04 +0000208///===----------------------------------------------------------------------===//
209
210#include "WebAssembly.h"
Derek Schuff53b9af02016-08-09 00:29:55 +0000211#include "llvm/IR/CallSite.h"
Heejin Ahnc0f18172016-09-01 21:05:15 +0000212#include "llvm/IR/Dominators.h"
Derek Schufff41f67d2016-08-01 21:34:04 +0000213#include "llvm/IR/IRBuilder.h"
Heejin Ahnc0f18172016-09-01 21:05:15 +0000214#include "llvm/Transforms/Utils/BasicBlockUtils.h"
215#include "llvm/Transforms/Utils/SSAUpdater.h"
Derek Schufff41f67d2016-08-01 21:34:04 +0000216
217using namespace llvm;
218
Derek Schuffccdceda2016-08-18 15:27:25 +0000219#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
Derek Schufff41f67d2016-08-01 21:34:04 +0000220
Derek Schuff66641322016-08-09 22:37:00 +0000221static cl::list<std::string>
Derek Schuffccdceda2016-08-18 15:27:25 +0000222 EHWhitelist("emscripten-cxx-exceptions-whitelist",
223 cl::desc("The list of function names in which Emscripten-style "
224 "exception handling is enabled (see emscripten "
225 "EMSCRIPTEN_CATCHING_WHITELIST options)"),
226 cl::CommaSeparated);
Derek Schuff66641322016-08-09 22:37:00 +0000227
Derek Schufff41f67d2016-08-01 21:34:04 +0000228namespace {
Derek Schuffccdceda2016-08-18 15:27:25 +0000229class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000230 bool EnableEH; // Enable exception handling
231 bool EnableSjLj; // Enable setjmp/longjmp handling
Derek Schuffccdceda2016-08-18 15:27:25 +0000232
Heejin Ahn18c56a02019-02-04 19:13:39 +0000233 GlobalVariable *ThrewGV = nullptr;
234 GlobalVariable *ThrewValueGV = nullptr;
235 Function *GetTempRet0Func = nullptr;
236 Function *SetTempRet0Func = nullptr;
237 Function *ResumeF = nullptr;
238 Function *EHTypeIDF = nullptr;
239 Function *EmLongjmpF = nullptr;
240 Function *EmLongjmpJmpbufF = nullptr;
241 Function *SaveSetjmpF = nullptr;
242 Function *TestSetjmpF = nullptr;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000243
Derek Schuffccdceda2016-08-18 15:27:25 +0000244 // __cxa_find_matching_catch_N functions.
245 // Indexed by the number of clauses in an original landingpad instruction.
246 DenseMap<int, Function *> FindMatchingCatches;
247 // Map of <function signature string, invoke_ wrappers>
248 StringMap<Function *> InvokeWrappers;
249 // Set of whitelisted function names for exception handling
250 std::set<std::string> EHWhitelistSet;
251
Mehdi Amini117296c2016-10-01 02:56:57 +0000252 StringRef getPassName() const override {
Derek Schufff41f67d2016-08-01 21:34:04 +0000253 return "WebAssembly Lower Emscripten Exceptions";
254 }
255
Derek Schuffccdceda2016-08-18 15:27:25 +0000256 bool runEHOnFunction(Function &F);
257 bool runSjLjOnFunction(Function &F);
Derek Schufff41f67d2016-08-01 21:34:04 +0000258 Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
259
Heejin Ahnc0f18172016-09-01 21:05:15 +0000260 template <typename CallOrInvoke> Value *wrapInvoke(CallOrInvoke *CI);
261 void wrapTestSetjmp(BasicBlock *BB, Instruction *InsertPt, Value *Threw,
262 Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
263 Value *&LongjmpResult, BasicBlock *&EndBB);
264 template <typename CallOrInvoke> Function *getInvokeWrapper(CallOrInvoke *CI);
265
Derek Schuffccdceda2016-08-18 15:27:25 +0000266 bool areAllExceptionsAllowed() const { return EHWhitelistSet.empty(); }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000267 bool canLongjmp(Module &M, const Value *Callee) const;
Guanzhong Chenb1cb9fd2019-08-16 18:21:08 +0000268 bool isEmAsmCall(Module &M, const Value *Callee) const;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000269
Heejin Ahnc0f18172016-09-01 21:05:15 +0000270 void rebuildSSA(Function &F);
Derek Schufff41f67d2016-08-01 21:34:04 +0000271
272public:
273 static char ID;
274
Heejin Ahnc0f18172016-09-01 21:05:15 +0000275 WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH = true, bool EnableSjLj = true)
Heejin Ahn18c56a02019-02-04 19:13:39 +0000276 : ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000277 EHWhitelistSet.insert(EHWhitelist.begin(), EHWhitelist.end());
Derek Schuff66641322016-08-09 22:37:00 +0000278 }
Derek Schufff41f67d2016-08-01 21:34:04 +0000279 bool runOnModule(Module &M) override;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000280
281 void getAnalysisUsage(AnalysisUsage &AU) const override {
282 AU.addRequired<DominatorTreeWrapperPass>();
283 }
Derek Schufff41f67d2016-08-01 21:34:04 +0000284};
285} // End anonymous namespace
286
Derek Schuffccdceda2016-08-18 15:27:25 +0000287char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
288INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
289 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
290 false, false)
291
Heejin Ahnc0f18172016-09-01 21:05:15 +0000292ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH,
293 bool EnableSjLj) {
294 return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj);
Derek Schufff41f67d2016-08-01 21:34:04 +0000295}
296
297static bool canThrow(const Value *V) {
298 if (const auto *F = dyn_cast<const Function>(V)) {
299 // Intrinsics cannot throw
300 if (F->isIntrinsic())
301 return false;
302 StringRef Name = F->getName();
303 // leave setjmp and longjmp (mostly) alone, we process them properly later
304 if (Name == "setjmp" || Name == "longjmp")
305 return false;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000306 return !F->doesNotThrow();
Derek Schufff41f67d2016-08-01 21:34:04 +0000307 }
Heejin Ahnb6cd5122016-08-24 22:53:00 +0000308 // not a function, so an indirect call - can throw, we can't tell
309 return true;
Derek Schufff41f67d2016-08-01 21:34:04 +0000310}
311
Sam Cleggb2486f12018-10-02 22:12:15 +0000312// Get a global variable with the given name. If it doesn't exist declare it,
313// which will generate an import and asssumes that it will exist at link time.
314static GlobalVariable *getGlobalVariableI32(Module &M, IRBuilder<> &IRB,
315 const char *Name) {
Sam Clegg28b3e992018-07-17 16:40:03 +0000316
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000317 auto *GV =
318 dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, IRB.getInt32Ty()));
Sam Clegg12011fa2019-04-04 01:43:21 +0000319 if (!GV)
320 report_fatal_error(Twine("unable to create global: ") + Name);
321
322 return GV;
Derek Schufff41f67d2016-08-01 21:34:04 +0000323}
324
325// Simple function name mangler.
326// This function simply takes LLVM's string representation of parameter types
Derek Schuff53b9af02016-08-09 00:29:55 +0000327// and concatenate them with '_'. There are non-alphanumeric characters but llc
328// is ok with it, and we need to postprocess these names after the lowering
329// phase anyway.
Derek Schufff41f67d2016-08-01 21:34:04 +0000330static std::string getSignature(FunctionType *FTy) {
331 std::string Sig;
332 raw_string_ostream OS(Sig);
333 OS << *FTy->getReturnType();
334 for (Type *ParamTy : FTy->params())
335 OS << "_" << *ParamTy;
336 if (FTy->isVarArg())
337 OS << "_...";
338 Sig = OS.str();
David Majnemerc7004902016-08-12 04:32:37 +0000339 Sig.erase(remove_if(Sig, isspace), Sig.end());
Derek Schuff53b9af02016-08-09 00:29:55 +0000340 // When s2wasm parses .s file, a comma means the end of an argument. So a
341 // mangled function name can contain any character but a comma.
342 std::replace(Sig.begin(), Sig.end(), ',', '.');
Derek Schufff41f67d2016-08-01 21:34:04 +0000343 return Sig;
344}
345
Heejin Ahnc0f18172016-09-01 21:05:15 +0000346// Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
347// This is because a landingpad instruction contains two more arguments, a
348// personality function and a cleanup bit, and __cxa_find_matching_catch_N
349// functions are named after the number of arguments in the original landingpad
350// instruction.
Derek Schuffccdceda2016-08-18 15:27:25 +0000351Function *
352WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
353 unsigned NumClauses) {
Derek Schufff41f67d2016-08-01 21:34:04 +0000354 if (FindMatchingCatches.count(NumClauses))
355 return FindMatchingCatches[NumClauses];
356 PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
357 SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
358 FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000359 Function *F = Function::Create(
360 FTy, GlobalValue::ExternalLinkage,
361 "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000362 FindMatchingCatches[NumClauses] = F;
363 return F;
364}
365
Heejin Ahnc0f18172016-09-01 21:05:15 +0000366// Generate invoke wrapper seqence with preamble and postamble
367// Preamble:
368// __THREW__ = 0;
369// Postamble:
370// %__THREW__.val = __THREW__; __THREW__ = 0;
371// Returns %__THREW__.val, which indicates whether an exception is thrown (or
372// whether longjmp occurred), for future use.
373template <typename CallOrInvoke>
374Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallOrInvoke *CI) {
375 LLVMContext &C = CI->getModule()->getContext();
376
377 // If we are calling a function that is noreturn, we must remove that
378 // attribute. The code we insert here does expect it to return, after we
379 // catch the exception.
380 if (CI->doesNotReturn()) {
381 if (auto *F = dyn_cast<Function>(CI->getCalledValue()))
382 F->removeFnAttr(Attribute::NoReturn);
Reid Klecknerb5180542017-03-21 16:57:19 +0000383 CI->removeAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000384 }
385
386 IRBuilder<> IRB(C);
387 IRB.SetInsertPoint(CI);
388
389 // Pre-invoke
390 // __THREW__ = 0;
391 IRB.CreateStore(IRB.getInt32(0), ThrewGV);
392
393 // Invoke function wrapper in JavaScript
394 SmallVector<Value *, 16> Args;
395 // Put the pointer to the callee as first argument, so it can be called
396 // within the invoke wrapper later
397 Args.push_back(CI->getCalledValue());
398 Args.append(CI->arg_begin(), CI->arg_end());
399 CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
400 NewCall->takeName(CI);
Keno Fischer5c3cdef2019-08-05 21:36:09 +0000401 NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000402 NewCall->setDebugLoc(CI->getDebugLoc());
403
404 // Because we added the pointer to the callee as first argument, all
405 // argument attribute indices have to be incremented by one.
Reid Kleckner7f720332017-04-13 00:58:09 +0000406 SmallVector<AttributeSet, 8> ArgAttributes;
Derek Schuff0db0ca32017-04-12 16:03:00 +0000407 const AttributeList &InvokeAL = CI->getAttributes();
408
Derek Schuff0db0ca32017-04-12 16:03:00 +0000409 // No attributes for the callee pointer.
Reid Kleckner7f720332017-04-13 00:58:09 +0000410 ArgAttributes.push_back(AttributeSet());
Derek Schuff0db0ca32017-04-12 16:03:00 +0000411 // Copy the argument attributes from the original
Heejin Ahn18c56a02019-02-04 19:13:39 +0000412 for (unsigned I = 0, E = CI->getNumArgOperands(); I < E; ++I)
413 ArgAttributes.push_back(InvokeAL.getParamAttributes(I));
Derek Schuff0db0ca32017-04-12 16:03:00 +0000414
Keno Fischer3c805d12019-08-03 21:38:19 +0000415 AttrBuilder FnAttrs(InvokeAL.getFnAttributes());
416 if (FnAttrs.contains(Attribute::AllocSize)) {
417 // The allocsize attribute (if any) referes to parameters by index and needs
418 // to be adjusted.
419 unsigned SizeArg;
420 Optional<unsigned> NEltArg;
421 std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs();
422 SizeArg += 1;
423 if (NEltArg.hasValue())
424 NEltArg = NEltArg.getValue() + 1;
425 FnAttrs.addAllocSizeAttr(SizeArg, NEltArg);
426 }
427
Heejin Ahnc0f18172016-09-01 21:05:15 +0000428 // Reconstruct the AttributesList based on the vector we constructed.
Reid Kleckner7f720332017-04-13 00:58:09 +0000429 AttributeList NewCallAL =
Keno Fischer3c805d12019-08-03 21:38:19 +0000430 AttributeList::get(C, AttributeSet::get(C, FnAttrs),
Reid Kleckner7f720332017-04-13 00:58:09 +0000431 InvokeAL.getRetAttributes(), ArgAttributes);
Derek Schuff0db0ca32017-04-12 16:03:00 +0000432 NewCall->setAttributes(NewCallAL);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000433
434 CI->replaceAllUsesWith(NewCall);
435
436 // Post-invoke
437 // %__THREW__.val = __THREW__; __THREW__ = 0;
James Y Knight14359ef2019-02-01 20:44:24 +0000438 Value *Threw =
439 IRB.CreateLoad(IRB.getInt32Ty(), ThrewGV, ThrewGV->getName() + ".val");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000440 IRB.CreateStore(IRB.getInt32(0), ThrewGV);
441 return Threw;
442}
443
444// Get matching invoke wrapper based on callee signature
445template <typename CallOrInvoke>
446Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallOrInvoke *CI) {
447 Module *M = CI->getModule();
Derek Schufff41f67d2016-08-01 21:34:04 +0000448 SmallVector<Type *, 16> ArgTys;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000449 Value *Callee = CI->getCalledValue();
Derek Schufff41f67d2016-08-01 21:34:04 +0000450 FunctionType *CalleeFTy;
451 if (auto *F = dyn_cast<Function>(Callee))
452 CalleeFTy = F->getFunctionType();
453 else {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000454 auto *CalleeTy = cast<PointerType>(Callee->getType())->getElementType();
Derek Schufff41f67d2016-08-01 21:34:04 +0000455 CalleeFTy = dyn_cast<FunctionType>(CalleeTy);
456 }
457
458 std::string Sig = getSignature(CalleeFTy);
459 if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
460 return InvokeWrappers[Sig];
461
462 // Put the pointer to the callee as first argument
463 ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
464 // Add argument types
465 ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
466
467 FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
468 CalleeFTy->isVarArg());
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000469 Function *F =
470 Function::Create(FTy, GlobalValue::ExternalLinkage, "__invoke_" + Sig, M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000471 InvokeWrappers[Sig] = F;
472 return F;
473}
474
Heejin Ahnc0f18172016-09-01 21:05:15 +0000475bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(Module &M,
476 const Value *Callee) const {
477 if (auto *CalleeF = dyn_cast<Function>(Callee))
478 if (CalleeF->isIntrinsic())
479 return false;
Heejin Ahn23d57102016-08-31 22:40:34 +0000480
Guanzhong Chenb88ebe82019-07-03 00:37:49 +0000481 // Attempting to transform inline assembly will result in something like:
482 // call void @__invoke_void(void ()* asm ...)
483 // which is invalid because inline assembly blocks do not have addresses
484 // and can't be passed by pointer. The result is a crash with illegal IR.
485 if (isa<InlineAsm>(Callee))
486 return false;
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000487 StringRef CalleeName = Callee->getName();
Guanzhong Chenb88ebe82019-07-03 00:37:49 +0000488
Heejin Ahnc0f18172016-09-01 21:05:15 +0000489 // The reason we include malloc/free here is to exclude the malloc/free
490 // calls generated in setjmp prep / cleanup routines.
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000491 if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free")
Heejin Ahn10a70862016-09-01 00:44:37 +0000492 return false;
493
Heejin Ahnc0f18172016-09-01 21:05:15 +0000494 // There are functions in JS glue code
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000495 if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" ||
496 CalleeName == "saveSetjmp" || CalleeName == "testSetjmp" ||
497 CalleeName == "getTempRet0" || CalleeName == "setTempRet0")
Heejin Ahnc0f18172016-09-01 21:05:15 +0000498 return false;
Heejin Ahn10a70862016-09-01 00:44:37 +0000499
Heejin Ahnc0f18172016-09-01 21:05:15 +0000500 // __cxa_find_matching_catch_N functions cannot longjmp
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000501 if (Callee->getName().startswith("__cxa_find_matching_catch_"))
Heejin Ahnc0f18172016-09-01 21:05:15 +0000502 return false;
503
504 // Exception-catching related functions
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000505 if (CalleeName == "__cxa_begin_catch" || CalleeName == "__cxa_end_catch" ||
506 CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" ||
507 CalleeName == "__clang_call_terminate")
Heejin Ahnc0f18172016-09-01 21:05:15 +0000508 return false;
509
510 // Otherwise we don't know
511 return true;
512}
513
Guanzhong Chenb1cb9fd2019-08-16 18:21:08 +0000514bool WebAssemblyLowerEmscriptenEHSjLj::isEmAsmCall(Module &M,
515 const Value *Callee) const {
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000516 StringRef CalleeName = Callee->getName();
Guanzhong Chenb1cb9fd2019-08-16 18:21:08 +0000517 // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>.
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000518 return CalleeName == "emscripten_asm_const_int" ||
519 CalleeName == "emscripten_asm_const_double" ||
520 CalleeName == "emscripten_asm_const_int_sync_on_main_thread" ||
521 CalleeName == "emscripten_asm_const_double_sync_on_main_thread" ||
522 CalleeName == "emscripten_asm_const_async_on_main_thread";
Guanzhong Chenb1cb9fd2019-08-16 18:21:08 +0000523}
524
Heejin Ahnc0f18172016-09-01 21:05:15 +0000525// Generate testSetjmp function call seqence with preamble and postamble.
526// The code this generates is equivalent to the following JavaScript code:
527// if (%__THREW__.val != 0 & threwValue != 0) {
528// %label = _testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
529// if (%label == 0)
530// emscripten_longjmp(%__THREW__.val, threwValue);
Sam Clegg4791a662018-11-20 19:25:07 +0000531// setTempRet0(threwValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000532// } else {
533// %label = -1;
534// }
Sam Clegg4791a662018-11-20 19:25:07 +0000535// %longjmp_result = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000536//
537// As output parameters. returns %label, %longjmp_result, and the BB the last
538// instruction (%longjmp_result = ...) is in.
539void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
540 BasicBlock *BB, Instruction *InsertPt, Value *Threw, Value *SetjmpTable,
541 Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
542 BasicBlock *&EndBB) {
543 Function *F = BB->getParent();
544 LLVMContext &C = BB->getModule()->getContext();
545 IRBuilder<> IRB(C);
546 IRB.SetInsertPoint(InsertPt);
547
548 // if (%__THREW__.val != 0 & threwValue != 0)
549 IRB.SetInsertPoint(BB);
550 BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
551 BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
552 BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
553 Value *ThrewCmp = IRB.CreateICmpNE(Threw, IRB.getInt32(0));
James Y Knight14359ef2019-02-01 20:44:24 +0000554 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
555 ThrewValueGV->getName() + ".val");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000556 Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
557 Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
558 IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
559
560 // %label = _testSetjmp(mem[%__THREW__.val], _setjmpTable, _setjmpTableSize);
561 // if (%label == 0)
562 IRB.SetInsertPoint(ThenBB1);
563 BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F);
564 BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
565 Value *ThrewInt = IRB.CreateIntToPtr(Threw, Type::getInt32PtrTy(C),
566 Threw->getName() + ".i32p");
James Y Knight14359ef2019-02-01 20:44:24 +0000567 Value *LoadedThrew = IRB.CreateLoad(IRB.getInt32Ty(), ThrewInt,
568 ThrewInt->getName() + ".loaded");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000569 Value *ThenLabel = IRB.CreateCall(
570 TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
571 Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
572 IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2);
573
574 // emscripten_longjmp(%__THREW__.val, threwValue);
575 IRB.SetInsertPoint(ThenBB2);
576 IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue});
577 IRB.CreateUnreachable();
578
Sam Clegg4791a662018-11-20 19:25:07 +0000579 // setTempRet0(threwValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000580 IRB.SetInsertPoint(EndBB2);
Sam Clegg4791a662018-11-20 19:25:07 +0000581 IRB.CreateCall(SetTempRet0Func, ThrewValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000582 IRB.CreateBr(EndBB1);
583
584 IRB.SetInsertPoint(ElseBB1);
585 IRB.CreateBr(EndBB1);
586
Sam Clegg4791a662018-11-20 19:25:07 +0000587 // longjmp_result = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000588 IRB.SetInsertPoint(EndBB1);
589 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
590 LabelPHI->addIncoming(ThenLabel, EndBB2);
591
592 LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
593
594 // Output parameter assignment
595 Label = LabelPHI;
596 EndBB = EndBB1;
Sam Clegg4791a662018-11-20 19:25:07 +0000597 LongjmpResult = IRB.CreateCall(GetTempRet0Func, None, "longjmp_result");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000598}
599
Heejin Ahnc0f18172016-09-01 21:05:15 +0000600void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
601 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
602 DT.recalculate(F); // CFG has been changed
603 SSAUpdater SSA;
604 for (BasicBlock &BB : F) {
605 for (Instruction &I : BB) {
Heejin Ahn173a3a52019-08-26 21:51:35 +0000606 SSA.Initialize(I.getType(), I.getName());
607 SSA.AddAvailableValue(&BB, &I);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000608 for (auto UI = I.use_begin(), UE = I.use_end(); UI != UE;) {
609 Use &U = *UI;
610 ++UI;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000611 auto *User = cast<Instruction>(U.getUser());
Heejin Ahn18c56a02019-02-04 19:13:39 +0000612 if (auto *UserPN = dyn_cast<PHINode>(User))
Heejin Ahnc0f18172016-09-01 21:05:15 +0000613 if (UserPN->getIncomingBlock(U) == &BB)
614 continue;
615
616 if (DT.dominates(&I, User))
617 continue;
618 SSA.RewriteUseAfterInsertions(U);
619 }
620 }
621 }
622}
623
624bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
Heejin Ahn569f0902019-01-09 23:05:21 +0000625 LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
626
Heejin Ahnc0f18172016-09-01 21:05:15 +0000627 LLVMContext &C = M.getContext();
628 IRBuilder<> IRB(C);
629
630 Function *SetjmpF = M.getFunction("setjmp");
631 Function *LongjmpF = M.getFunction("longjmp");
632 bool SetjmpUsed = SetjmpF && !SetjmpF->use_empty();
633 bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
634 bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed);
635
Sam Clegg4791a662018-11-20 19:25:07 +0000636 // Declare (or get) global variables __THREW__, __threwValue, and
637 // getTempRet0/setTempRet0 function which are used in common for both
638 // exception handling and setjmp/longjmp handling
Sam Cleggb2486f12018-10-02 22:12:15 +0000639 ThrewGV = getGlobalVariableI32(M, IRB, "__THREW__");
640 ThrewValueGV = getGlobalVariableI32(M, IRB, "__threwValue");
Sam Clegg4791a662018-11-20 19:25:07 +0000641 GetTempRet0Func =
642 Function::Create(FunctionType::get(IRB.getInt32Ty(), false),
643 GlobalValue::ExternalLinkage, "getTempRet0", &M);
644 SetTempRet0Func = Function::Create(
645 FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
646 GlobalValue::ExternalLinkage, "setTempRet0", &M);
647 GetTempRet0Func->setDoesNotThrow();
648 SetTempRet0Func->setDoesNotThrow();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000649
650 bool Changed = false;
651
652 // Exception handling
653 if (EnableEH) {
654 // Register __resumeException function
655 FunctionType *ResumeFTy =
656 FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
657 ResumeF = Function::Create(ResumeFTy, GlobalValue::ExternalLinkage,
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000658 "__resumeException", &M);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000659
660 // Register llvm_eh_typeid_for function
661 FunctionType *EHTypeIDTy =
662 FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
663 EHTypeIDF = Function::Create(EHTypeIDTy, GlobalValue::ExternalLinkage,
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000664 "llvm_eh_typeid_for", &M);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000665
666 for (Function &F : M) {
667 if (F.isDeclaration())
668 continue;
669 Changed |= runEHOnFunction(F);
670 }
671 }
672
673 // Setjmp/longjmp handling
674 if (DoSjLj) {
675 Changed = true; // We have setjmp or longjmp somewhere
676
Heejin Ahnc0f18172016-09-01 21:05:15 +0000677 if (LongjmpF) {
678 // Replace all uses of longjmp with emscripten_longjmp_jmpbuf, which is
679 // defined in JS code
680 EmLongjmpJmpbufF = Function::Create(LongjmpF->getFunctionType(),
681 GlobalValue::ExternalLinkage,
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000682 "emscripten_longjmp_jmpbuf", &M);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000683
684 LongjmpF->replaceAllUsesWith(EmLongjmpJmpbufF);
685 }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000686
Heejin Ahn0c68a872018-11-08 22:56:26 +0000687 if (SetjmpF) {
688 // Register saveSetjmp function
689 FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
690 SmallVector<Type *, 4> Params = {SetjmpFTy->getParamType(0),
691 IRB.getInt32Ty(), Type::getInt32PtrTy(C),
692 IRB.getInt32Ty()};
693 FunctionType *FTy =
694 FunctionType::get(Type::getInt32PtrTy(C), Params, false);
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000695 SaveSetjmpF =
696 Function::Create(FTy, GlobalValue::ExternalLinkage, "saveSetjmp", &M);
Heejin Ahn0c68a872018-11-08 22:56:26 +0000697
698 // Register testSetjmp function
699 Params = {IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()};
700 FTy = FunctionType::get(IRB.getInt32Ty(), Params, false);
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000701 TestSetjmpF =
702 Function::Create(FTy, GlobalValue::ExternalLinkage, "testSetjmp", &M);
Heejin Ahn0c68a872018-11-08 22:56:26 +0000703
704 FTy = FunctionType::get(IRB.getVoidTy(),
705 {IRB.getInt32Ty(), IRB.getInt32Ty()}, false);
706 EmLongjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000707 "emscripten_longjmp", &M);
Heejin Ahn0c68a872018-11-08 22:56:26 +0000708
709 // Only traverse functions that uses setjmp in order not to insert
710 // unnecessary prep / cleanup code in every function
711 SmallPtrSet<Function *, 8> SetjmpUsers;
712 for (User *U : SetjmpF->users()) {
713 auto *UI = cast<Instruction>(U);
714 SetjmpUsers.insert(UI->getFunction());
715 }
716 for (Function *F : SetjmpUsers)
717 runSjLjOnFunction(*F);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000718 }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000719 }
720
721 if (!Changed) {
722 // Delete unused global variables and functions
Heejin Ahnc0f18172016-09-01 21:05:15 +0000723 if (ResumeF)
724 ResumeF->eraseFromParent();
725 if (EHTypeIDF)
726 EHTypeIDF->eraseFromParent();
727 if (EmLongjmpF)
728 EmLongjmpF->eraseFromParent();
729 if (SaveSetjmpF)
730 SaveSetjmpF->eraseFromParent();
731 if (TestSetjmpF)
732 TestSetjmpF->eraseFromParent();
733 return false;
734 }
735
Derek Schufff41f67d2016-08-01 21:34:04 +0000736 return true;
737}
738
Derek Schuffccdceda2016-08-18 15:27:25 +0000739bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
Derek Schufff41f67d2016-08-01 21:34:04 +0000740 Module &M = *F.getParent();
Derek Schuff53b9af02016-08-09 00:29:55 +0000741 LLVMContext &C = F.getContext();
Derek Schuffccdceda2016-08-18 15:27:25 +0000742 IRBuilder<> IRB(C);
Derek Schufff41f67d2016-08-01 21:34:04 +0000743 bool Changed = false;
744 SmallVector<Instruction *, 64> ToErase;
745 SmallPtrSet<LandingPadInst *, 32> LandingPads;
Derek Schuff66641322016-08-09 22:37:00 +0000746 bool AllowExceptions =
Derek Schuffccdceda2016-08-18 15:27:25 +0000747 areAllExceptionsAllowed() || EHWhitelistSet.count(F.getName());
Derek Schufff41f67d2016-08-01 21:34:04 +0000748
749 for (BasicBlock &BB : F) {
750 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
751 if (!II)
752 continue;
753 Changed = true;
754 LandingPads.insert(II->getLandingPadInst());
Derek Schuffccdceda2016-08-18 15:27:25 +0000755 IRB.SetInsertPoint(II);
Derek Schufff41f67d2016-08-01 21:34:04 +0000756
Derek Schuff53b9af02016-08-09 00:29:55 +0000757 bool NeedInvoke = AllowExceptions && canThrow(II->getCalledValue());
758 if (NeedInvoke) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000759 // Wrap invoke with invoke wrapper and generate preamble/postamble
760 Value *Threw = wrapInvoke(II);
Derek Schufff41f67d2016-08-01 21:34:04 +0000761 ToErase.push_back(II);
762
Derek Schufff41f67d2016-08-01 21:34:04 +0000763 // Insert a branch based on __THREW__ variable
Heejin Ahnc0f18172016-09-01 21:05:15 +0000764 Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(1), "cmp");
765 IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
Derek Schufff41f67d2016-08-01 21:34:04 +0000766
767 } else {
768 // This can't throw, and we don't need this invoke, just replace it with a
769 // call+branch
Heejin Ahnc0f18172016-09-01 21:05:15 +0000770 SmallVector<Value *, 16> Args(II->arg_begin(), II->arg_end());
James Y Knight7976eb52019-02-01 20:43:25 +0000771 CallInst *NewCall =
772 IRB.CreateCall(II->getFunctionType(), II->getCalledValue(), Args);
Derek Schufff41f67d2016-08-01 21:34:04 +0000773 NewCall->takeName(II);
774 NewCall->setCallingConv(II->getCallingConv());
Derek Schufff41f67d2016-08-01 21:34:04 +0000775 NewCall->setDebugLoc(II->getDebugLoc());
Derek Schuff53b9af02016-08-09 00:29:55 +0000776 NewCall->setAttributes(II->getAttributes());
Derek Schufff41f67d2016-08-01 21:34:04 +0000777 II->replaceAllUsesWith(NewCall);
778 ToErase.push_back(II);
779
Derek Schuffccdceda2016-08-18 15:27:25 +0000780 IRB.CreateBr(II->getNormalDest());
Derek Schufff41f67d2016-08-01 21:34:04 +0000781
782 // Remove any PHI node entries from the exception destination
783 II->getUnwindDest()->removePredecessor(&BB);
784 }
785 }
786
787 // Process resume instructions
788 for (BasicBlock &BB : F) {
789 // Scan the body of the basic block for resumes
790 for (Instruction &I : BB) {
791 auto *RI = dyn_cast<ResumeInst>(&I);
792 if (!RI)
793 continue;
794
795 // Split the input into legal values
796 Value *Input = RI->getValue();
Derek Schuffccdceda2016-08-18 15:27:25 +0000797 IRB.SetInsertPoint(RI);
798 Value *Low = IRB.CreateExtractValue(Input, 0, "low");
Derek Schuff53b9af02016-08-09 00:29:55 +0000799 // Create a call to __resumeException function
Heejin Ahnc0f18172016-09-01 21:05:15 +0000800 IRB.CreateCall(ResumeF, {Low});
Derek Schufff41f67d2016-08-01 21:34:04 +0000801 // Add a terminator to the block
Derek Schuffccdceda2016-08-18 15:27:25 +0000802 IRB.CreateUnreachable();
Derek Schufff41f67d2016-08-01 21:34:04 +0000803 ToErase.push_back(RI);
804 }
805 }
806
Derek Schuff53b9af02016-08-09 00:29:55 +0000807 // Process llvm.eh.typeid.for intrinsics
808 for (BasicBlock &BB : F) {
809 for (Instruction &I : BB) {
810 auto *CI = dyn_cast<CallInst>(&I);
811 if (!CI)
812 continue;
813 const Function *Callee = CI->getCalledFunction();
814 if (!Callee)
815 continue;
816 if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
817 continue;
818
Derek Schuffccdceda2016-08-18 15:27:25 +0000819 IRB.SetInsertPoint(CI);
Derek Schuff53b9af02016-08-09 00:29:55 +0000820 CallInst *NewCI =
Derek Schuffccdceda2016-08-18 15:27:25 +0000821 IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
Derek Schuff53b9af02016-08-09 00:29:55 +0000822 CI->replaceAllUsesWith(NewCI);
823 ToErase.push_back(CI);
824 }
825 }
826
Hiroshi Inouec3969642017-06-30 07:17:53 +0000827 // Look for orphan landingpads, can occur in blocks with no predecessors
Derek Schufff41f67d2016-08-01 21:34:04 +0000828 for (BasicBlock &BB : F) {
829 Instruction *I = BB.getFirstNonPHI();
830 if (auto *LPI = dyn_cast<LandingPadInst>(I))
831 LandingPads.insert(LPI);
832 }
833
834 // Handle all the landingpad for this function together, as multiple invokes
835 // may share a single lp
836 for (LandingPadInst *LPI : LandingPads) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000837 IRB.SetInsertPoint(LPI);
Derek Schufff41f67d2016-08-01 21:34:04 +0000838 SmallVector<Value *, 16> FMCArgs;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000839 for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
840 Constant *Clause = LPI->getClause(I);
Derek Schufff41f67d2016-08-01 21:34:04 +0000841 // As a temporary workaround for the lack of aggregate varargs support
842 // in the interface between JS and wasm, break out filter operands into
843 // their component elements.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000844 if (LPI->isFilter(I)) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000845 auto *ATy = cast<ArrayType>(Clause->getType());
Heejin Ahn18c56a02019-02-04 19:13:39 +0000846 for (unsigned J = 0, E = ATy->getNumElements(); J < E; ++J) {
847 Value *EV = IRB.CreateExtractValue(Clause, makeArrayRef(J), "filter");
Derek Schufff41f67d2016-08-01 21:34:04 +0000848 FMCArgs.push_back(EV);
849 }
850 } else
851 FMCArgs.push_back(Clause);
852 }
853
Derek Schuff53b9af02016-08-09 00:29:55 +0000854 // Create a call to __cxa_find_matching_catch_N function
Derek Schufff41f67d2016-08-01 21:34:04 +0000855 Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
Derek Schuffccdceda2016-08-18 15:27:25 +0000856 CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
Derek Schufff41f67d2016-08-01 21:34:04 +0000857 Value *Undef = UndefValue::get(LPI->getType());
Derek Schuffccdceda2016-08-18 15:27:25 +0000858 Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
Sam Clegg4791a662018-11-20 19:25:07 +0000859 Value *TempRet0 = IRB.CreateCall(GetTempRet0Func, None, "tempret0");
Derek Schuffccdceda2016-08-18 15:27:25 +0000860 Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
Derek Schufff41f67d2016-08-01 21:34:04 +0000861
862 LPI->replaceAllUsesWith(Pair1);
863 ToErase.push_back(LPI);
864 }
865
866 // Erase everything we no longer need in this function
867 for (Instruction *I : ToErase)
868 I->eraseFromParent();
869
870 return Changed;
871}
Derek Schuffccdceda2016-08-18 15:27:25 +0000872
873bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000874 Module &M = *F.getParent();
875 LLVMContext &C = F.getContext();
876 IRBuilder<> IRB(C);
877 SmallVector<Instruction *, 64> ToErase;
878 // Vector of %setjmpTable values
879 std::vector<Instruction *> SetjmpTableInsts;
880 // Vector of %setjmpTableSize values
881 std::vector<Instruction *> SetjmpTableSizeInsts;
882
883 // Setjmp preparation
884
885 // This instruction effectively means %setjmpTableSize = 4.
886 // We create this as an instruction intentionally, and we don't want to fold
887 // this instruction to a constant 4, because this value will be used in
888 // SSAUpdater.AddAvailableValue(...) later.
889 BasicBlock &EntryBB = F.getEntryBlock();
890 BinaryOperator *SetjmpTableSize = BinaryOperator::Create(
891 Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize",
892 &*EntryBB.getFirstInsertionPt());
893 // setjmpTable = (int *) malloc(40);
894 Instruction *SetjmpTable = CallInst::CreateMalloc(
895 SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
896 nullptr, nullptr, "setjmpTable");
897 // setjmpTable[0] = 0;
898 IRB.SetInsertPoint(SetjmpTableSize);
899 IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
900 SetjmpTableInsts.push_back(SetjmpTable);
901 SetjmpTableSizeInsts.push_back(SetjmpTableSize);
902
903 // Setjmp transformation
904 std::vector<PHINode *> SetjmpRetPHIs;
905 Function *SetjmpF = M.getFunction("setjmp");
906 for (User *U : SetjmpF->users()) {
907 auto *CI = dyn_cast<CallInst>(U);
908 if (!CI)
909 report_fatal_error("Does not support indirect calls to setjmp");
910
911 BasicBlock *BB = CI->getParent();
912 if (BB->getParent() != &F) // in other function
913 continue;
914
915 // The tail is everything right after the call, and will be reached once
916 // when setjmp is called, and later when longjmp returns to the setjmp
917 BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
918 // Add a phi to the tail, which will be the output of setjmp, which
919 // indicates if this is the first call or a longjmp back. The phi directly
920 // uses the right value based on where we arrive from
921 IRB.SetInsertPoint(Tail->getFirstNonPHI());
922 PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
923
924 // setjmp initial call returns 0
925 SetjmpRet->addIncoming(IRB.getInt32(0), BB);
926 // The proper output is now this, not the setjmp call itself
927 CI->replaceAllUsesWith(SetjmpRet);
928 // longjmp returns to the setjmp will add themselves to this phi
929 SetjmpRetPHIs.push_back(SetjmpRet);
930
931 // Fix call target
932 // Our index in the function is our place in the array + 1 to avoid index
933 // 0, because index 0 means the longjmp is not ours to handle.
934 IRB.SetInsertPoint(CI);
935 Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
936 SetjmpTable, SetjmpTableSize};
937 Instruction *NewSetjmpTable =
938 IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
939 Instruction *NewSetjmpTableSize =
Sam Clegg4791a662018-11-20 19:25:07 +0000940 IRB.CreateCall(GetTempRet0Func, None, "setjmpTableSize");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000941 SetjmpTableInsts.push_back(NewSetjmpTable);
942 SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
943 ToErase.push_back(CI);
944 }
945
946 // Update each call that can longjmp so it can return to a setjmp where
947 // relevant.
948
949 // Because we are creating new BBs while processing and don't want to make
950 // all these newly created BBs candidates again for longjmp processing, we
951 // first make the vector of candidate BBs.
952 std::vector<BasicBlock *> BBs;
953 for (BasicBlock &BB : F)
954 BBs.push_back(&BB);
955
956 // BBs.size() will change within the loop, so we query it every time
Heejin Ahn18c56a02019-02-04 19:13:39 +0000957 for (unsigned I = 0; I < BBs.size(); I++) {
958 BasicBlock *BB = BBs[I];
Heejin Ahnc0f18172016-09-01 21:05:15 +0000959 for (Instruction &I : *BB) {
960 assert(!isa<InvokeInst>(&I));
961 auto *CI = dyn_cast<CallInst>(&I);
962 if (!CI)
963 continue;
964
965 const Value *Callee = CI->getCalledValue();
966 if (!canLongjmp(M, Callee))
967 continue;
Guanzhong Chenb1cb9fd2019-08-16 18:21:08 +0000968 if (isEmAsmCall(M, Callee))
969 report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
970 F.getName() +
971 ". Please consider using EM_JS, or move the "
972 "EM_ASM into another function.",
973 false);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000974
975 Value *Threw = nullptr;
976 BasicBlock *Tail;
Heejin Ahn49e7ee42019-09-03 22:26:49 +0000977 if (Callee->getName().startswith("__invoke_")) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000978 // If invoke wrapper has already been generated for this call in
979 // previous EH phase, search for the load instruction
980 // %__THREW__.val = __THREW__;
981 // in postamble after the invoke wrapper call
982 LoadInst *ThrewLI = nullptr;
983 StoreInst *ThrewResetSI = nullptr;
984 for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
985 I != IE; ++I) {
986 if (auto *LI = dyn_cast<LoadInst>(I))
987 if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
988 if (GV == ThrewGV) {
989 Threw = ThrewLI = LI;
990 break;
991 }
992 }
993 // Search for the store instruction after the load above
994 // __THREW__ = 0;
995 for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
996 I != IE; ++I) {
997 if (auto *SI = dyn_cast<StoreInst>(I))
998 if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand()))
999 if (GV == ThrewGV && SI->getValueOperand() == IRB.getInt32(0)) {
1000 ThrewResetSI = SI;
1001 break;
1002 }
1003 }
1004 assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
1005 assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
1006 Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
1007
1008 } else {
1009 // Wrap call with invoke wrapper and generate preamble/postamble
1010 Threw = wrapInvoke(CI);
1011 ToErase.push_back(CI);
1012 Tail = SplitBlock(BB, CI->getNextNode());
1013 }
1014
1015 // We need to replace the terminator in Tail - SplitBlock makes BB go
1016 // straight to Tail, we need to check if a longjmp occurred, and go to the
1017 // right setjmp-tail if so
1018 ToErase.push_back(BB->getTerminator());
1019
1020 // Generate a function call to testSetjmp function and preamble/postamble
1021 // code to figure out (1) whether longjmp occurred (2) if longjmp
1022 // occurred, which setjmp it corresponds to
1023 Value *Label = nullptr;
1024 Value *LongjmpResult = nullptr;
1025 BasicBlock *EndBB = nullptr;
1026 wrapTestSetjmp(BB, CI, Threw, SetjmpTable, SetjmpTableSize, Label,
1027 LongjmpResult, EndBB);
1028 assert(Label && LongjmpResult && EndBB);
1029
1030 // Create switch instruction
1031 IRB.SetInsertPoint(EndBB);
1032 SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1033 // -1 means no longjmp happened, continue normally (will hit the default
1034 // switch case). 0 means a longjmp that is not ours to handle, needs a
1035 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1036 // 0).
Heejin Ahn18c56a02019-02-04 19:13:39 +00001037 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1038 SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1039 SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB);
Heejin Ahnc0f18172016-09-01 21:05:15 +00001040 }
1041
1042 // We are splitting the block here, and must continue to find other calls
1043 // in the block - which is now split. so continue to traverse in the Tail
1044 BBs.push_back(Tail);
1045 }
1046 }
1047
1048 // Erase everything we no longer need in this function
1049 for (Instruction *I : ToErase)
1050 I->eraseFromParent();
1051
1052 // Free setjmpTable buffer before each return instruction
1053 for (BasicBlock &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001054 Instruction *TI = BB.getTerminator();
Heejin Ahnc0f18172016-09-01 21:05:15 +00001055 if (isa<ReturnInst>(TI))
1056 CallInst::CreateFree(SetjmpTable, TI);
1057 }
1058
1059 // Every call to saveSetjmp can change setjmpTable and setjmpTableSize
1060 // (when buffer reallocation occurs)
1061 // entry:
1062 // setjmpTableSize = 4;
1063 // setjmpTable = (int *) malloc(40);
1064 // setjmpTable[0] = 0;
1065 // ...
1066 // somebb:
1067 // setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
Sam Clegg4791a662018-11-20 19:25:07 +00001068 // setjmpTableSize = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +00001069 // So we need to make sure the SSA for these variables is valid so that every
1070 // saveSetjmp and testSetjmp calls have the correct arguments.
1071 SSAUpdater SetjmpTableSSA;
1072 SSAUpdater SetjmpTableSizeSSA;
1073 SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
1074 SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
1075 for (Instruction *I : SetjmpTableInsts)
1076 SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
1077 for (Instruction *I : SetjmpTableSizeInsts)
1078 SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
1079
1080 for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end();
1081 UI != UE;) {
1082 // Grab the use before incrementing the iterator.
1083 Use &U = *UI;
1084 // Increment the iterator before removing the use from the list.
1085 ++UI;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001086 if (auto *I = dyn_cast<Instruction>(U.getUser()))
Heejin Ahnc0f18172016-09-01 21:05:15 +00001087 if (I->getParent() != &EntryBB)
1088 SetjmpTableSSA.RewriteUse(U);
1089 }
1090 for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end();
1091 UI != UE;) {
1092 Use &U = *UI;
1093 ++UI;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001094 if (auto *I = dyn_cast<Instruction>(U.getUser()))
Heejin Ahnc0f18172016-09-01 21:05:15 +00001095 if (I->getParent() != &EntryBB)
1096 SetjmpTableSizeSSA.RewriteUse(U);
1097 }
1098
1099 // Finally, our modifications to the cfg can break dominance of SSA variables.
1100 // For example, in this code,
1101 // if (x()) { .. setjmp() .. }
1102 // if (y()) { .. longjmp() .. }
1103 // We must split the longjmp block, and it can jump into the block splitted
1104 // from setjmp one. But that means that when we split the setjmp block, it's
1105 // first part no longer dominates its second part - there is a theoretically
1106 // possible control flow path where x() is false, then y() is true and we
1107 // reach the second part of the setjmp block, without ever reaching the first
1108 // part. So, we rebuild SSA form here.
1109 rebuildSSA(F);
1110 return true;
Derek Schuffccdceda2016-08-18 15:27:25 +00001111}