blob: 68a9b192c4ff73327d653d815088e48065ea854a [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//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000011/// This file lowers exception-related instructions and setjmp/longjmp
Heejin Ahnc0f18172016-09-01 21:05:15 +000012/// function calls in order to use Emscripten's JavaScript try and catch
13/// mechanism.
Derek Schufff41f67d2016-08-01 21:34:04 +000014///
Heejin Ahnc0f18172016-09-01 21:05:15 +000015/// To handle exceptions and setjmp/longjmps, this scheme relies on JavaScript's
16/// try and catch syntax and relevant exception-related libraries implemented
17/// in JavaScript glue code that will be produced by Emscripten. This is similar
18/// to the current Emscripten asm.js exception handling in fastcomp. For
19/// fastcomp's EH / SjLj scheme, see these files in fastcomp LLVM branch:
Derek Schufff41f67d2016-08-01 21:34:04 +000020/// (Location: https://github.com/kripken/emscripten-fastcomp)
21/// lib/Target/JSBackend/NaCl/LowerEmExceptionsPass.cpp
Heejin Ahnc0f18172016-09-01 21:05:15 +000022/// lib/Target/JSBackend/NaCl/LowerEmSetjmp.cpp
Derek Schufff41f67d2016-08-01 21:34:04 +000023/// lib/Target/JSBackend/JSBackend.cpp
24/// lib/Target/JSBackend/CallHandlers.h
25///
Heejin Ahnc0f18172016-09-01 21:05:15 +000026/// * Exception handling
27/// This pass lowers invokes and landingpads into library functions in JS glue
28/// code. Invokes are lowered into function wrappers called invoke wrappers that
29/// exist in JS side, which wraps the original function call with JS try-catch.
30/// If an exception occurred, cxa_throw() function in JS side sets some
31/// variables (see below) so we can check whether an exception occurred from
32/// wasm code and handle it appropriately.
Derek Schufff41f67d2016-08-01 21:34:04 +000033///
Heejin Ahnc0f18172016-09-01 21:05:15 +000034/// * Setjmp-longjmp handling
35/// This pass lowers setjmp to a reasonably-performant approach for emscripten.
36/// The idea is that each block with a setjmp is broken up into two parts: the
37/// part containing setjmp and the part right after the setjmp. The latter part
38/// is either reached from the setjmp, or later from a longjmp. To handle the
39/// longjmp, all calls that might longjmp are also called using invoke wrappers
40/// and thus JS / try-catch. JS longjmp() function also sets some variables so
41/// we can check / whether a longjmp occurred from wasm code. Each block with a
42/// function call that might longjmp is also split up after the longjmp call.
43/// After the longjmp call, we check whether a longjmp occurred, and if it did,
44/// which setjmp it corresponds to, and jump to the right post-setjmp block.
45/// We assume setjmp-longjmp handling always run after EH handling, which means
46/// we don't expect any exception-related instructions when SjLj runs.
47/// FIXME Currently this scheme does not support indirect call of setjmp,
48/// because of the limitation of the scheme itself. fastcomp does not support it
49/// either.
50///
51/// In detail, this pass does following things:
52///
Sam Cleggb2486f12018-10-02 22:12:15 +000053/// 1) Assumes the existence of global variables: __THREW__, __threwValue, and
54/// __tempRet0.
Heejin Ahnc0f18172016-09-01 21:05:15 +000055/// __tempRet0 will be set within __cxa_find_matching_catch() function in
Derek Schuffccdceda2016-08-18 15:27:25 +000056/// JS library, and __THREW__ and __threwValue will be set in invoke wrappers
Heejin Ahnc0f18172016-09-01 21:05:15 +000057/// in JS glue code. For what invoke wrappers are, refer to 3). These
58/// variables are used for both exceptions and setjmp/longjmps.
59/// __THREW__ indicates whether an exception or a longjmp occurred or not. 0
60/// means nothing occurred, 1 means an exception occurred, and other numbers
Heejin Ahn99bd16b2016-09-10 02:33:47 +000061/// mean a longjmp occurred. In the case of longjmp, __threwValue variable
Heejin Ahnc0f18172016-09-01 21:05:15 +000062/// indicates the corresponding setjmp buffer the longjmp corresponds to.
63/// In exception handling, __tempRet0 indicates the type of an exception
64/// caught, and in setjmp/longjmp, it means the second argument to longjmp
65/// function.
66///
67/// * Exception handling
Derek Schufff41f67d2016-08-01 21:34:04 +000068///
Sam Cleggb2486f12018-10-02 22:12:15 +000069/// 2) We assume the existence of setThrew and setTempRet0 functions at link
70/// time.
71/// The global variables in 1) will exist in wasm address space,
72/// but their values should be set in JS code, so these functions
Derek Schufff41f67d2016-08-01 21:34:04 +000073/// as interfaces to JS glue code. These functions are equivalent to the
74/// following JS functions, which actually exist in asm.js version of JS
75/// library.
76///
77/// function setThrew(threw, value) {
78/// if (__THREW__ == 0) {
79/// __THREW__ = threw;
Derek Schuffccdceda2016-08-18 15:27:25 +000080/// __threwValue = value;
Derek Schufff41f67d2016-08-01 21:34:04 +000081/// }
82/// }
83///
84/// function setTempRet0(value) {
Heejin Ahnc0f18172016-09-01 21:05:15 +000085/// __tempRet0 = value;
Derek Schufff41f67d2016-08-01 21:34:04 +000086/// }
87///
88/// 3) Lower
89/// invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
90/// into
91/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +000092/// call @__invoke_SIG(func, arg1, arg2)
Derek Schufff41f67d2016-08-01 21:34:04 +000093/// %__THREW__.val = __THREW__;
94/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +000095/// if (%__THREW__.val == 1)
96/// goto %lpad
97/// else
98/// goto %invoke.cont
Derek Schufff41f67d2016-08-01 21:34:04 +000099/// SIG is a mangled string generated based on the LLVM IR-level function
100/// signature. After LLVM IR types are lowered to the target wasm types,
101/// the names for these wrappers will change based on wasm types as well,
102/// as in invoke_vi (function takes an int and returns void). The bodies of
103/// these wrappers will be generated in JS glue code, and inside those
104/// wrappers we use JS try-catch to generate actual exception effects. It
105/// also calls the original callee function. An example wrapper in JS code
106/// would look like this:
107/// function invoke_vi(index,a1) {
108/// try {
109/// Module["dynCall_vi"](index,a1); // This calls original callee
110/// } catch(e) {
111/// if (typeof e !== 'number' && e !== 'longjmp') throw e;
112/// asm["setThrew"](1, 0); // setThrew is called here
113/// }
114/// }
115/// If an exception is thrown, __THREW__ will be set to true in a wrapper,
116/// so we can jump to the right BB based on this value.
117///
118/// 4) Lower
119/// %val = landingpad catch c1 catch c2 catch c3 ...
120/// ... use %val ...
121/// into
Derek Schuff53b9af02016-08-09 00:29:55 +0000122/// %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
Heejin Ahnc0f18172016-09-01 21:05:15 +0000123/// %val = {%fmc, __tempRet0}
Derek Schufff41f67d2016-08-01 21:34:04 +0000124/// ... use %val ...
125/// Here N is a number calculated based on the number of clauses.
Heejin Ahnc0f18172016-09-01 21:05:15 +0000126/// Global variable __tempRet0 is set within __cxa_find_matching_catch() in
Derek Schufff41f67d2016-08-01 21:34:04 +0000127/// JS glue code.
128///
129/// 5) Lower
130/// resume {%a, %b}
131/// into
Derek Schuff53b9af02016-08-09 00:29:55 +0000132/// call @__resumeException(%a)
133/// where __resumeException() is a function in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +0000134///
Derek Schuff53b9af02016-08-09 00:29:55 +0000135/// 6) Lower
136/// call @llvm.eh.typeid.for(type) (intrinsic)
137/// into
138/// call @llvm_eh_typeid_for(type)
139/// llvm_eh_typeid_for function will be generated in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +0000140///
Heejin Ahnc0f18172016-09-01 21:05:15 +0000141/// * Setjmp / Longjmp handling
142///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000143/// In case calls to longjmp() exists
144///
145/// 1) Lower
146/// longjmp(buf, value)
147/// into
148/// emscripten_longjmp_jmpbuf(buf, value)
149/// emscripten_longjmp_jmpbuf will be lowered to emscripten_longjmp later.
150///
151/// In case calls to setjmp() exists
152///
153/// 2) In the function entry that calls setjmp, initialize setjmpTable and
Heejin Ahnc0f18172016-09-01 21:05:15 +0000154/// sejmpTableSize as follows:
155/// setjmpTableSize = 4;
156/// setjmpTable = (int *) malloc(40);
157/// setjmpTable[0] = 0;
158/// setjmpTable and setjmpTableSize are used in saveSetjmp() function in JS
159/// code.
160///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000161/// 3) Lower
Heejin Ahnc0f18172016-09-01 21:05:15 +0000162/// setjmp(buf)
163/// into
164/// setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
165/// setjmpTableSize = __tempRet0;
166/// For each dynamic setjmp call, setjmpTable stores its ID (a number which
167/// is incrementally assigned from 0) and its label (a unique number that
168/// represents each callsite of setjmp). When we need more entries in
169/// setjmpTable, it is reallocated in saveSetjmp() in JS code and it will
170/// return the new table address, and assign the new table size in
171/// __tempRet0. saveSetjmp also stores the setjmp's ID into the buffer buf.
172/// A BB with setjmp is split into two after setjmp call in order to make the
173/// post-setjmp BB the possible destination of longjmp BB.
174///
Heejin Ahnc0f18172016-09-01 21:05:15 +0000175///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000176/// 4) Lower every call that might longjmp into
Heejin Ahnc0f18172016-09-01 21:05:15 +0000177/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000178/// call @__invoke_SIG(func, arg1, arg2)
Heejin Ahnc0f18172016-09-01 21:05:15 +0000179/// %__THREW__.val = __THREW__;
180/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000181/// if (%__THREW__.val != 0 & __threwValue != 0) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000182/// %label = testSetjmp(mem[%__THREW__.val], setjmpTable,
183/// setjmpTableSize);
184/// if (%label == 0)
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000185/// emscripten_longjmp(%__THREW__.val, __threwValue);
186/// __tempRet0 = __threwValue;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000187/// } else {
188/// %label = -1;
189/// }
190/// longjmp_result = __tempRet0;
191/// switch label {
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000192/// label 1: goto post-setjmp BB 1
193/// label 2: goto post-setjmp BB 2
Heejin Ahnc0f18172016-09-01 21:05:15 +0000194/// ...
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000195/// default: goto splitted next BB
Heejin Ahnc0f18172016-09-01 21:05:15 +0000196/// }
Heejin Ahn0c68a872018-11-08 22:56:26 +0000197/// testSetjmp examines setjmpTable to see if there is a matching setjmp
198/// call. After calling an invoke wrapper, if a longjmp occurred, __THREW__
199/// will be the address of matching jmp_buf buffer and __threwValue be the
200/// second argument to longjmp. mem[__THREW__.val] is a setjmp ID that is
201/// stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to
202/// each setjmp callsite. Label 0 means this longjmp buffer does not
203/// correspond to one of the setjmp callsites in this function, so in this
204/// case we just chain the longjmp to the caller. (Here we call
205/// emscripten_longjmp, which is different from emscripten_longjmp_jmpbuf.
206/// emscripten_longjmp_jmpbuf takes jmp_buf as its first argument, while
207/// emscripten_longjmp takes an int. Both of them will eventually be lowered
208/// to emscripten_longjmp in s2wasm, but here we need two signatures - we
209/// can't translate an int value to a jmp_buf.)
210/// Label -1 means no longjmp occurred. Otherwise we jump to the right
211/// post-setjmp BB based on the label.
Heejin Ahnc0f18172016-09-01 21:05:15 +0000212///
Derek Schufff41f67d2016-08-01 21:34:04 +0000213///===----------------------------------------------------------------------===//
214
215#include "WebAssembly.h"
Derek Schuff53b9af02016-08-09 00:29:55 +0000216#include "llvm/IR/CallSite.h"
Heejin Ahnc0f18172016-09-01 21:05:15 +0000217#include "llvm/IR/Dominators.h"
Derek Schufff41f67d2016-08-01 21:34:04 +0000218#include "llvm/IR/IRBuilder.h"
Heejin Ahnc0f18172016-09-01 21:05:15 +0000219#include "llvm/Transforms/Utils/BasicBlockUtils.h"
220#include "llvm/Transforms/Utils/SSAUpdater.h"
Derek Schufff41f67d2016-08-01 21:34:04 +0000221
222using namespace llvm;
223
Derek Schuffccdceda2016-08-18 15:27:25 +0000224#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
Derek Schufff41f67d2016-08-01 21:34:04 +0000225
Derek Schuff66641322016-08-09 22:37:00 +0000226static cl::list<std::string>
Derek Schuffccdceda2016-08-18 15:27:25 +0000227 EHWhitelist("emscripten-cxx-exceptions-whitelist",
228 cl::desc("The list of function names in which Emscripten-style "
229 "exception handling is enabled (see emscripten "
230 "EMSCRIPTEN_CATCHING_WHITELIST options)"),
231 cl::CommaSeparated);
Derek Schuff66641322016-08-09 22:37:00 +0000232
Derek Schufff41f67d2016-08-01 21:34:04 +0000233namespace {
Derek Schuffccdceda2016-08-18 15:27:25 +0000234class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
Derek Schuffccdceda2016-08-18 15:27:25 +0000235 static const char *ResumeFName;
236 static const char *EHTypeIDFName;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000237 static const char *EmLongjmpFName;
238 static const char *EmLongjmpJmpbufFName;
239 static const char *SaveSetjmpFName;
240 static const char *TestSetjmpFName;
Derek Schuffccdceda2016-08-18 15:27:25 +0000241 static const char *FindMatchingCatchPrefix;
242 static const char *InvokePrefix;
243
Heejin Ahnc0f18172016-09-01 21:05:15 +0000244 bool EnableEH; // Enable exception handling
245 bool EnableSjLj; // Enable setjmp/longjmp handling
Derek Schuffccdceda2016-08-18 15:27:25 +0000246
247 GlobalVariable *ThrewGV;
248 GlobalVariable *ThrewValueGV;
249 GlobalVariable *TempRet0GV;
250 Function *ResumeF;
251 Function *EHTypeIDF;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000252 Function *EmLongjmpF;
253 Function *EmLongjmpJmpbufF;
254 Function *SaveSetjmpF;
255 Function *TestSetjmpF;
256
Derek Schuffccdceda2016-08-18 15:27:25 +0000257 // __cxa_find_matching_catch_N functions.
258 // Indexed by the number of clauses in an original landingpad instruction.
259 DenseMap<int, Function *> FindMatchingCatches;
260 // Map of <function signature string, invoke_ wrappers>
261 StringMap<Function *> InvokeWrappers;
262 // Set of whitelisted function names for exception handling
263 std::set<std::string> EHWhitelistSet;
264
Mehdi Amini117296c2016-10-01 02:56:57 +0000265 StringRef getPassName() const override {
Derek Schufff41f67d2016-08-01 21:34:04 +0000266 return "WebAssembly Lower Emscripten Exceptions";
267 }
268
Derek Schuffccdceda2016-08-18 15:27:25 +0000269 bool runEHOnFunction(Function &F);
270 bool runSjLjOnFunction(Function &F);
Derek Schufff41f67d2016-08-01 21:34:04 +0000271 Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
272
Heejin Ahnc0f18172016-09-01 21:05:15 +0000273 template <typename CallOrInvoke> Value *wrapInvoke(CallOrInvoke *CI);
274 void wrapTestSetjmp(BasicBlock *BB, Instruction *InsertPt, Value *Threw,
275 Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
276 Value *&LongjmpResult, BasicBlock *&EndBB);
277 template <typename CallOrInvoke> Function *getInvokeWrapper(CallOrInvoke *CI);
278
Derek Schuffccdceda2016-08-18 15:27:25 +0000279 bool areAllExceptionsAllowed() const { return EHWhitelistSet.empty(); }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000280 bool canLongjmp(Module &M, const Value *Callee) const;
281
Heejin Ahnc0f18172016-09-01 21:05:15 +0000282 void rebuildSSA(Function &F);
Derek Schufff41f67d2016-08-01 21:34:04 +0000283
284public:
285 static char ID;
286
Heejin Ahnc0f18172016-09-01 21:05:15 +0000287 WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH = true, bool EnableSjLj = true)
288 : ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj),
289 ThrewGV(nullptr), ThrewValueGV(nullptr), TempRet0GV(nullptr),
290 ResumeF(nullptr), EHTypeIDF(nullptr), EmLongjmpF(nullptr),
291 EmLongjmpJmpbufF(nullptr), SaveSetjmpF(nullptr), TestSetjmpF(nullptr) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000292 EHWhitelistSet.insert(EHWhitelist.begin(), EHWhitelist.end());
Derek Schuff66641322016-08-09 22:37:00 +0000293 }
Derek Schufff41f67d2016-08-01 21:34:04 +0000294 bool runOnModule(Module &M) override;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000295
296 void getAnalysisUsage(AnalysisUsage &AU) const override {
297 AU.addRequired<DominatorTreeWrapperPass>();
298 }
Derek Schufff41f67d2016-08-01 21:34:04 +0000299};
300} // End anonymous namespace
301
Derek Schuffccdceda2016-08-18 15:27:25 +0000302const char *WebAssemblyLowerEmscriptenEHSjLj::ResumeFName = "__resumeException";
303const char *WebAssemblyLowerEmscriptenEHSjLj::EHTypeIDFName =
304 "llvm_eh_typeid_for";
Heejin Ahnc0f18172016-09-01 21:05:15 +0000305const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpFName =
306 "emscripten_longjmp";
307const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpJmpbufFName =
308 "emscripten_longjmp_jmpbuf";
309const char *WebAssemblyLowerEmscriptenEHSjLj::SaveSetjmpFName = "saveSetjmp";
310const char *WebAssemblyLowerEmscriptenEHSjLj::TestSetjmpFName = "testSetjmp";
Derek Schuffccdceda2016-08-18 15:27:25 +0000311const char *WebAssemblyLowerEmscriptenEHSjLj::FindMatchingCatchPrefix =
312 "__cxa_find_matching_catch_";
313const char *WebAssemblyLowerEmscriptenEHSjLj::InvokePrefix = "__invoke_";
Derek Schufff41f67d2016-08-01 21:34:04 +0000314
Derek Schuffccdceda2016-08-18 15:27:25 +0000315char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
316INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
317 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
318 false, false)
319
Heejin Ahnc0f18172016-09-01 21:05:15 +0000320ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH,
321 bool EnableSjLj) {
322 return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj);
Derek Schufff41f67d2016-08-01 21:34:04 +0000323}
324
325static bool canThrow(const Value *V) {
326 if (const auto *F = dyn_cast<const Function>(V)) {
327 // Intrinsics cannot throw
328 if (F->isIntrinsic())
329 return false;
330 StringRef Name = F->getName();
331 // leave setjmp and longjmp (mostly) alone, we process them properly later
332 if (Name == "setjmp" || Name == "longjmp")
333 return false;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000334 return !F->doesNotThrow();
Derek Schufff41f67d2016-08-01 21:34:04 +0000335 }
Heejin Ahnb6cd5122016-08-24 22:53:00 +0000336 // not a function, so an indirect call - can throw, we can't tell
337 return true;
Derek Schufff41f67d2016-08-01 21:34:04 +0000338}
339
Sam Cleggb2486f12018-10-02 22:12:15 +0000340// Get a global variable with the given name. If it doesn't exist declare it,
341// which will generate an import and asssumes that it will exist at link time.
342static GlobalVariable *getGlobalVariableI32(Module &M, IRBuilder<> &IRB,
343 const char *Name) {
Sam Clegg28b3e992018-07-17 16:40:03 +0000344 if (M.getNamedGlobal(Name))
345 report_fatal_error(Twine("variable name is reserved: ") + Name);
346
347 return new GlobalVariable(M, IRB.getInt32Ty(), false,
Sam Cleggb2486f12018-10-02 22:12:15 +0000348 GlobalValue::ExternalLinkage, nullptr, Name);
Derek Schufff41f67d2016-08-01 21:34:04 +0000349}
350
351// Simple function name mangler.
352// This function simply takes LLVM's string representation of parameter types
Derek Schuff53b9af02016-08-09 00:29:55 +0000353// and concatenate them with '_'. There are non-alphanumeric characters but llc
354// is ok with it, and we need to postprocess these names after the lowering
355// phase anyway.
Derek Schufff41f67d2016-08-01 21:34:04 +0000356static std::string getSignature(FunctionType *FTy) {
357 std::string Sig;
358 raw_string_ostream OS(Sig);
359 OS << *FTy->getReturnType();
360 for (Type *ParamTy : FTy->params())
361 OS << "_" << *ParamTy;
362 if (FTy->isVarArg())
363 OS << "_...";
364 Sig = OS.str();
David Majnemerc7004902016-08-12 04:32:37 +0000365 Sig.erase(remove_if(Sig, isspace), Sig.end());
Derek Schuff53b9af02016-08-09 00:29:55 +0000366 // When s2wasm parses .s file, a comma means the end of an argument. So a
367 // mangled function name can contain any character but a comma.
368 std::replace(Sig.begin(), Sig.end(), ',', '.');
Derek Schufff41f67d2016-08-01 21:34:04 +0000369 return Sig;
370}
371
Heejin Ahnc0f18172016-09-01 21:05:15 +0000372// Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
373// This is because a landingpad instruction contains two more arguments, a
374// personality function and a cleanup bit, and __cxa_find_matching_catch_N
375// functions are named after the number of arguments in the original landingpad
376// instruction.
Derek Schuffccdceda2016-08-18 15:27:25 +0000377Function *
378WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
379 unsigned NumClauses) {
Derek Schufff41f67d2016-08-01 21:34:04 +0000380 if (FindMatchingCatches.count(NumClauses))
381 return FindMatchingCatches[NumClauses];
382 PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
383 SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
384 FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
Derek Schuffccdceda2016-08-18 15:27:25 +0000385 Function *F =
386 Function::Create(FTy, GlobalValue::ExternalLinkage,
387 FindMatchingCatchPrefix + Twine(NumClauses + 2), &M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000388 FindMatchingCatches[NumClauses] = F;
389 return F;
390}
391
Heejin Ahnc0f18172016-09-01 21:05:15 +0000392// Generate invoke wrapper seqence with preamble and postamble
393// Preamble:
394// __THREW__ = 0;
395// Postamble:
396// %__THREW__.val = __THREW__; __THREW__ = 0;
397// Returns %__THREW__.val, which indicates whether an exception is thrown (or
398// whether longjmp occurred), for future use.
399template <typename CallOrInvoke>
400Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallOrInvoke *CI) {
401 LLVMContext &C = CI->getModule()->getContext();
402
403 // If we are calling a function that is noreturn, we must remove that
404 // attribute. The code we insert here does expect it to return, after we
405 // catch the exception.
406 if (CI->doesNotReturn()) {
407 if (auto *F = dyn_cast<Function>(CI->getCalledValue()))
408 F->removeFnAttr(Attribute::NoReturn);
Reid Klecknerb5180542017-03-21 16:57:19 +0000409 CI->removeAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000410 }
411
412 IRBuilder<> IRB(C);
413 IRB.SetInsertPoint(CI);
414
415 // Pre-invoke
416 // __THREW__ = 0;
417 IRB.CreateStore(IRB.getInt32(0), ThrewGV);
418
419 // Invoke function wrapper in JavaScript
420 SmallVector<Value *, 16> Args;
421 // Put the pointer to the callee as first argument, so it can be called
422 // within the invoke wrapper later
423 Args.push_back(CI->getCalledValue());
424 Args.append(CI->arg_begin(), CI->arg_end());
425 CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
426 NewCall->takeName(CI);
427 NewCall->setCallingConv(CI->getCallingConv());
428 NewCall->setDebugLoc(CI->getDebugLoc());
429
430 // Because we added the pointer to the callee as first argument, all
431 // argument attribute indices have to be incremented by one.
Reid Kleckner7f720332017-04-13 00:58:09 +0000432 SmallVector<AttributeSet, 8> ArgAttributes;
Derek Schuff0db0ca32017-04-12 16:03:00 +0000433 const AttributeList &InvokeAL = CI->getAttributes();
434
Derek Schuff0db0ca32017-04-12 16:03:00 +0000435 // No attributes for the callee pointer.
Reid Kleckner7f720332017-04-13 00:58:09 +0000436 ArgAttributes.push_back(AttributeSet());
Derek Schuff0db0ca32017-04-12 16:03:00 +0000437 // Copy the argument attributes from the original
Reid Klecknerf021fab2017-04-13 23:12:13 +0000438 for (unsigned i = 0, e = CI->getNumArgOperands(); i < e; ++i)
Reid Kleckner7f720332017-04-13 00:58:09 +0000439 ArgAttributes.push_back(InvokeAL.getParamAttributes(i));
Derek Schuff0db0ca32017-04-12 16:03:00 +0000440
Heejin Ahnc0f18172016-09-01 21:05:15 +0000441 // Reconstruct the AttributesList based on the vector we constructed.
Reid Kleckner7f720332017-04-13 00:58:09 +0000442 AttributeList NewCallAL =
443 AttributeList::get(C, InvokeAL.getFnAttributes(),
444 InvokeAL.getRetAttributes(), ArgAttributes);
Derek Schuff0db0ca32017-04-12 16:03:00 +0000445 NewCall->setAttributes(NewCallAL);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000446
447 CI->replaceAllUsesWith(NewCall);
448
449 // Post-invoke
450 // %__THREW__.val = __THREW__; __THREW__ = 0;
451 Value *Threw = IRB.CreateLoad(ThrewGV, ThrewGV->getName() + ".val");
452 IRB.CreateStore(IRB.getInt32(0), ThrewGV);
453 return Threw;
454}
455
456// Get matching invoke wrapper based on callee signature
457template <typename CallOrInvoke>
458Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallOrInvoke *CI) {
459 Module *M = CI->getModule();
Derek Schufff41f67d2016-08-01 21:34:04 +0000460 SmallVector<Type *, 16> ArgTys;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000461 Value *Callee = CI->getCalledValue();
Derek Schufff41f67d2016-08-01 21:34:04 +0000462 FunctionType *CalleeFTy;
463 if (auto *F = dyn_cast<Function>(Callee))
464 CalleeFTy = F->getFunctionType();
465 else {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000466 auto *CalleeTy = cast<PointerType>(Callee->getType())->getElementType();
Derek Schufff41f67d2016-08-01 21:34:04 +0000467 CalleeFTy = dyn_cast<FunctionType>(CalleeTy);
468 }
469
470 std::string Sig = getSignature(CalleeFTy);
471 if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
472 return InvokeWrappers[Sig];
473
474 // Put the pointer to the callee as first argument
475 ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
476 // Add argument types
477 ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
478
479 FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
480 CalleeFTy->isVarArg());
481 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage,
Heejin Ahnc0f18172016-09-01 21:05:15 +0000482 InvokePrefix + Sig, M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000483 InvokeWrappers[Sig] = F;
484 return F;
485}
486
Heejin Ahnc0f18172016-09-01 21:05:15 +0000487bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(Module &M,
488 const Value *Callee) const {
489 if (auto *CalleeF = dyn_cast<Function>(Callee))
490 if (CalleeF->isIntrinsic())
491 return false;
Heejin Ahn23d57102016-08-31 22:40:34 +0000492
Heejin Ahnc0f18172016-09-01 21:05:15 +0000493 // The reason we include malloc/free here is to exclude the malloc/free
494 // calls generated in setjmp prep / cleanup routines.
495 Function *SetjmpF = M.getFunction("setjmp");
496 Function *MallocF = M.getFunction("malloc");
497 Function *FreeF = M.getFunction("free");
498 if (Callee == SetjmpF || Callee == MallocF || Callee == FreeF)
Heejin Ahn10a70862016-09-01 00:44:37 +0000499 return false;
500
Heejin Ahnc0f18172016-09-01 21:05:15 +0000501 // There are functions in JS glue code
502 if (Callee == ResumeF || Callee == EHTypeIDF || Callee == SaveSetjmpF ||
503 Callee == TestSetjmpF)
504 return false;
Heejin Ahn10a70862016-09-01 00:44:37 +0000505
Heejin Ahnc0f18172016-09-01 21:05:15 +0000506 // __cxa_find_matching_catch_N functions cannot longjmp
507 if (Callee->getName().startswith(FindMatchingCatchPrefix))
508 return false;
509
510 // Exception-catching related functions
511 Function *BeginCatchF = M.getFunction("__cxa_begin_catch");
512 Function *EndCatchF = M.getFunction("__cxa_end_catch");
513 Function *AllocExceptionF = M.getFunction("__cxa_allocate_exception");
514 Function *ThrowF = M.getFunction("__cxa_throw");
515 Function *TerminateF = M.getFunction("__clang_call_terminate");
516 if (Callee == BeginCatchF || Callee == EndCatchF ||
517 Callee == AllocExceptionF || Callee == ThrowF || Callee == TerminateF)
518 return false;
519
520 // Otherwise we don't know
521 return true;
522}
523
524// Generate testSetjmp function call seqence with preamble and postamble.
525// The code this generates is equivalent to the following JavaScript code:
526// if (%__THREW__.val != 0 & threwValue != 0) {
527// %label = _testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
528// if (%label == 0)
529// emscripten_longjmp(%__THREW__.val, threwValue);
530// __tempRet0 = threwValue;
531// } else {
532// %label = -1;
533// }
534// %longjmp_result = __tempRet0;
535//
536// As output parameters. returns %label, %longjmp_result, and the BB the last
537// instruction (%longjmp_result = ...) is in.
538void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
539 BasicBlock *BB, Instruction *InsertPt, Value *Threw, Value *SetjmpTable,
540 Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
541 BasicBlock *&EndBB) {
542 Function *F = BB->getParent();
543 LLVMContext &C = BB->getModule()->getContext();
544 IRBuilder<> IRB(C);
545 IRB.SetInsertPoint(InsertPt);
546
547 // if (%__THREW__.val != 0 & threwValue != 0)
548 IRB.SetInsertPoint(BB);
549 BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
550 BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
551 BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
552 Value *ThrewCmp = IRB.CreateICmpNE(Threw, IRB.getInt32(0));
553 Value *ThrewValue =
554 IRB.CreateLoad(ThrewValueGV, ThrewValueGV->getName() + ".val");
555 Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
556 Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
557 IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
558
559 // %label = _testSetjmp(mem[%__THREW__.val], _setjmpTable, _setjmpTableSize);
560 // if (%label == 0)
561 IRB.SetInsertPoint(ThenBB1);
562 BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F);
563 BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
564 Value *ThrewInt = IRB.CreateIntToPtr(Threw, Type::getInt32PtrTy(C),
565 Threw->getName() + ".i32p");
566 Value *LoadedThrew =
567 IRB.CreateLoad(ThrewInt, ThrewInt->getName() + ".loaded");
568 Value *ThenLabel = IRB.CreateCall(
569 TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
570 Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
571 IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2);
572
573 // emscripten_longjmp(%__THREW__.val, threwValue);
574 IRB.SetInsertPoint(ThenBB2);
575 IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue});
576 IRB.CreateUnreachable();
577
578 // __tempRet0 = threwValue;
579 IRB.SetInsertPoint(EndBB2);
580 IRB.CreateStore(ThrewValue, TempRet0GV);
581 IRB.CreateBr(EndBB1);
582
583 IRB.SetInsertPoint(ElseBB1);
584 IRB.CreateBr(EndBB1);
585
586 // longjmp_result = __tempRet0;
587 IRB.SetInsertPoint(EndBB1);
588 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
589 LabelPHI->addIncoming(ThenLabel, EndBB2);
590
591 LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
592
593 // Output parameter assignment
594 Label = LabelPHI;
595 EndBB = EndBB1;
596 LongjmpResult = IRB.CreateLoad(TempRet0GV, "longjmp_result");
597}
598
Heejin Ahnc0f18172016-09-01 21:05:15 +0000599void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
600 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
601 DT.recalculate(F); // CFG has been changed
602 SSAUpdater SSA;
603 for (BasicBlock &BB : F) {
604 for (Instruction &I : BB) {
605 for (auto UI = I.use_begin(), UE = I.use_end(); UI != UE;) {
606 Use &U = *UI;
607 ++UI;
608 SSA.Initialize(I.getType(), I.getName());
609 SSA.AddAvailableValue(&BB, &I);
610 Instruction *User = cast<Instruction>(U.getUser());
611 if (User->getParent() == &BB)
612 continue;
613
614 if (PHINode *UserPN = dyn_cast<PHINode>(User))
615 if (UserPN->getIncomingBlock(U) == &BB)
616 continue;
617
618 if (DT.dominates(&I, User))
619 continue;
620 SSA.RewriteUseAfterInsertions(U);
621 }
622 }
623 }
624}
625
626bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
627 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 Cleggb2486f12018-10-02 22:12:15 +0000636 // Declare (or get) global variables __THREW__, __threwValue, and __tempRet0,
637 // which are used in common for both exception handling and setjmp/longjmp
638 // handling
639 ThrewGV = getGlobalVariableI32(M, IRB, "__THREW__");
640 ThrewValueGV = getGlobalVariableI32(M, IRB, "__threwValue");
641 TempRet0GV = getGlobalVariableI32(M, IRB, "__tempRet0");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000642
643 bool Changed = false;
644
645 // Exception handling
646 if (EnableEH) {
647 // Register __resumeException function
648 FunctionType *ResumeFTy =
649 FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
650 ResumeF = Function::Create(ResumeFTy, GlobalValue::ExternalLinkage,
651 ResumeFName, &M);
652
653 // Register llvm_eh_typeid_for function
654 FunctionType *EHTypeIDTy =
655 FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
656 EHTypeIDF = Function::Create(EHTypeIDTy, GlobalValue::ExternalLinkage,
657 EHTypeIDFName, &M);
658
659 for (Function &F : M) {
660 if (F.isDeclaration())
661 continue;
662 Changed |= runEHOnFunction(F);
663 }
664 }
665
666 // Setjmp/longjmp handling
667 if (DoSjLj) {
668 Changed = true; // We have setjmp or longjmp somewhere
669
Heejin Ahnc0f18172016-09-01 21:05:15 +0000670 if (LongjmpF) {
671 // Replace all uses of longjmp with emscripten_longjmp_jmpbuf, which is
672 // defined in JS code
673 EmLongjmpJmpbufF = Function::Create(LongjmpF->getFunctionType(),
674 GlobalValue::ExternalLinkage,
675 EmLongjmpJmpbufFName, &M);
676
677 LongjmpF->replaceAllUsesWith(EmLongjmpJmpbufF);
678 }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000679
Heejin Ahn0c68a872018-11-08 22:56:26 +0000680 if (SetjmpF) {
681 // Register saveSetjmp function
682 FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
683 SmallVector<Type *, 4> Params = {SetjmpFTy->getParamType(0),
684 IRB.getInt32Ty(), Type::getInt32PtrTy(C),
685 IRB.getInt32Ty()};
686 FunctionType *FTy =
687 FunctionType::get(Type::getInt32PtrTy(C), Params, false);
688 SaveSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
689 SaveSetjmpFName, &M);
690
691 // Register testSetjmp function
692 Params = {IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()};
693 FTy = FunctionType::get(IRB.getInt32Ty(), Params, false);
694 TestSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
695 TestSetjmpFName, &M);
696
697 FTy = FunctionType::get(IRB.getVoidTy(),
698 {IRB.getInt32Ty(), IRB.getInt32Ty()}, false);
699 EmLongjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
700 EmLongjmpFName, &M);
701
702 // Only traverse functions that uses setjmp in order not to insert
703 // unnecessary prep / cleanup code in every function
704 SmallPtrSet<Function *, 8> SetjmpUsers;
705 for (User *U : SetjmpF->users()) {
706 auto *UI = cast<Instruction>(U);
707 SetjmpUsers.insert(UI->getFunction());
708 }
709 for (Function *F : SetjmpUsers)
710 runSjLjOnFunction(*F);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000711 }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000712 }
713
714 if (!Changed) {
715 // Delete unused global variables and functions
Heejin Ahnc0f18172016-09-01 21:05:15 +0000716 if (ResumeF)
717 ResumeF->eraseFromParent();
718 if (EHTypeIDF)
719 EHTypeIDF->eraseFromParent();
720 if (EmLongjmpF)
721 EmLongjmpF->eraseFromParent();
722 if (SaveSetjmpF)
723 SaveSetjmpF->eraseFromParent();
724 if (TestSetjmpF)
725 TestSetjmpF->eraseFromParent();
726 return false;
727 }
728
Derek Schufff41f67d2016-08-01 21:34:04 +0000729 return true;
730}
731
Derek Schuffccdceda2016-08-18 15:27:25 +0000732bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
Derek Schufff41f67d2016-08-01 21:34:04 +0000733 Module &M = *F.getParent();
Derek Schuff53b9af02016-08-09 00:29:55 +0000734 LLVMContext &C = F.getContext();
Derek Schuffccdceda2016-08-18 15:27:25 +0000735 IRBuilder<> IRB(C);
Derek Schufff41f67d2016-08-01 21:34:04 +0000736 bool Changed = false;
737 SmallVector<Instruction *, 64> ToErase;
738 SmallPtrSet<LandingPadInst *, 32> LandingPads;
Derek Schuff66641322016-08-09 22:37:00 +0000739 bool AllowExceptions =
Derek Schuffccdceda2016-08-18 15:27:25 +0000740 areAllExceptionsAllowed() || EHWhitelistSet.count(F.getName());
Derek Schufff41f67d2016-08-01 21:34:04 +0000741
742 for (BasicBlock &BB : F) {
743 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
744 if (!II)
745 continue;
746 Changed = true;
747 LandingPads.insert(II->getLandingPadInst());
Derek Schuffccdceda2016-08-18 15:27:25 +0000748 IRB.SetInsertPoint(II);
Derek Schufff41f67d2016-08-01 21:34:04 +0000749
Derek Schuff53b9af02016-08-09 00:29:55 +0000750 bool NeedInvoke = AllowExceptions && canThrow(II->getCalledValue());
751 if (NeedInvoke) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000752 // Wrap invoke with invoke wrapper and generate preamble/postamble
753 Value *Threw = wrapInvoke(II);
Derek Schufff41f67d2016-08-01 21:34:04 +0000754 ToErase.push_back(II);
755
Derek Schufff41f67d2016-08-01 21:34:04 +0000756 // Insert a branch based on __THREW__ variable
Heejin Ahnc0f18172016-09-01 21:05:15 +0000757 Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(1), "cmp");
758 IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
Derek Schufff41f67d2016-08-01 21:34:04 +0000759
760 } else {
761 // This can't throw, and we don't need this invoke, just replace it with a
762 // call+branch
Heejin Ahnc0f18172016-09-01 21:05:15 +0000763 SmallVector<Value *, 16> Args(II->arg_begin(), II->arg_end());
764 CallInst *NewCall = IRB.CreateCall(II->getCalledValue(), Args);
Derek Schufff41f67d2016-08-01 21:34:04 +0000765 NewCall->takeName(II);
766 NewCall->setCallingConv(II->getCallingConv());
Derek Schufff41f67d2016-08-01 21:34:04 +0000767 NewCall->setDebugLoc(II->getDebugLoc());
Derek Schuff53b9af02016-08-09 00:29:55 +0000768 NewCall->setAttributes(II->getAttributes());
Derek Schufff41f67d2016-08-01 21:34:04 +0000769 II->replaceAllUsesWith(NewCall);
770 ToErase.push_back(II);
771
Derek Schuffccdceda2016-08-18 15:27:25 +0000772 IRB.CreateBr(II->getNormalDest());
Derek Schufff41f67d2016-08-01 21:34:04 +0000773
774 // Remove any PHI node entries from the exception destination
775 II->getUnwindDest()->removePredecessor(&BB);
776 }
777 }
778
779 // Process resume instructions
780 for (BasicBlock &BB : F) {
781 // Scan the body of the basic block for resumes
782 for (Instruction &I : BB) {
783 auto *RI = dyn_cast<ResumeInst>(&I);
784 if (!RI)
785 continue;
786
787 // Split the input into legal values
788 Value *Input = RI->getValue();
Derek Schuffccdceda2016-08-18 15:27:25 +0000789 IRB.SetInsertPoint(RI);
790 Value *Low = IRB.CreateExtractValue(Input, 0, "low");
Derek Schuff53b9af02016-08-09 00:29:55 +0000791 // Create a call to __resumeException function
Heejin Ahnc0f18172016-09-01 21:05:15 +0000792 IRB.CreateCall(ResumeF, {Low});
Derek Schufff41f67d2016-08-01 21:34:04 +0000793 // Add a terminator to the block
Derek Schuffccdceda2016-08-18 15:27:25 +0000794 IRB.CreateUnreachable();
Derek Schufff41f67d2016-08-01 21:34:04 +0000795 ToErase.push_back(RI);
796 }
797 }
798
Derek Schuff53b9af02016-08-09 00:29:55 +0000799 // Process llvm.eh.typeid.for intrinsics
800 for (BasicBlock &BB : F) {
801 for (Instruction &I : BB) {
802 auto *CI = dyn_cast<CallInst>(&I);
803 if (!CI)
804 continue;
805 const Function *Callee = CI->getCalledFunction();
806 if (!Callee)
807 continue;
808 if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
809 continue;
810
Derek Schuffccdceda2016-08-18 15:27:25 +0000811 IRB.SetInsertPoint(CI);
Derek Schuff53b9af02016-08-09 00:29:55 +0000812 CallInst *NewCI =
Derek Schuffccdceda2016-08-18 15:27:25 +0000813 IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
Derek Schuff53b9af02016-08-09 00:29:55 +0000814 CI->replaceAllUsesWith(NewCI);
815 ToErase.push_back(CI);
816 }
817 }
818
Hiroshi Inouec3969642017-06-30 07:17:53 +0000819 // Look for orphan landingpads, can occur in blocks with no predecessors
Derek Schufff41f67d2016-08-01 21:34:04 +0000820 for (BasicBlock &BB : F) {
821 Instruction *I = BB.getFirstNonPHI();
822 if (auto *LPI = dyn_cast<LandingPadInst>(I))
823 LandingPads.insert(LPI);
824 }
825
826 // Handle all the landingpad for this function together, as multiple invokes
827 // may share a single lp
828 for (LandingPadInst *LPI : LandingPads) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000829 IRB.SetInsertPoint(LPI);
Derek Schufff41f67d2016-08-01 21:34:04 +0000830 SmallVector<Value *, 16> FMCArgs;
831 for (unsigned i = 0, e = LPI->getNumClauses(); i < e; ++i) {
832 Constant *Clause = LPI->getClause(i);
833 // As a temporary workaround for the lack of aggregate varargs support
834 // in the interface between JS and wasm, break out filter operands into
835 // their component elements.
836 if (LPI->isFilter(i)) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000837 auto *ATy = cast<ArrayType>(Clause->getType());
Derek Schufff41f67d2016-08-01 21:34:04 +0000838 for (unsigned j = 0, e = ATy->getNumElements(); j < e; ++j) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000839 Value *EV = IRB.CreateExtractValue(Clause, makeArrayRef(j), "filter");
Derek Schufff41f67d2016-08-01 21:34:04 +0000840 FMCArgs.push_back(EV);
841 }
842 } else
843 FMCArgs.push_back(Clause);
844 }
845
Derek Schuff53b9af02016-08-09 00:29:55 +0000846 // Create a call to __cxa_find_matching_catch_N function
Derek Schufff41f67d2016-08-01 21:34:04 +0000847 Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
Derek Schuffccdceda2016-08-18 15:27:25 +0000848 CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
Derek Schufff41f67d2016-08-01 21:34:04 +0000849 Value *Undef = UndefValue::get(LPI->getType());
Derek Schuffccdceda2016-08-18 15:27:25 +0000850 Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000851 Value *TempRet0 =
852 IRB.CreateLoad(TempRet0GV, TempRet0GV->getName() + ".val");
Derek Schuffccdceda2016-08-18 15:27:25 +0000853 Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
Derek Schufff41f67d2016-08-01 21:34:04 +0000854
855 LPI->replaceAllUsesWith(Pair1);
856 ToErase.push_back(LPI);
857 }
858
859 // Erase everything we no longer need in this function
860 for (Instruction *I : ToErase)
861 I->eraseFromParent();
862
863 return Changed;
864}
Derek Schuffccdceda2016-08-18 15:27:25 +0000865
866bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000867 Module &M = *F.getParent();
868 LLVMContext &C = F.getContext();
869 IRBuilder<> IRB(C);
870 SmallVector<Instruction *, 64> ToErase;
871 // Vector of %setjmpTable values
872 std::vector<Instruction *> SetjmpTableInsts;
873 // Vector of %setjmpTableSize values
874 std::vector<Instruction *> SetjmpTableSizeInsts;
875
876 // Setjmp preparation
877
878 // This instruction effectively means %setjmpTableSize = 4.
879 // We create this as an instruction intentionally, and we don't want to fold
880 // this instruction to a constant 4, because this value will be used in
881 // SSAUpdater.AddAvailableValue(...) later.
882 BasicBlock &EntryBB = F.getEntryBlock();
883 BinaryOperator *SetjmpTableSize = BinaryOperator::Create(
884 Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize",
885 &*EntryBB.getFirstInsertionPt());
886 // setjmpTable = (int *) malloc(40);
887 Instruction *SetjmpTable = CallInst::CreateMalloc(
888 SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
889 nullptr, nullptr, "setjmpTable");
890 // setjmpTable[0] = 0;
891 IRB.SetInsertPoint(SetjmpTableSize);
892 IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
893 SetjmpTableInsts.push_back(SetjmpTable);
894 SetjmpTableSizeInsts.push_back(SetjmpTableSize);
895
896 // Setjmp transformation
897 std::vector<PHINode *> SetjmpRetPHIs;
898 Function *SetjmpF = M.getFunction("setjmp");
899 for (User *U : SetjmpF->users()) {
900 auto *CI = dyn_cast<CallInst>(U);
901 if (!CI)
902 report_fatal_error("Does not support indirect calls to setjmp");
903
904 BasicBlock *BB = CI->getParent();
905 if (BB->getParent() != &F) // in other function
906 continue;
907
908 // The tail is everything right after the call, and will be reached once
909 // when setjmp is called, and later when longjmp returns to the setjmp
910 BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
911 // Add a phi to the tail, which will be the output of setjmp, which
912 // indicates if this is the first call or a longjmp back. The phi directly
913 // uses the right value based on where we arrive from
914 IRB.SetInsertPoint(Tail->getFirstNonPHI());
915 PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
916
917 // setjmp initial call returns 0
918 SetjmpRet->addIncoming(IRB.getInt32(0), BB);
919 // The proper output is now this, not the setjmp call itself
920 CI->replaceAllUsesWith(SetjmpRet);
921 // longjmp returns to the setjmp will add themselves to this phi
922 SetjmpRetPHIs.push_back(SetjmpRet);
923
924 // Fix call target
925 // Our index in the function is our place in the array + 1 to avoid index
926 // 0, because index 0 means the longjmp is not ours to handle.
927 IRB.SetInsertPoint(CI);
928 Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
929 SetjmpTable, SetjmpTableSize};
930 Instruction *NewSetjmpTable =
931 IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
932 Instruction *NewSetjmpTableSize =
933 IRB.CreateLoad(TempRet0GV, "setjmpTableSize");
934 SetjmpTableInsts.push_back(NewSetjmpTable);
935 SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
936 ToErase.push_back(CI);
937 }
938
939 // Update each call that can longjmp so it can return to a setjmp where
940 // relevant.
941
942 // Because we are creating new BBs while processing and don't want to make
943 // all these newly created BBs candidates again for longjmp processing, we
944 // first make the vector of candidate BBs.
945 std::vector<BasicBlock *> BBs;
946 for (BasicBlock &BB : F)
947 BBs.push_back(&BB);
948
949 // BBs.size() will change within the loop, so we query it every time
950 for (unsigned i = 0; i < BBs.size(); i++) {
951 BasicBlock *BB = BBs[i];
952 for (Instruction &I : *BB) {
953 assert(!isa<InvokeInst>(&I));
954 auto *CI = dyn_cast<CallInst>(&I);
955 if (!CI)
956 continue;
957
958 const Value *Callee = CI->getCalledValue();
959 if (!canLongjmp(M, Callee))
960 continue;
961
962 Value *Threw = nullptr;
963 BasicBlock *Tail;
964 if (Callee->getName().startswith(InvokePrefix)) {
965 // If invoke wrapper has already been generated for this call in
966 // previous EH phase, search for the load instruction
967 // %__THREW__.val = __THREW__;
968 // in postamble after the invoke wrapper call
969 LoadInst *ThrewLI = nullptr;
970 StoreInst *ThrewResetSI = nullptr;
971 for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
972 I != IE; ++I) {
973 if (auto *LI = dyn_cast<LoadInst>(I))
974 if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
975 if (GV == ThrewGV) {
976 Threw = ThrewLI = LI;
977 break;
978 }
979 }
980 // Search for the store instruction after the load above
981 // __THREW__ = 0;
982 for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
983 I != IE; ++I) {
984 if (auto *SI = dyn_cast<StoreInst>(I))
985 if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand()))
986 if (GV == ThrewGV && SI->getValueOperand() == IRB.getInt32(0)) {
987 ThrewResetSI = SI;
988 break;
989 }
990 }
991 assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
992 assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
993 Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
994
995 } else {
996 // Wrap call with invoke wrapper and generate preamble/postamble
997 Threw = wrapInvoke(CI);
998 ToErase.push_back(CI);
999 Tail = SplitBlock(BB, CI->getNextNode());
1000 }
1001
1002 // We need to replace the terminator in Tail - SplitBlock makes BB go
1003 // straight to Tail, we need to check if a longjmp occurred, and go to the
1004 // right setjmp-tail if so
1005 ToErase.push_back(BB->getTerminator());
1006
1007 // Generate a function call to testSetjmp function and preamble/postamble
1008 // code to figure out (1) whether longjmp occurred (2) if longjmp
1009 // occurred, which setjmp it corresponds to
1010 Value *Label = nullptr;
1011 Value *LongjmpResult = nullptr;
1012 BasicBlock *EndBB = nullptr;
1013 wrapTestSetjmp(BB, CI, Threw, SetjmpTable, SetjmpTableSize, Label,
1014 LongjmpResult, EndBB);
1015 assert(Label && LongjmpResult && EndBB);
1016
1017 // Create switch instruction
1018 IRB.SetInsertPoint(EndBB);
1019 SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1020 // -1 means no longjmp happened, continue normally (will hit the default
1021 // switch case). 0 means a longjmp that is not ours to handle, needs a
1022 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1023 // 0).
1024 for (unsigned i = 0; i < SetjmpRetPHIs.size(); i++) {
1025 SI->addCase(IRB.getInt32(i + 1), SetjmpRetPHIs[i]->getParent());
1026 SetjmpRetPHIs[i]->addIncoming(LongjmpResult, EndBB);
1027 }
1028
1029 // We are splitting the block here, and must continue to find other calls
1030 // in the block - which is now split. so continue to traverse in the Tail
1031 BBs.push_back(Tail);
1032 }
1033 }
1034
1035 // Erase everything we no longer need in this function
1036 for (Instruction *I : ToErase)
1037 I->eraseFromParent();
1038
1039 // Free setjmpTable buffer before each return instruction
1040 for (BasicBlock &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001041 Instruction *TI = BB.getTerminator();
Heejin Ahnc0f18172016-09-01 21:05:15 +00001042 if (isa<ReturnInst>(TI))
1043 CallInst::CreateFree(SetjmpTable, TI);
1044 }
1045
1046 // Every call to saveSetjmp can change setjmpTable and setjmpTableSize
1047 // (when buffer reallocation occurs)
1048 // entry:
1049 // setjmpTableSize = 4;
1050 // setjmpTable = (int *) malloc(40);
1051 // setjmpTable[0] = 0;
1052 // ...
1053 // somebb:
1054 // setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
1055 // setjmpTableSize = __tempRet0;
1056 // So we need to make sure the SSA for these variables is valid so that every
1057 // saveSetjmp and testSetjmp calls have the correct arguments.
1058 SSAUpdater SetjmpTableSSA;
1059 SSAUpdater SetjmpTableSizeSSA;
1060 SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
1061 SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
1062 for (Instruction *I : SetjmpTableInsts)
1063 SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
1064 for (Instruction *I : SetjmpTableSizeInsts)
1065 SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
1066
1067 for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end();
1068 UI != UE;) {
1069 // Grab the use before incrementing the iterator.
1070 Use &U = *UI;
1071 // Increment the iterator before removing the use from the list.
1072 ++UI;
1073 if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
1074 if (I->getParent() != &EntryBB)
1075 SetjmpTableSSA.RewriteUse(U);
1076 }
1077 for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end();
1078 UI != UE;) {
1079 Use &U = *UI;
1080 ++UI;
1081 if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
1082 if (I->getParent() != &EntryBB)
1083 SetjmpTableSizeSSA.RewriteUse(U);
1084 }
1085
1086 // Finally, our modifications to the cfg can break dominance of SSA variables.
1087 // For example, in this code,
1088 // if (x()) { .. setjmp() .. }
1089 // if (y()) { .. longjmp() .. }
1090 // We must split the longjmp block, and it can jump into the block splitted
1091 // from setjmp one. But that means that when we split the setjmp block, it's
1092 // first part no longer dominates its second part - there is a theoretically
1093 // possible control flow path where x() is false, then y() is true and we
1094 // reach the second part of the setjmp block, without ever reaching the first
1095 // part. So, we rebuild SSA form here.
1096 rebuildSSA(F);
1097 return true;
Derek Schuffccdceda2016-08-18 15:27:25 +00001098}