blob: 8755198f45b52481ae73854e18d8d7248e93a380 [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 Clegg4791a662018-11-20 19:25:07 +000053/// 1) Assumes the existence of global variables: __THREW__, __threwValue
54/// __THREW__ and __threwValue will be set in invoke wrappers
Heejin Ahnc0f18172016-09-01 21:05:15 +000055/// in JS glue code. For what invoke wrappers are, refer to 3). These
56/// variables are used for both exceptions and setjmp/longjmps.
57/// __THREW__ indicates whether an exception or a longjmp occurred or not. 0
58/// means nothing occurred, 1 means an exception occurred, and other numbers
Heejin Ahn99bd16b2016-09-10 02:33:47 +000059/// mean a longjmp occurred. In the case of longjmp, __threwValue variable
Heejin Ahnc0f18172016-09-01 21:05:15 +000060/// indicates the corresponding setjmp buffer the longjmp corresponds to.
Heejin Ahnc0f18172016-09-01 21:05:15 +000061///
62/// * Exception handling
Derek Schufff41f67d2016-08-01 21:34:04 +000063///
Sam Clegg4791a662018-11-20 19:25:07 +000064/// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions
65/// at link time.
Sam Cleggb2486f12018-10-02 22:12:15 +000066/// The global variables in 1) will exist in wasm address space,
67/// but their values should be set in JS code, so these functions
Derek Schufff41f67d2016-08-01 21:34:04 +000068/// as interfaces to JS glue code. These functions are equivalent to the
69/// following JS functions, which actually exist in asm.js version of JS
70/// library.
71///
72/// function setThrew(threw, value) {
73/// if (__THREW__ == 0) {
74/// __THREW__ = threw;
Derek Schuffccdceda2016-08-18 15:27:25 +000075/// __threwValue = value;
Derek Schufff41f67d2016-08-01 21:34:04 +000076/// }
77/// }
Sam Clegg4791a662018-11-20 19:25:07 +000078//
79/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +000080///
Sam Clegg4791a662018-11-20 19:25:07 +000081/// In exception handling, getTempRet0 indicates the type of an exception
82/// caught, and in setjmp/longjmp, it means the second argument to longjmp
83/// function.
Derek Schufff41f67d2016-08-01 21:34:04 +000084///
85/// 3) Lower
86/// invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
87/// into
88/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +000089/// call @__invoke_SIG(func, arg1, arg2)
Derek Schufff41f67d2016-08-01 21:34:04 +000090/// %__THREW__.val = __THREW__;
91/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +000092/// if (%__THREW__.val == 1)
93/// goto %lpad
94/// else
95/// goto %invoke.cont
Derek Schufff41f67d2016-08-01 21:34:04 +000096/// SIG is a mangled string generated based on the LLVM IR-level function
97/// signature. After LLVM IR types are lowered to the target wasm types,
98/// the names for these wrappers will change based on wasm types as well,
99/// as in invoke_vi (function takes an int and returns void). The bodies of
100/// these wrappers will be generated in JS glue code, and inside those
101/// wrappers we use JS try-catch to generate actual exception effects. It
102/// also calls the original callee function. An example wrapper in JS code
103/// would look like this:
104/// function invoke_vi(index,a1) {
105/// try {
106/// Module["dynCall_vi"](index,a1); // This calls original callee
107/// } catch(e) {
108/// if (typeof e !== 'number' && e !== 'longjmp') throw e;
109/// asm["setThrew"](1, 0); // setThrew is called here
110/// }
111/// }
112/// If an exception is thrown, __THREW__ will be set to true in a wrapper,
113/// so we can jump to the right BB based on this value.
114///
115/// 4) Lower
116/// %val = landingpad catch c1 catch c2 catch c3 ...
117/// ... use %val ...
118/// into
Derek Schuff53b9af02016-08-09 00:29:55 +0000119/// %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
Sam Clegg4791a662018-11-20 19:25:07 +0000120/// %val = {%fmc, getTempRet0()}
Derek Schufff41f67d2016-08-01 21:34:04 +0000121/// ... use %val ...
122/// Here N is a number calculated based on the number of clauses.
Sam Clegg4791a662018-11-20 19:25:07 +0000123/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +0000124///
125/// 5) Lower
126/// resume {%a, %b}
127/// into
Derek Schuff53b9af02016-08-09 00:29:55 +0000128/// call @__resumeException(%a)
129/// where __resumeException() is a function in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +0000130///
Derek Schuff53b9af02016-08-09 00:29:55 +0000131/// 6) Lower
132/// call @llvm.eh.typeid.for(type) (intrinsic)
133/// into
134/// call @llvm_eh_typeid_for(type)
135/// llvm_eh_typeid_for function will be generated in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +0000136///
Heejin Ahnc0f18172016-09-01 21:05:15 +0000137/// * Setjmp / Longjmp handling
138///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000139/// In case calls to longjmp() exists
140///
141/// 1) Lower
142/// longjmp(buf, value)
143/// into
144/// emscripten_longjmp_jmpbuf(buf, value)
145/// emscripten_longjmp_jmpbuf will be lowered to emscripten_longjmp later.
146///
147/// In case calls to setjmp() exists
148///
149/// 2) In the function entry that calls setjmp, initialize setjmpTable and
Heejin Ahnc0f18172016-09-01 21:05:15 +0000150/// sejmpTableSize as follows:
151/// setjmpTableSize = 4;
152/// setjmpTable = (int *) malloc(40);
153/// setjmpTable[0] = 0;
154/// setjmpTable and setjmpTableSize are used in saveSetjmp() function in JS
155/// code.
156///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000157/// 3) Lower
Heejin Ahnc0f18172016-09-01 21:05:15 +0000158/// setjmp(buf)
159/// into
160/// setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
Sam Clegg4791a662018-11-20 19:25:07 +0000161/// setjmpTableSize = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000162/// For each dynamic setjmp call, setjmpTable stores its ID (a number which
163/// is incrementally assigned from 0) and its label (a unique number that
164/// represents each callsite of setjmp). When we need more entries in
165/// setjmpTable, it is reallocated in saveSetjmp() in JS code and it will
166/// return the new table address, and assign the new table size in
Sam Clegg4791a662018-11-20 19:25:07 +0000167/// setTempRet0(). saveSetjmp also stores the setjmp's ID into the buffer
168/// buf. A BB with setjmp is split into two after setjmp call in order to
169/// make the post-setjmp BB the possible destination of longjmp BB.
Heejin Ahnc0f18172016-09-01 21:05:15 +0000170///
Heejin Ahnc0f18172016-09-01 21:05:15 +0000171///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000172/// 4) Lower every call that might longjmp into
Heejin Ahnc0f18172016-09-01 21:05:15 +0000173/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000174/// call @__invoke_SIG(func, arg1, arg2)
Heejin Ahnc0f18172016-09-01 21:05:15 +0000175/// %__THREW__.val = __THREW__;
176/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000177/// if (%__THREW__.val != 0 & __threwValue != 0) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000178/// %label = testSetjmp(mem[%__THREW__.val], setjmpTable,
179/// setjmpTableSize);
180/// if (%label == 0)
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000181/// emscripten_longjmp(%__THREW__.val, __threwValue);
Sam Clegg4791a662018-11-20 19:25:07 +0000182/// setTempRet0(__threwValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000183/// } else {
184/// %label = -1;
185/// }
Sam Clegg4791a662018-11-20 19:25:07 +0000186/// longjmp_result = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000187/// switch label {
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000188/// label 1: goto post-setjmp BB 1
189/// label 2: goto post-setjmp BB 2
Heejin Ahnc0f18172016-09-01 21:05:15 +0000190/// ...
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000191/// default: goto splitted next BB
Heejin Ahnc0f18172016-09-01 21:05:15 +0000192/// }
Heejin Ahn0c68a872018-11-08 22:56:26 +0000193/// testSetjmp examines setjmpTable to see if there is a matching setjmp
194/// call. After calling an invoke wrapper, if a longjmp occurred, __THREW__
195/// will be the address of matching jmp_buf buffer and __threwValue be the
196/// second argument to longjmp. mem[__THREW__.val] is a setjmp ID that is
197/// stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to
198/// each setjmp callsite. Label 0 means this longjmp buffer does not
199/// correspond to one of the setjmp callsites in this function, so in this
200/// case we just chain the longjmp to the caller. (Here we call
201/// emscripten_longjmp, which is different from emscripten_longjmp_jmpbuf.
202/// emscripten_longjmp_jmpbuf takes jmp_buf as its first argument, while
203/// emscripten_longjmp takes an int. Both of them will eventually be lowered
204/// to emscripten_longjmp in s2wasm, but here we need two signatures - we
205/// can't translate an int value to a jmp_buf.)
206/// Label -1 means no longjmp occurred. Otherwise we jump to the right
207/// post-setjmp BB based on the label.
Heejin Ahnc0f18172016-09-01 21:05:15 +0000208///
Derek Schufff41f67d2016-08-01 21:34:04 +0000209///===----------------------------------------------------------------------===//
210
211#include "WebAssembly.h"
Derek Schuff53b9af02016-08-09 00:29:55 +0000212#include "llvm/IR/CallSite.h"
Heejin Ahnc0f18172016-09-01 21:05:15 +0000213#include "llvm/IR/Dominators.h"
Derek Schufff41f67d2016-08-01 21:34:04 +0000214#include "llvm/IR/IRBuilder.h"
Heejin Ahnc0f18172016-09-01 21:05:15 +0000215#include "llvm/Transforms/Utils/BasicBlockUtils.h"
216#include "llvm/Transforms/Utils/SSAUpdater.h"
Derek Schufff41f67d2016-08-01 21:34:04 +0000217
218using namespace llvm;
219
Derek Schuffccdceda2016-08-18 15:27:25 +0000220#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
Derek Schufff41f67d2016-08-01 21:34:04 +0000221
Derek Schuff66641322016-08-09 22:37:00 +0000222static cl::list<std::string>
Derek Schuffccdceda2016-08-18 15:27:25 +0000223 EHWhitelist("emscripten-cxx-exceptions-whitelist",
224 cl::desc("The list of function names in which Emscripten-style "
225 "exception handling is enabled (see emscripten "
226 "EMSCRIPTEN_CATCHING_WHITELIST options)"),
227 cl::CommaSeparated);
Derek Schuff66641322016-08-09 22:37:00 +0000228
Derek Schufff41f67d2016-08-01 21:34:04 +0000229namespace {
Derek Schuffccdceda2016-08-18 15:27:25 +0000230class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
Derek Schuffccdceda2016-08-18 15:27:25 +0000231 static const char *ResumeFName;
232 static const char *EHTypeIDFName;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000233 static const char *EmLongjmpFName;
234 static const char *EmLongjmpJmpbufFName;
235 static const char *SaveSetjmpFName;
236 static const char *TestSetjmpFName;
Derek Schuffccdceda2016-08-18 15:27:25 +0000237 static const char *FindMatchingCatchPrefix;
238 static const char *InvokePrefix;
239
Heejin Ahnc0f18172016-09-01 21:05:15 +0000240 bool EnableEH; // Enable exception handling
241 bool EnableSjLj; // Enable setjmp/longjmp handling
Derek Schuffccdceda2016-08-18 15:27:25 +0000242
243 GlobalVariable *ThrewGV;
244 GlobalVariable *ThrewValueGV;
Sam Clegg4791a662018-11-20 19:25:07 +0000245 Function *GetTempRet0Func;
246 Function *SetTempRet0Func;
Derek Schuffccdceda2016-08-18 15:27:25 +0000247 Function *ResumeF;
248 Function *EHTypeIDF;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000249 Function *EmLongjmpF;
250 Function *EmLongjmpJmpbufF;
251 Function *SaveSetjmpF;
252 Function *TestSetjmpF;
253
Derek Schuffccdceda2016-08-18 15:27:25 +0000254 // __cxa_find_matching_catch_N functions.
255 // Indexed by the number of clauses in an original landingpad instruction.
256 DenseMap<int, Function *> FindMatchingCatches;
257 // Map of <function signature string, invoke_ wrappers>
258 StringMap<Function *> InvokeWrappers;
259 // Set of whitelisted function names for exception handling
260 std::set<std::string> EHWhitelistSet;
261
Mehdi Amini117296c2016-10-01 02:56:57 +0000262 StringRef getPassName() const override {
Derek Schufff41f67d2016-08-01 21:34:04 +0000263 return "WebAssembly Lower Emscripten Exceptions";
264 }
265
Derek Schuffccdceda2016-08-18 15:27:25 +0000266 bool runEHOnFunction(Function &F);
267 bool runSjLjOnFunction(Function &F);
Derek Schufff41f67d2016-08-01 21:34:04 +0000268 Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
269
Heejin Ahnc0f18172016-09-01 21:05:15 +0000270 template <typename CallOrInvoke> Value *wrapInvoke(CallOrInvoke *CI);
271 void wrapTestSetjmp(BasicBlock *BB, Instruction *InsertPt, Value *Threw,
272 Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
273 Value *&LongjmpResult, BasicBlock *&EndBB);
274 template <typename CallOrInvoke> Function *getInvokeWrapper(CallOrInvoke *CI);
275
Derek Schuffccdceda2016-08-18 15:27:25 +0000276 bool areAllExceptionsAllowed() const { return EHWhitelistSet.empty(); }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000277 bool canLongjmp(Module &M, const Value *Callee) const;
278
Heejin Ahnc0f18172016-09-01 21:05:15 +0000279 void rebuildSSA(Function &F);
Derek Schufff41f67d2016-08-01 21:34:04 +0000280
281public:
282 static char ID;
283
Heejin Ahnc0f18172016-09-01 21:05:15 +0000284 WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH = true, bool EnableSjLj = true)
285 : ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj),
Sam Clegg4791a662018-11-20 19:25:07 +0000286 ThrewGV(nullptr), ThrewValueGV(nullptr), GetTempRet0Func(nullptr),
287 SetTempRet0Func(nullptr), ResumeF(nullptr), EHTypeIDF(nullptr),
288 EmLongjmpF(nullptr), EmLongjmpJmpbufF(nullptr), SaveSetjmpF(nullptr),
289 TestSetjmpF(nullptr) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000290 EHWhitelistSet.insert(EHWhitelist.begin(), EHWhitelist.end());
Derek Schuff66641322016-08-09 22:37:00 +0000291 }
Derek Schufff41f67d2016-08-01 21:34:04 +0000292 bool runOnModule(Module &M) override;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000293
294 void getAnalysisUsage(AnalysisUsage &AU) const override {
295 AU.addRequired<DominatorTreeWrapperPass>();
296 }
Derek Schufff41f67d2016-08-01 21:34:04 +0000297};
298} // End anonymous namespace
299
Derek Schuffccdceda2016-08-18 15:27:25 +0000300const char *WebAssemblyLowerEmscriptenEHSjLj::ResumeFName = "__resumeException";
301const char *WebAssemblyLowerEmscriptenEHSjLj::EHTypeIDFName =
302 "llvm_eh_typeid_for";
Heejin Ahnc0f18172016-09-01 21:05:15 +0000303const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpFName =
304 "emscripten_longjmp";
305const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpJmpbufFName =
306 "emscripten_longjmp_jmpbuf";
307const char *WebAssemblyLowerEmscriptenEHSjLj::SaveSetjmpFName = "saveSetjmp";
308const char *WebAssemblyLowerEmscriptenEHSjLj::TestSetjmpFName = "testSetjmp";
Derek Schuffccdceda2016-08-18 15:27:25 +0000309const char *WebAssemblyLowerEmscriptenEHSjLj::FindMatchingCatchPrefix =
310 "__cxa_find_matching_catch_";
311const char *WebAssemblyLowerEmscriptenEHSjLj::InvokePrefix = "__invoke_";
Derek Schufff41f67d2016-08-01 21:34:04 +0000312
Derek Schuffccdceda2016-08-18 15:27:25 +0000313char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
314INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
315 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
316 false, false)
317
Heejin Ahnc0f18172016-09-01 21:05:15 +0000318ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH,
319 bool EnableSjLj) {
320 return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj);
Derek Schufff41f67d2016-08-01 21:34:04 +0000321}
322
323static bool canThrow(const Value *V) {
324 if (const auto *F = dyn_cast<const Function>(V)) {
325 // Intrinsics cannot throw
326 if (F->isIntrinsic())
327 return false;
328 StringRef Name = F->getName();
329 // leave setjmp and longjmp (mostly) alone, we process them properly later
330 if (Name == "setjmp" || Name == "longjmp")
331 return false;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000332 return !F->doesNotThrow();
Derek Schufff41f67d2016-08-01 21:34:04 +0000333 }
Heejin Ahnb6cd5122016-08-24 22:53:00 +0000334 // not a function, so an indirect call - can throw, we can't tell
335 return true;
Derek Schufff41f67d2016-08-01 21:34:04 +0000336}
337
Sam Cleggb2486f12018-10-02 22:12:15 +0000338// Get a global variable with the given name. If it doesn't exist declare it,
339// which will generate an import and asssumes that it will exist at link time.
340static GlobalVariable *getGlobalVariableI32(Module &M, IRBuilder<> &IRB,
341 const char *Name) {
Sam Clegg28b3e992018-07-17 16:40:03 +0000342 if (M.getNamedGlobal(Name))
343 report_fatal_error(Twine("variable name is reserved: ") + Name);
344
345 return new GlobalVariable(M, IRB.getInt32Ty(), false,
Sam Cleggb2486f12018-10-02 22:12:15 +0000346 GlobalValue::ExternalLinkage, nullptr, Name);
Derek Schufff41f67d2016-08-01 21:34:04 +0000347}
348
349// Simple function name mangler.
350// This function simply takes LLVM's string representation of parameter types
Derek Schuff53b9af02016-08-09 00:29:55 +0000351// and concatenate them with '_'. There are non-alphanumeric characters but llc
352// is ok with it, and we need to postprocess these names after the lowering
353// phase anyway.
Derek Schufff41f67d2016-08-01 21:34:04 +0000354static std::string getSignature(FunctionType *FTy) {
355 std::string Sig;
356 raw_string_ostream OS(Sig);
357 OS << *FTy->getReturnType();
358 for (Type *ParamTy : FTy->params())
359 OS << "_" << *ParamTy;
360 if (FTy->isVarArg())
361 OS << "_...";
362 Sig = OS.str();
David Majnemerc7004902016-08-12 04:32:37 +0000363 Sig.erase(remove_if(Sig, isspace), Sig.end());
Derek Schuff53b9af02016-08-09 00:29:55 +0000364 // When s2wasm parses .s file, a comma means the end of an argument. So a
365 // mangled function name can contain any character but a comma.
366 std::replace(Sig.begin(), Sig.end(), ',', '.');
Derek Schufff41f67d2016-08-01 21:34:04 +0000367 return Sig;
368}
369
Heejin Ahnc0f18172016-09-01 21:05:15 +0000370// Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
371// This is because a landingpad instruction contains two more arguments, a
372// personality function and a cleanup bit, and __cxa_find_matching_catch_N
373// functions are named after the number of arguments in the original landingpad
374// instruction.
Derek Schuffccdceda2016-08-18 15:27:25 +0000375Function *
376WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
377 unsigned NumClauses) {
Derek Schufff41f67d2016-08-01 21:34:04 +0000378 if (FindMatchingCatches.count(NumClauses))
379 return FindMatchingCatches[NumClauses];
380 PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
381 SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
382 FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
Derek Schuffccdceda2016-08-18 15:27:25 +0000383 Function *F =
384 Function::Create(FTy, GlobalValue::ExternalLinkage,
385 FindMatchingCatchPrefix + Twine(NumClauses + 2), &M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000386 FindMatchingCatches[NumClauses] = F;
387 return F;
388}
389
Heejin Ahnc0f18172016-09-01 21:05:15 +0000390// Generate invoke wrapper seqence with preamble and postamble
391// Preamble:
392// __THREW__ = 0;
393// Postamble:
394// %__THREW__.val = __THREW__; __THREW__ = 0;
395// Returns %__THREW__.val, which indicates whether an exception is thrown (or
396// whether longjmp occurred), for future use.
397template <typename CallOrInvoke>
398Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallOrInvoke *CI) {
399 LLVMContext &C = CI->getModule()->getContext();
400
401 // If we are calling a function that is noreturn, we must remove that
402 // attribute. The code we insert here does expect it to return, after we
403 // catch the exception.
404 if (CI->doesNotReturn()) {
405 if (auto *F = dyn_cast<Function>(CI->getCalledValue()))
406 F->removeFnAttr(Attribute::NoReturn);
Reid Klecknerb5180542017-03-21 16:57:19 +0000407 CI->removeAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000408 }
409
410 IRBuilder<> IRB(C);
411 IRB.SetInsertPoint(CI);
412
413 // Pre-invoke
414 // __THREW__ = 0;
415 IRB.CreateStore(IRB.getInt32(0), ThrewGV);
416
417 // Invoke function wrapper in JavaScript
418 SmallVector<Value *, 16> Args;
419 // Put the pointer to the callee as first argument, so it can be called
420 // within the invoke wrapper later
421 Args.push_back(CI->getCalledValue());
422 Args.append(CI->arg_begin(), CI->arg_end());
423 CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
424 NewCall->takeName(CI);
425 NewCall->setCallingConv(CI->getCallingConv());
426 NewCall->setDebugLoc(CI->getDebugLoc());
427
428 // Because we added the pointer to the callee as first argument, all
429 // argument attribute indices have to be incremented by one.
Reid Kleckner7f720332017-04-13 00:58:09 +0000430 SmallVector<AttributeSet, 8> ArgAttributes;
Derek Schuff0db0ca32017-04-12 16:03:00 +0000431 const AttributeList &InvokeAL = CI->getAttributes();
432
Derek Schuff0db0ca32017-04-12 16:03:00 +0000433 // No attributes for the callee pointer.
Reid Kleckner7f720332017-04-13 00:58:09 +0000434 ArgAttributes.push_back(AttributeSet());
Derek Schuff0db0ca32017-04-12 16:03:00 +0000435 // Copy the argument attributes from the original
Reid Klecknerf021fab2017-04-13 23:12:13 +0000436 for (unsigned i = 0, e = CI->getNumArgOperands(); i < e; ++i)
Reid Kleckner7f720332017-04-13 00:58:09 +0000437 ArgAttributes.push_back(InvokeAL.getParamAttributes(i));
Derek Schuff0db0ca32017-04-12 16:03:00 +0000438
Heejin Ahnc0f18172016-09-01 21:05:15 +0000439 // Reconstruct the AttributesList based on the vector we constructed.
Reid Kleckner7f720332017-04-13 00:58:09 +0000440 AttributeList NewCallAL =
441 AttributeList::get(C, InvokeAL.getFnAttributes(),
442 InvokeAL.getRetAttributes(), ArgAttributes);
Derek Schuff0db0ca32017-04-12 16:03:00 +0000443 NewCall->setAttributes(NewCallAL);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000444
445 CI->replaceAllUsesWith(NewCall);
446
447 // Post-invoke
448 // %__THREW__.val = __THREW__; __THREW__ = 0;
449 Value *Threw = IRB.CreateLoad(ThrewGV, ThrewGV->getName() + ".val");
450 IRB.CreateStore(IRB.getInt32(0), ThrewGV);
451 return Threw;
452}
453
454// Get matching invoke wrapper based on callee signature
455template <typename CallOrInvoke>
456Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallOrInvoke *CI) {
457 Module *M = CI->getModule();
Derek Schufff41f67d2016-08-01 21:34:04 +0000458 SmallVector<Type *, 16> ArgTys;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000459 Value *Callee = CI->getCalledValue();
Derek Schufff41f67d2016-08-01 21:34:04 +0000460 FunctionType *CalleeFTy;
461 if (auto *F = dyn_cast<Function>(Callee))
462 CalleeFTy = F->getFunctionType();
463 else {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000464 auto *CalleeTy = cast<PointerType>(Callee->getType())->getElementType();
Derek Schufff41f67d2016-08-01 21:34:04 +0000465 CalleeFTy = dyn_cast<FunctionType>(CalleeTy);
466 }
467
468 std::string Sig = getSignature(CalleeFTy);
469 if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
470 return InvokeWrappers[Sig];
471
472 // Put the pointer to the callee as first argument
473 ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
474 // Add argument types
475 ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
476
477 FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
478 CalleeFTy->isVarArg());
479 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage,
Heejin Ahnc0f18172016-09-01 21:05:15 +0000480 InvokePrefix + Sig, M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000481 InvokeWrappers[Sig] = F;
482 return F;
483}
484
Heejin Ahnc0f18172016-09-01 21:05:15 +0000485bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(Module &M,
486 const Value *Callee) const {
487 if (auto *CalleeF = dyn_cast<Function>(Callee))
488 if (CalleeF->isIntrinsic())
489 return false;
Heejin Ahn23d57102016-08-31 22:40:34 +0000490
Heejin Ahnc0f18172016-09-01 21:05:15 +0000491 // The reason we include malloc/free here is to exclude the malloc/free
492 // calls generated in setjmp prep / cleanup routines.
493 Function *SetjmpF = M.getFunction("setjmp");
494 Function *MallocF = M.getFunction("malloc");
495 Function *FreeF = M.getFunction("free");
496 if (Callee == SetjmpF || Callee == MallocF || Callee == FreeF)
Heejin Ahn10a70862016-09-01 00:44:37 +0000497 return false;
498
Heejin Ahnc0f18172016-09-01 21:05:15 +0000499 // There are functions in JS glue code
500 if (Callee == ResumeF || Callee == EHTypeIDF || Callee == SaveSetjmpF ||
501 Callee == TestSetjmpF)
502 return false;
Heejin Ahn10a70862016-09-01 00:44:37 +0000503
Heejin Ahnc0f18172016-09-01 21:05:15 +0000504 // __cxa_find_matching_catch_N functions cannot longjmp
505 if (Callee->getName().startswith(FindMatchingCatchPrefix))
506 return false;
507
508 // Exception-catching related functions
509 Function *BeginCatchF = M.getFunction("__cxa_begin_catch");
510 Function *EndCatchF = M.getFunction("__cxa_end_catch");
511 Function *AllocExceptionF = M.getFunction("__cxa_allocate_exception");
512 Function *ThrowF = M.getFunction("__cxa_throw");
513 Function *TerminateF = M.getFunction("__clang_call_terminate");
514 if (Callee == BeginCatchF || Callee == EndCatchF ||
Sam Clegg4791a662018-11-20 19:25:07 +0000515 Callee == AllocExceptionF || Callee == ThrowF || Callee == TerminateF ||
516 Callee == GetTempRet0Func || Callee == SetTempRet0Func)
Heejin Ahnc0f18172016-09-01 21:05:15 +0000517 return false;
518
519 // Otherwise we don't know
520 return true;
521}
522
523// Generate testSetjmp function call seqence with preamble and postamble.
524// The code this generates is equivalent to the following JavaScript code:
525// if (%__THREW__.val != 0 & threwValue != 0) {
526// %label = _testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
527// if (%label == 0)
528// emscripten_longjmp(%__THREW__.val, threwValue);
Sam Clegg4791a662018-11-20 19:25:07 +0000529// setTempRet0(threwValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000530// } else {
531// %label = -1;
532// }
Sam Clegg4791a662018-11-20 19:25:07 +0000533// %longjmp_result = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000534//
535// As output parameters. returns %label, %longjmp_result, and the BB the last
536// instruction (%longjmp_result = ...) is in.
537void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
538 BasicBlock *BB, Instruction *InsertPt, Value *Threw, Value *SetjmpTable,
539 Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
540 BasicBlock *&EndBB) {
541 Function *F = BB->getParent();
542 LLVMContext &C = BB->getModule()->getContext();
543 IRBuilder<> IRB(C);
544 IRB.SetInsertPoint(InsertPt);
545
546 // if (%__THREW__.val != 0 & threwValue != 0)
547 IRB.SetInsertPoint(BB);
548 BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
549 BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
550 BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
551 Value *ThrewCmp = IRB.CreateICmpNE(Threw, IRB.getInt32(0));
552 Value *ThrewValue =
553 IRB.CreateLoad(ThrewValueGV, ThrewValueGV->getName() + ".val");
554 Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
555 Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
556 IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
557
558 // %label = _testSetjmp(mem[%__THREW__.val], _setjmpTable, _setjmpTableSize);
559 // if (%label == 0)
560 IRB.SetInsertPoint(ThenBB1);
561 BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F);
562 BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
563 Value *ThrewInt = IRB.CreateIntToPtr(Threw, Type::getInt32PtrTy(C),
564 Threw->getName() + ".i32p");
565 Value *LoadedThrew =
566 IRB.CreateLoad(ThrewInt, ThrewInt->getName() + ".loaded");
567 Value *ThenLabel = IRB.CreateCall(
568 TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
569 Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
570 IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2);
571
572 // emscripten_longjmp(%__THREW__.val, threwValue);
573 IRB.SetInsertPoint(ThenBB2);
574 IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue});
575 IRB.CreateUnreachable();
576
Sam Clegg4791a662018-11-20 19:25:07 +0000577 // setTempRet0(threwValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000578 IRB.SetInsertPoint(EndBB2);
Sam Clegg4791a662018-11-20 19:25:07 +0000579 IRB.CreateCall(SetTempRet0Func, ThrewValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000580 IRB.CreateBr(EndBB1);
581
582 IRB.SetInsertPoint(ElseBB1);
583 IRB.CreateBr(EndBB1);
584
Sam Clegg4791a662018-11-20 19:25:07 +0000585 // longjmp_result = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000586 IRB.SetInsertPoint(EndBB1);
587 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
588 LabelPHI->addIncoming(ThenLabel, EndBB2);
589
590 LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
591
592 // Output parameter assignment
593 Label = LabelPHI;
594 EndBB = EndBB1;
Sam Clegg4791a662018-11-20 19:25:07 +0000595 LongjmpResult = IRB.CreateCall(GetTempRet0Func, None, "longjmp_result");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000596}
597
Heejin Ahnc0f18172016-09-01 21:05:15 +0000598void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
599 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
600 DT.recalculate(F); // CFG has been changed
601 SSAUpdater SSA;
602 for (BasicBlock &BB : F) {
603 for (Instruction &I : BB) {
604 for (auto UI = I.use_begin(), UE = I.use_end(); UI != UE;) {
605 Use &U = *UI;
606 ++UI;
607 SSA.Initialize(I.getType(), I.getName());
608 SSA.AddAvailableValue(&BB, &I);
609 Instruction *User = cast<Instruction>(U.getUser());
610 if (User->getParent() == &BB)
611 continue;
612
613 if (PHINode *UserPN = dyn_cast<PHINode>(User))
614 if (UserPN->getIncomingBlock(U) == &BB)
615 continue;
616
617 if (DT.dominates(&I, User))
618 continue;
619 SSA.RewriteUseAfterInsertions(U);
620 }
621 }
622 }
623}
624
625bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
626 LLVMContext &C = M.getContext();
627 IRBuilder<> IRB(C);
628
629 Function *SetjmpF = M.getFunction("setjmp");
630 Function *LongjmpF = M.getFunction("longjmp");
631 bool SetjmpUsed = SetjmpF && !SetjmpF->use_empty();
632 bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
633 bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed);
634
Sam Clegg4791a662018-11-20 19:25:07 +0000635 // Declare (or get) global variables __THREW__, __threwValue, and
636 // getTempRet0/setTempRet0 function which are used in common for both
637 // exception handling and setjmp/longjmp handling
Sam Cleggb2486f12018-10-02 22:12:15 +0000638 ThrewGV = getGlobalVariableI32(M, IRB, "__THREW__");
639 ThrewValueGV = getGlobalVariableI32(M, IRB, "__threwValue");
Sam Clegg4791a662018-11-20 19:25:07 +0000640 GetTempRet0Func =
641 Function::Create(FunctionType::get(IRB.getInt32Ty(), false),
642 GlobalValue::ExternalLinkage, "getTempRet0", &M);
643 SetTempRet0Func = Function::Create(
644 FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
645 GlobalValue::ExternalLinkage, "setTempRet0", &M);
646 GetTempRet0Func->setDoesNotThrow();
647 SetTempRet0Func->setDoesNotThrow();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000648
649 bool Changed = false;
650
651 // Exception handling
652 if (EnableEH) {
653 // Register __resumeException function
654 FunctionType *ResumeFTy =
655 FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
656 ResumeF = Function::Create(ResumeFTy, GlobalValue::ExternalLinkage,
657 ResumeFName, &M);
658
659 // Register llvm_eh_typeid_for function
660 FunctionType *EHTypeIDTy =
661 FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
662 EHTypeIDF = Function::Create(EHTypeIDTy, GlobalValue::ExternalLinkage,
663 EHTypeIDFName, &M);
664
665 for (Function &F : M) {
666 if (F.isDeclaration())
667 continue;
668 Changed |= runEHOnFunction(F);
669 }
670 }
671
672 // Setjmp/longjmp handling
673 if (DoSjLj) {
674 Changed = true; // We have setjmp or longjmp somewhere
675
Heejin Ahnc0f18172016-09-01 21:05:15 +0000676 if (LongjmpF) {
677 // Replace all uses of longjmp with emscripten_longjmp_jmpbuf, which is
678 // defined in JS code
679 EmLongjmpJmpbufF = Function::Create(LongjmpF->getFunctionType(),
680 GlobalValue::ExternalLinkage,
681 EmLongjmpJmpbufFName, &M);
682
683 LongjmpF->replaceAllUsesWith(EmLongjmpJmpbufF);
684 }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000685
Heejin Ahn0c68a872018-11-08 22:56:26 +0000686 if (SetjmpF) {
687 // Register saveSetjmp function
688 FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
689 SmallVector<Type *, 4> Params = {SetjmpFTy->getParamType(0),
690 IRB.getInt32Ty(), Type::getInt32PtrTy(C),
691 IRB.getInt32Ty()};
692 FunctionType *FTy =
693 FunctionType::get(Type::getInt32PtrTy(C), Params, false);
694 SaveSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
695 SaveSetjmpFName, &M);
696
697 // Register testSetjmp function
698 Params = {IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()};
699 FTy = FunctionType::get(IRB.getInt32Ty(), Params, false);
700 TestSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
701 TestSetjmpFName, &M);
702
703 FTy = FunctionType::get(IRB.getVoidTy(),
704 {IRB.getInt32Ty(), IRB.getInt32Ty()}, false);
705 EmLongjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
706 EmLongjmpFName, &M);
707
708 // Only traverse functions that uses setjmp in order not to insert
709 // unnecessary prep / cleanup code in every function
710 SmallPtrSet<Function *, 8> SetjmpUsers;
711 for (User *U : SetjmpF->users()) {
712 auto *UI = cast<Instruction>(U);
713 SetjmpUsers.insert(UI->getFunction());
714 }
715 for (Function *F : SetjmpUsers)
716 runSjLjOnFunction(*F);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000717 }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000718 }
719
720 if (!Changed) {
721 // Delete unused global variables and functions
Heejin Ahnc0f18172016-09-01 21:05:15 +0000722 if (ResumeF)
723 ResumeF->eraseFromParent();
724 if (EHTypeIDF)
725 EHTypeIDF->eraseFromParent();
726 if (EmLongjmpF)
727 EmLongjmpF->eraseFromParent();
728 if (SaveSetjmpF)
729 SaveSetjmpF->eraseFromParent();
730 if (TestSetjmpF)
731 TestSetjmpF->eraseFromParent();
732 return false;
733 }
734
Derek Schufff41f67d2016-08-01 21:34:04 +0000735 return true;
736}
737
Derek Schuffccdceda2016-08-18 15:27:25 +0000738bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
Derek Schufff41f67d2016-08-01 21:34:04 +0000739 Module &M = *F.getParent();
Derek Schuff53b9af02016-08-09 00:29:55 +0000740 LLVMContext &C = F.getContext();
Derek Schuffccdceda2016-08-18 15:27:25 +0000741 IRBuilder<> IRB(C);
Derek Schufff41f67d2016-08-01 21:34:04 +0000742 bool Changed = false;
743 SmallVector<Instruction *, 64> ToErase;
744 SmallPtrSet<LandingPadInst *, 32> LandingPads;
Derek Schuff66641322016-08-09 22:37:00 +0000745 bool AllowExceptions =
Derek Schuffccdceda2016-08-18 15:27:25 +0000746 areAllExceptionsAllowed() || EHWhitelistSet.count(F.getName());
Derek Schufff41f67d2016-08-01 21:34:04 +0000747
748 for (BasicBlock &BB : F) {
749 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
750 if (!II)
751 continue;
752 Changed = true;
753 LandingPads.insert(II->getLandingPadInst());
Derek Schuffccdceda2016-08-18 15:27:25 +0000754 IRB.SetInsertPoint(II);
Derek Schufff41f67d2016-08-01 21:34:04 +0000755
Derek Schuff53b9af02016-08-09 00:29:55 +0000756 bool NeedInvoke = AllowExceptions && canThrow(II->getCalledValue());
757 if (NeedInvoke) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000758 // Wrap invoke with invoke wrapper and generate preamble/postamble
759 Value *Threw = wrapInvoke(II);
Derek Schufff41f67d2016-08-01 21:34:04 +0000760 ToErase.push_back(II);
761
Derek Schufff41f67d2016-08-01 21:34:04 +0000762 // Insert a branch based on __THREW__ variable
Heejin Ahnc0f18172016-09-01 21:05:15 +0000763 Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(1), "cmp");
764 IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
Derek Schufff41f67d2016-08-01 21:34:04 +0000765
766 } else {
767 // This can't throw, and we don't need this invoke, just replace it with a
768 // call+branch
Heejin Ahnc0f18172016-09-01 21:05:15 +0000769 SmallVector<Value *, 16> Args(II->arg_begin(), II->arg_end());
770 CallInst *NewCall = IRB.CreateCall(II->getCalledValue(), Args);
Derek Schufff41f67d2016-08-01 21:34:04 +0000771 NewCall->takeName(II);
772 NewCall->setCallingConv(II->getCallingConv());
Derek Schufff41f67d2016-08-01 21:34:04 +0000773 NewCall->setDebugLoc(II->getDebugLoc());
Derek Schuff53b9af02016-08-09 00:29:55 +0000774 NewCall->setAttributes(II->getAttributes());
Derek Schufff41f67d2016-08-01 21:34:04 +0000775 II->replaceAllUsesWith(NewCall);
776 ToErase.push_back(II);
777
Derek Schuffccdceda2016-08-18 15:27:25 +0000778 IRB.CreateBr(II->getNormalDest());
Derek Schufff41f67d2016-08-01 21:34:04 +0000779
780 // Remove any PHI node entries from the exception destination
781 II->getUnwindDest()->removePredecessor(&BB);
782 }
783 }
784
785 // Process resume instructions
786 for (BasicBlock &BB : F) {
787 // Scan the body of the basic block for resumes
788 for (Instruction &I : BB) {
789 auto *RI = dyn_cast<ResumeInst>(&I);
790 if (!RI)
791 continue;
792
793 // Split the input into legal values
794 Value *Input = RI->getValue();
Derek Schuffccdceda2016-08-18 15:27:25 +0000795 IRB.SetInsertPoint(RI);
796 Value *Low = IRB.CreateExtractValue(Input, 0, "low");
Derek Schuff53b9af02016-08-09 00:29:55 +0000797 // Create a call to __resumeException function
Heejin Ahnc0f18172016-09-01 21:05:15 +0000798 IRB.CreateCall(ResumeF, {Low});
Derek Schufff41f67d2016-08-01 21:34:04 +0000799 // Add a terminator to the block
Derek Schuffccdceda2016-08-18 15:27:25 +0000800 IRB.CreateUnreachable();
Derek Schufff41f67d2016-08-01 21:34:04 +0000801 ToErase.push_back(RI);
802 }
803 }
804
Derek Schuff53b9af02016-08-09 00:29:55 +0000805 // Process llvm.eh.typeid.for intrinsics
806 for (BasicBlock &BB : F) {
807 for (Instruction &I : BB) {
808 auto *CI = dyn_cast<CallInst>(&I);
809 if (!CI)
810 continue;
811 const Function *Callee = CI->getCalledFunction();
812 if (!Callee)
813 continue;
814 if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
815 continue;
816
Derek Schuffccdceda2016-08-18 15:27:25 +0000817 IRB.SetInsertPoint(CI);
Derek Schuff53b9af02016-08-09 00:29:55 +0000818 CallInst *NewCI =
Derek Schuffccdceda2016-08-18 15:27:25 +0000819 IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
Derek Schuff53b9af02016-08-09 00:29:55 +0000820 CI->replaceAllUsesWith(NewCI);
821 ToErase.push_back(CI);
822 }
823 }
824
Hiroshi Inouec3969642017-06-30 07:17:53 +0000825 // Look for orphan landingpads, can occur in blocks with no predecessors
Derek Schufff41f67d2016-08-01 21:34:04 +0000826 for (BasicBlock &BB : F) {
827 Instruction *I = BB.getFirstNonPHI();
828 if (auto *LPI = dyn_cast<LandingPadInst>(I))
829 LandingPads.insert(LPI);
830 }
831
832 // Handle all the landingpad for this function together, as multiple invokes
833 // may share a single lp
834 for (LandingPadInst *LPI : LandingPads) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000835 IRB.SetInsertPoint(LPI);
Derek Schufff41f67d2016-08-01 21:34:04 +0000836 SmallVector<Value *, 16> FMCArgs;
837 for (unsigned i = 0, e = LPI->getNumClauses(); i < e; ++i) {
838 Constant *Clause = LPI->getClause(i);
839 // As a temporary workaround for the lack of aggregate varargs support
840 // in the interface between JS and wasm, break out filter operands into
841 // their component elements.
842 if (LPI->isFilter(i)) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000843 auto *ATy = cast<ArrayType>(Clause->getType());
Derek Schufff41f67d2016-08-01 21:34:04 +0000844 for (unsigned j = 0, e = ATy->getNumElements(); j < e; ++j) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000845 Value *EV = IRB.CreateExtractValue(Clause, makeArrayRef(j), "filter");
Derek Schufff41f67d2016-08-01 21:34:04 +0000846 FMCArgs.push_back(EV);
847 }
848 } else
849 FMCArgs.push_back(Clause);
850 }
851
Derek Schuff53b9af02016-08-09 00:29:55 +0000852 // Create a call to __cxa_find_matching_catch_N function
Derek Schufff41f67d2016-08-01 21:34:04 +0000853 Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
Derek Schuffccdceda2016-08-18 15:27:25 +0000854 CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
Derek Schufff41f67d2016-08-01 21:34:04 +0000855 Value *Undef = UndefValue::get(LPI->getType());
Derek Schuffccdceda2016-08-18 15:27:25 +0000856 Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
Sam Clegg4791a662018-11-20 19:25:07 +0000857 Value *TempRet0 = IRB.CreateCall(GetTempRet0Func, None, "tempret0");
Derek Schuffccdceda2016-08-18 15:27:25 +0000858 Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
Derek Schufff41f67d2016-08-01 21:34:04 +0000859
860 LPI->replaceAllUsesWith(Pair1);
861 ToErase.push_back(LPI);
862 }
863
864 // Erase everything we no longer need in this function
865 for (Instruction *I : ToErase)
866 I->eraseFromParent();
867
868 return Changed;
869}
Derek Schuffccdceda2016-08-18 15:27:25 +0000870
871bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000872 Module &M = *F.getParent();
873 LLVMContext &C = F.getContext();
874 IRBuilder<> IRB(C);
875 SmallVector<Instruction *, 64> ToErase;
876 // Vector of %setjmpTable values
877 std::vector<Instruction *> SetjmpTableInsts;
878 // Vector of %setjmpTableSize values
879 std::vector<Instruction *> SetjmpTableSizeInsts;
880
881 // Setjmp preparation
882
883 // This instruction effectively means %setjmpTableSize = 4.
884 // We create this as an instruction intentionally, and we don't want to fold
885 // this instruction to a constant 4, because this value will be used in
886 // SSAUpdater.AddAvailableValue(...) later.
887 BasicBlock &EntryBB = F.getEntryBlock();
888 BinaryOperator *SetjmpTableSize = BinaryOperator::Create(
889 Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize",
890 &*EntryBB.getFirstInsertionPt());
891 // setjmpTable = (int *) malloc(40);
892 Instruction *SetjmpTable = CallInst::CreateMalloc(
893 SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
894 nullptr, nullptr, "setjmpTable");
895 // setjmpTable[0] = 0;
896 IRB.SetInsertPoint(SetjmpTableSize);
897 IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
898 SetjmpTableInsts.push_back(SetjmpTable);
899 SetjmpTableSizeInsts.push_back(SetjmpTableSize);
900
901 // Setjmp transformation
902 std::vector<PHINode *> SetjmpRetPHIs;
903 Function *SetjmpF = M.getFunction("setjmp");
904 for (User *U : SetjmpF->users()) {
905 auto *CI = dyn_cast<CallInst>(U);
906 if (!CI)
907 report_fatal_error("Does not support indirect calls to setjmp");
908
909 BasicBlock *BB = CI->getParent();
910 if (BB->getParent() != &F) // in other function
911 continue;
912
913 // The tail is everything right after the call, and will be reached once
914 // when setjmp is called, and later when longjmp returns to the setjmp
915 BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
916 // Add a phi to the tail, which will be the output of setjmp, which
917 // indicates if this is the first call or a longjmp back. The phi directly
918 // uses the right value based on where we arrive from
919 IRB.SetInsertPoint(Tail->getFirstNonPHI());
920 PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
921
922 // setjmp initial call returns 0
923 SetjmpRet->addIncoming(IRB.getInt32(0), BB);
924 // The proper output is now this, not the setjmp call itself
925 CI->replaceAllUsesWith(SetjmpRet);
926 // longjmp returns to the setjmp will add themselves to this phi
927 SetjmpRetPHIs.push_back(SetjmpRet);
928
929 // Fix call target
930 // Our index in the function is our place in the array + 1 to avoid index
931 // 0, because index 0 means the longjmp is not ours to handle.
932 IRB.SetInsertPoint(CI);
933 Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
934 SetjmpTable, SetjmpTableSize};
935 Instruction *NewSetjmpTable =
936 IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
937 Instruction *NewSetjmpTableSize =
Sam Clegg4791a662018-11-20 19:25:07 +0000938 IRB.CreateCall(GetTempRet0Func, None, "setjmpTableSize");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000939 SetjmpTableInsts.push_back(NewSetjmpTable);
940 SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
941 ToErase.push_back(CI);
942 }
943
944 // Update each call that can longjmp so it can return to a setjmp where
945 // relevant.
946
947 // Because we are creating new BBs while processing and don't want to make
948 // all these newly created BBs candidates again for longjmp processing, we
949 // first make the vector of candidate BBs.
950 std::vector<BasicBlock *> BBs;
951 for (BasicBlock &BB : F)
952 BBs.push_back(&BB);
953
954 // BBs.size() will change within the loop, so we query it every time
955 for (unsigned i = 0; i < BBs.size(); i++) {
956 BasicBlock *BB = BBs[i];
957 for (Instruction &I : *BB) {
958 assert(!isa<InvokeInst>(&I));
959 auto *CI = dyn_cast<CallInst>(&I);
960 if (!CI)
961 continue;
962
963 const Value *Callee = CI->getCalledValue();
964 if (!canLongjmp(M, Callee))
965 continue;
966
967 Value *Threw = nullptr;
968 BasicBlock *Tail;
969 if (Callee->getName().startswith(InvokePrefix)) {
970 // If invoke wrapper has already been generated for this call in
971 // previous EH phase, search for the load instruction
972 // %__THREW__.val = __THREW__;
973 // in postamble after the invoke wrapper call
974 LoadInst *ThrewLI = nullptr;
975 StoreInst *ThrewResetSI = nullptr;
976 for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
977 I != IE; ++I) {
978 if (auto *LI = dyn_cast<LoadInst>(I))
979 if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
980 if (GV == ThrewGV) {
981 Threw = ThrewLI = LI;
982 break;
983 }
984 }
985 // Search for the store instruction after the load above
986 // __THREW__ = 0;
987 for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
988 I != IE; ++I) {
989 if (auto *SI = dyn_cast<StoreInst>(I))
990 if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand()))
991 if (GV == ThrewGV && SI->getValueOperand() == IRB.getInt32(0)) {
992 ThrewResetSI = SI;
993 break;
994 }
995 }
996 assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
997 assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
998 Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
999
1000 } else {
1001 // Wrap call with invoke wrapper and generate preamble/postamble
1002 Threw = wrapInvoke(CI);
1003 ToErase.push_back(CI);
1004 Tail = SplitBlock(BB, CI->getNextNode());
1005 }
1006
1007 // We need to replace the terminator in Tail - SplitBlock makes BB go
1008 // straight to Tail, we need to check if a longjmp occurred, and go to the
1009 // right setjmp-tail if so
1010 ToErase.push_back(BB->getTerminator());
1011
1012 // Generate a function call to testSetjmp function and preamble/postamble
1013 // code to figure out (1) whether longjmp occurred (2) if longjmp
1014 // occurred, which setjmp it corresponds to
1015 Value *Label = nullptr;
1016 Value *LongjmpResult = nullptr;
1017 BasicBlock *EndBB = nullptr;
1018 wrapTestSetjmp(BB, CI, Threw, SetjmpTable, SetjmpTableSize, Label,
1019 LongjmpResult, EndBB);
1020 assert(Label && LongjmpResult && EndBB);
1021
1022 // Create switch instruction
1023 IRB.SetInsertPoint(EndBB);
1024 SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1025 // -1 means no longjmp happened, continue normally (will hit the default
1026 // switch case). 0 means a longjmp that is not ours to handle, needs a
1027 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1028 // 0).
1029 for (unsigned i = 0; i < SetjmpRetPHIs.size(); i++) {
1030 SI->addCase(IRB.getInt32(i + 1), SetjmpRetPHIs[i]->getParent());
1031 SetjmpRetPHIs[i]->addIncoming(LongjmpResult, EndBB);
1032 }
1033
1034 // We are splitting the block here, and must continue to find other calls
1035 // in the block - which is now split. so continue to traverse in the Tail
1036 BBs.push_back(Tail);
1037 }
1038 }
1039
1040 // Erase everything we no longer need in this function
1041 for (Instruction *I : ToErase)
1042 I->eraseFromParent();
1043
1044 // Free setjmpTable buffer before each return instruction
1045 for (BasicBlock &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001046 Instruction *TI = BB.getTerminator();
Heejin Ahnc0f18172016-09-01 21:05:15 +00001047 if (isa<ReturnInst>(TI))
1048 CallInst::CreateFree(SetjmpTable, TI);
1049 }
1050
1051 // Every call to saveSetjmp can change setjmpTable and setjmpTableSize
1052 // (when buffer reallocation occurs)
1053 // entry:
1054 // setjmpTableSize = 4;
1055 // setjmpTable = (int *) malloc(40);
1056 // setjmpTable[0] = 0;
1057 // ...
1058 // somebb:
1059 // setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
Sam Clegg4791a662018-11-20 19:25:07 +00001060 // setjmpTableSize = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +00001061 // So we need to make sure the SSA for these variables is valid so that every
1062 // saveSetjmp and testSetjmp calls have the correct arguments.
1063 SSAUpdater SetjmpTableSSA;
1064 SSAUpdater SetjmpTableSizeSSA;
1065 SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
1066 SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
1067 for (Instruction *I : SetjmpTableInsts)
1068 SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
1069 for (Instruction *I : SetjmpTableSizeInsts)
1070 SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
1071
1072 for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end();
1073 UI != UE;) {
1074 // Grab the use before incrementing the iterator.
1075 Use &U = *UI;
1076 // Increment the iterator before removing the use from the list.
1077 ++UI;
1078 if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
1079 if (I->getParent() != &EntryBB)
1080 SetjmpTableSSA.RewriteUse(U);
1081 }
1082 for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end();
1083 UI != UE;) {
1084 Use &U = *UI;
1085 ++UI;
1086 if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
1087 if (I->getParent() != &EntryBB)
1088 SetjmpTableSizeSSA.RewriteUse(U);
1089 }
1090
1091 // Finally, our modifications to the cfg can break dominance of SSA variables.
1092 // For example, in this code,
1093 // if (x()) { .. setjmp() .. }
1094 // if (y()) { .. longjmp() .. }
1095 // We must split the longjmp block, and it can jump into the block splitted
1096 // from setjmp one. But that means that when we split the setjmp block, it's
1097 // first part no longer dominates its second part - there is a theoretically
1098 // possible control flow path where x() is false, then y() is true and we
1099 // reach the second part of the setjmp block, without ever reaching the first
1100 // part. So, we rebuild SSA form here.
1101 rebuildSSA(F);
1102 return true;
Derek Schuffccdceda2016-08-18 15:27:25 +00001103}