1 //=== WebAssemblyLowerEmscriptenEHSjLj.cpp - Lower exceptions for Emscripten =//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file lowers exception-related instructions and setjmp/longjmp function
11 /// calls to use Emscripten's library functions. The pass uses JavaScript's try
12 /// and catch mechanism in case of Emscripten EH/SjLj and Wasm EH intrinsics in
13 /// case of Emscripten SjLJ.
14 ///
15 /// * Emscripten exception handling
16 /// This pass lowers invokes and landingpads into library functions in JS glue
17 /// code. Invokes are lowered into function wrappers called invoke wrappers that
18 /// exist in JS side, which wraps the original function call with JS try-catch.
19 /// If an exception occurred, cxa_throw() function in JS side sets some
20 /// variables (see below) so we can check whether an exception occurred from
21 /// wasm code and handle it appropriately.
22 ///
23 /// * Emscripten setjmp-longjmp handling
24 /// This pass lowers setjmp to a reasonably-performant approach for emscripten.
25 /// The idea is that each block with a setjmp is broken up into two parts: the
26 /// part containing setjmp and the part right after the setjmp. The latter part
27 /// is either reached from the setjmp, or later from a longjmp. To handle the
28 /// longjmp, all calls that might longjmp are also called using invoke wrappers
29 /// and thus JS / try-catch. JS longjmp() function also sets some variables so
30 /// we can check / whether a longjmp occurred from wasm code. Each block with a
31 /// function call that might longjmp is also split up after the longjmp call.
32 /// After the longjmp call, we check whether a longjmp occurred, and if it did,
33 /// which setjmp it corresponds to, and jump to the right post-setjmp block.
34 /// We assume setjmp-longjmp handling always run after EH handling, which means
35 /// we don't expect any exception-related instructions when SjLj runs.
36 /// FIXME Currently this scheme does not support indirect call of setjmp,
37 /// because of the limitation of the scheme itself. fastcomp does not support it
38 /// either.
39 ///
40 /// In detail, this pass does following things:
41 ///
42 /// 1) Assumes the existence of global variables: __THREW__, __threwValue
43 ///    __THREW__ and __threwValue are defined in compiler-rt in Emscripten.
44 ///    These variables are used for both exceptions and setjmp/longjmps.
45 ///    __THREW__ indicates whether an exception or a longjmp occurred or not. 0
46 ///    means nothing occurred, 1 means an exception occurred, and other numbers
47 ///    mean a longjmp occurred. In the case of longjmp, __THREW__ variable
48 ///    indicates the corresponding setjmp buffer the longjmp corresponds to.
49 ///    __threwValue is 0 for exceptions, and the argument to longjmp in case of
50 ///    longjmp.
51 ///
52 /// * Emscripten exception handling
53 ///
54 /// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions
55 ///    at link time. setThrew exists in Emscripten's compiler-rt:
56 ///
57 ///    void setThrew(uintptr_t threw, int value) {
58 ///      if (__THREW__ == 0) {
59 ///        __THREW__ = threw;
60 ///        __threwValue = value;
61 ///      }
62 ///    }
63 //
64 ///    setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
65 ///    In exception handling, getTempRet0 indicates the type of an exception
66 ///    caught, and in setjmp/longjmp, it means the second argument to longjmp
67 ///    function.
68 ///
69 /// 3) Lower
70 ///      invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
71 ///    into
72 ///      __THREW__ = 0;
73 ///      call @__invoke_SIG(func, arg1, arg2)
74 ///      %__THREW__.val = __THREW__;
75 ///      __THREW__ = 0;
76 ///      if (%__THREW__.val == 1)
77 ///        goto %lpad
78 ///      else
79 ///         goto %invoke.cont
80 ///    SIG is a mangled string generated based on the LLVM IR-level function
81 ///    signature. After LLVM IR types are lowered to the target wasm types,
82 ///    the names for these wrappers will change based on wasm types as well,
83 ///    as in invoke_vi (function takes an int and returns void). The bodies of
84 ///    these wrappers will be generated in JS glue code, and inside those
85 ///    wrappers we use JS try-catch to generate actual exception effects. It
86 ///    also calls the original callee function. An example wrapper in JS code
87 ///    would look like this:
88 ///      function invoke_vi(index,a1) {
89 ///        try {
90 ///          Module["dynCall_vi"](index,a1); // This calls original callee
91 ///        } catch(e) {
92 ///          if (typeof e !== 'number' && e !== 'longjmp') throw e;
93 ///          _setThrew(1, 0); // setThrew is called here
94 ///        }
95 ///      }
96 ///    If an exception is thrown, __THREW__ will be set to true in a wrapper,
97 ///    so we can jump to the right BB based on this value.
98 ///
99 /// 4) Lower
100 ///      %val = landingpad catch c1 catch c2 catch c3 ...
101 ///      ... use %val ...
102 ///    into
103 ///      %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
104 ///      %val = {%fmc, getTempRet0()}
105 ///      ... use %val ...
106 ///    Here N is a number calculated based on the number of clauses.
107 ///    setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
108 ///
109 /// 5) Lower
110 ///      resume {%a, %b}
111 ///    into
112 ///      call @__resumeException(%a)
113 ///    where __resumeException() is a function in JS glue code.
114 ///
115 /// 6) Lower
116 ///      call @llvm.eh.typeid.for(type) (intrinsic)
117 ///    into
118 ///      call @llvm_eh_typeid_for(type)
119 ///    llvm_eh_typeid_for function will be generated in JS glue code.
120 ///
121 /// * Emscripten setjmp / longjmp handling
122 ///
123 /// If there are calls to longjmp()
124 ///
125 /// 1) Lower
126 ///      longjmp(env, val)
127 ///    into
128 ///      emscripten_longjmp(env, val)
129 ///
130 /// If there are calls to setjmp()
131 ///
132 /// 2) In the function entry that calls setjmp, initialize setjmpTable and
133 ///    sejmpTableSize as follows:
134 ///      setjmpTableSize = 4;
135 ///      setjmpTable = (int *) malloc(40);
136 ///      setjmpTable[0] = 0;
137 ///    setjmpTable and setjmpTableSize are used to call saveSetjmp() function in
138 ///    Emscripten compiler-rt.
139 ///
140 /// 3) Lower
141 ///      setjmp(env)
142 ///    into
143 ///      setjmpTable = saveSetjmp(env, label, setjmpTable, setjmpTableSize);
144 ///      setjmpTableSize = getTempRet0();
145 ///    For each dynamic setjmp call, setjmpTable stores its ID (a number which
146 ///    is incrementally assigned from 0) and its label (a unique number that
147 ///    represents each callsite of setjmp). When we need more entries in
148 ///    setjmpTable, it is reallocated in saveSetjmp() in Emscripten's
149 ///    compiler-rt and it will return the new table address, and assign the new
150 ///    table size in setTempRet0(). saveSetjmp also stores the setjmp's ID into
151 ///    the buffer 'env'. A BB with setjmp is split into two after setjmp call in
152 ///    order to make the post-setjmp BB the possible destination of longjmp BB.
153 ///
154 /// 4) Lower every call that might longjmp into
155 ///      __THREW__ = 0;
156 ///      call @__invoke_SIG(func, arg1, arg2)
157 ///      %__THREW__.val = __THREW__;
158 ///      __THREW__ = 0;
159 ///      %__threwValue.val = __threwValue;
160 ///      if (%__THREW__.val != 0 & %__threwValue.val != 0) {
161 ///        %label = testSetjmp(mem[%__THREW__.val], setjmpTable,
162 ///                            setjmpTableSize);
163 ///        if (%label == 0)
164 ///          emscripten_longjmp(%__THREW__.val, %__threwValue.val);
165 ///        setTempRet0(%__threwValue.val);
166 ///      } else {
167 ///        %label = -1;
168 ///      }
169 ///      longjmp_result = getTempRet0();
170 ///      switch %label {
171 ///        label 1: goto post-setjmp BB 1
172 ///        label 2: goto post-setjmp BB 2
173 ///        ...
174 ///        default: goto splitted next BB
175 ///      }
176 ///    testSetjmp examines setjmpTable to see if there is a matching setjmp
177 ///    call. After calling an invoke wrapper, if a longjmp occurred, __THREW__
178 ///    will be the address of matching jmp_buf buffer and __threwValue be the
179 ///    second argument to longjmp. mem[%__THREW__.val] is a setjmp ID that is
180 ///    stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to
181 ///    each setjmp callsite. Label 0 means this longjmp buffer does not
182 ///    correspond to one of the setjmp callsites in this function, so in this
183 ///    case we just chain the longjmp to the caller. Label -1 means no longjmp
184 ///    occurred. Otherwise we jump to the right post-setjmp BB based on the
185 ///    label.
186 ///
187 /// * Wasm setjmp / longjmp handling
188 /// This mode still uses some Emscripten library functions but not JavaScript's
189 /// try-catch mechanism. It instead uses Wasm exception handling intrinsics,
190 /// which will be lowered to exception handling instructions.
191 ///
192 /// If there are calls to longjmp()
193 ///
194 /// 1) Lower
195 ///      longjmp(env, val)
196 ///    into
197 ///      __wasm_longjmp(env, val)
198 ///
199 /// If there are calls to setjmp()
200 ///
201 /// 2) and 3): The same as 2) and 3) in Emscripten SjLj.
202 /// (setjmpTable/setjmpTableSize initialization + setjmp callsite
203 /// transformation)
204 ///
205 /// 4) Create a catchpad with a wasm.catch() intrinsic, which returns the value
206 /// thrown by __wasm_longjmp function. In Emscripten library, we have this
207 /// struct:
208 ///
209 /// struct __WasmLongjmpArgs {
210 ///   void *env;
211 ///   int val;
212 /// };
213 /// struct __WasmLongjmpArgs __wasm_longjmp_args;
214 ///
215 /// The thrown value here is a pointer to __wasm_longjmp_args struct object. We
216 /// use this struct to transfer two values by throwing a single value. Wasm
217 /// throw and catch instructions are capable of throwing and catching multiple
218 /// values, but it also requires multivalue support that is currently not very
219 /// reliable.
220 /// TODO Switch to throwing and catching two values without using the struct
221 ///
222 /// All longjmpable function calls will be converted to an invoke that will
223 /// unwind to this catchpad in case a longjmp occurs. Within the catchpad, we
224 /// test the thrown values using testSetjmp function as we do for Emscripten
225 /// SjLj. The main difference is, in Emscripten SjLj, we need to transform every
226 /// longjmpable callsite into a sequence of code including testSetjmp() call; in
227 /// Wasm SjLj we do the testing in only one place, in this catchpad.
228 ///
229 /// After testing calling testSetjmp(), if the longjmp does not correspond to
230 /// one of the setjmps within the current function, it rethrows the longjmp
231 /// by calling __wasm_longjmp(). If it corresponds to one of setjmps in the
232 /// function, we jump to the beginning of the function, which contains a switch
233 /// to each post-setjmp BB. Again, in Emscripten SjLj, this switch is added for
234 /// every longjmpable callsite; in Wasm SjLj we do this only once at the top of
235 /// the function. (after setjmpTable/setjmpTableSize initialization)
236 ///
237 /// The below is the pseudocode for what we have described
238 ///
239 /// entry:
240 ///   Initialize setjmpTable and setjmpTableSize
241 ///
242 /// setjmp.dispatch:
243 ///    switch %label {
244 ///      label 1: goto post-setjmp BB 1
245 ///      label 2: goto post-setjmp BB 2
246 ///      ...
247 ///      default: goto splitted next BB
248 ///    }
249 /// ...
250 ///
251 /// bb:
252 ///   invoke void @foo() ;; foo is a longjmpable function
253 ///     to label %next unwind label %catch.dispatch.longjmp
254 /// ...
255 ///
256 /// catch.dispatch.longjmp:
257 ///   %0 = catchswitch within none [label %catch.longjmp] unwind to caller
258 ///
259 /// catch.longjmp:
260 ///   %longjmp.args = wasm.catch() ;; struct __WasmLongjmpArgs
261 ///   %env = load 'env' field from __WasmLongjmpArgs
262 ///   %val = load 'val' field from __WasmLongjmpArgs
263 ///   %label = testSetjmp(mem[%env], setjmpTable, setjmpTableSize);
264 ///   if (%label == 0)
265 ///     __wasm_longjmp(%env, %val)
266 ///   catchret to %setjmp.dispatch
267 ///
268 ///===----------------------------------------------------------------------===//
269 
270 #include "Utils/WebAssemblyUtilities.h"
271 #include "WebAssembly.h"
272 #include "WebAssemblyTargetMachine.h"
273 #include "llvm/ADT/StringExtras.h"
274 #include "llvm/CodeGen/TargetPassConfig.h"
275 #include "llvm/CodeGen/WasmEHFuncInfo.h"
276 #include "llvm/IR/DebugInfoMetadata.h"
277 #include "llvm/IR/Dominators.h"
278 #include "llvm/IR/IRBuilder.h"
279 #include "llvm/IR/IntrinsicsWebAssembly.h"
280 #include "llvm/Support/CommandLine.h"
281 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
282 #include "llvm/Transforms/Utils/SSAUpdater.h"
283 #include "llvm/Transforms/Utils/SSAUpdaterBulk.h"
284 
285 using namespace llvm;
286 
287 #define DEBUG_TYPE "wasm-lower-em-ehsjlj"
288 
289 static cl::list<std::string>
290     EHAllowlist("emscripten-cxx-exceptions-allowed",
291                 cl::desc("The list of function names in which Emscripten-style "
292                          "exception handling is enabled (see emscripten "
293                          "EMSCRIPTEN_CATCHING_ALLOWED options)"),
294                 cl::CommaSeparated);
295 
296 namespace {
297 class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
298   bool EnableEmEH;     // Enable Emscripten exception handling
299   bool EnableEmSjLj;   // Enable Emscripten setjmp/longjmp handling
300   bool EnableWasmSjLj; // Enable Wasm setjmp/longjmp handling
301   bool DoSjLj;         // Whether we actually perform setjmp/longjmp handling
302 
303   GlobalVariable *ThrewGV = nullptr;      // __THREW__ (Emscripten)
304   GlobalVariable *ThrewValueGV = nullptr; // __threwValue (Emscripten)
305   Function *GetTempRet0F = nullptr;       // getTempRet0() (Emscripten)
306   Function *SetTempRet0F = nullptr;       // setTempRet0() (Emscripten)
307   Function *ResumeF = nullptr;            // __resumeException() (Emscripten)
308   Function *EHTypeIDF = nullptr;          // llvm.eh.typeid.for() (intrinsic)
309   Function *EmLongjmpF = nullptr;         // emscripten_longjmp() (Emscripten)
310   Function *SaveSetjmpF = nullptr;        // saveSetjmp() (Emscripten)
311   Function *TestSetjmpF = nullptr;        // testSetjmp() (Emscripten)
312   Function *WasmLongjmpF = nullptr;       // __wasm_longjmp() (Emscripten)
313   Function *CatchF = nullptr;             // wasm.catch() (intrinsic)
314 
315   // type of 'struct __WasmLongjmpArgs' defined in emscripten
316   Type *LongjmpArgsTy = nullptr;
317 
318   // __cxa_find_matching_catch_N functions.
319   // Indexed by the number of clauses in an original landingpad instruction.
320   DenseMap<int, Function *> FindMatchingCatches;
321   // Map of <function signature string, invoke_ wrappers>
322   StringMap<Function *> InvokeWrappers;
323   // Set of allowed function names for exception handling
324   std::set<std::string> EHAllowlistSet;
325   // Functions that contains calls to setjmp
326   SmallPtrSet<Function *, 8> SetjmpUsers;
327 
328   StringRef getPassName() const override {
329     return "WebAssembly Lower Emscripten Exceptions";
330   }
331 
332   using InstVector = SmallVectorImpl<Instruction *>;
333   bool runEHOnFunction(Function &F);
334   bool runSjLjOnFunction(Function &F);
335   void handleLongjmpableCallsForEmscriptenSjLj(
336       Function &F, InstVector &SetjmpTableInsts,
337       InstVector &SetjmpTableSizeInsts,
338       SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
339   void
340   handleLongjmpableCallsForWasmSjLj(Function &F, InstVector &SetjmpTableInsts,
341                                     InstVector &SetjmpTableSizeInsts,
342                                     SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
343   Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
344 
345   Value *wrapInvoke(CallBase *CI);
346   void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw,
347                       Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
348                       Value *&LongjmpResult, BasicBlock *&CallEmLongjmpBB,
349                       PHINode *&CallEmLongjmpBBThrewPHI,
350                       PHINode *&CallEmLongjmpBBThrewValuePHI,
351                       BasicBlock *&EndBB);
352   Function *getInvokeWrapper(CallBase *CI);
353 
354   bool areAllExceptionsAllowed() const { return EHAllowlistSet.empty(); }
355   bool supportsException(const Function *F) const {
356     return EnableEmEH && (areAllExceptionsAllowed() ||
357                           EHAllowlistSet.count(std::string(F->getName())));
358   }
359   void replaceLongjmpWith(Function *LongjmpF, Function *NewF);
360 
361   void rebuildSSA(Function &F);
362 
363 public:
364   static char ID;
365 
366   WebAssemblyLowerEmscriptenEHSjLj()
367       : ModulePass(ID), EnableEmEH(WebAssembly::WasmEnableEmEH),
368         EnableEmSjLj(WebAssembly::WasmEnableEmSjLj),
369         EnableWasmSjLj(WebAssembly::WasmEnableSjLj) {
370     assert(!(EnableEmSjLj && EnableWasmSjLj) &&
371            "Two SjLj modes cannot be turned on at the same time");
372     assert(!(EnableEmEH && EnableWasmSjLj) &&
373            "Wasm SjLj should be only used with Wasm EH");
374     EHAllowlistSet.insert(EHAllowlist.begin(), EHAllowlist.end());
375   }
376   bool runOnModule(Module &M) override;
377 
378   void getAnalysisUsage(AnalysisUsage &AU) const override {
379     AU.addRequired<DominatorTreeWrapperPass>();
380   }
381 };
382 } // End anonymous namespace
383 
384 char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
385 INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
386                 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
387                 false, false)
388 
389 ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj() {
390   return new WebAssemblyLowerEmscriptenEHSjLj();
391 }
392 
393 static bool canThrow(const Value *V) {
394   if (const auto *F = dyn_cast<const Function>(V)) {
395     // Intrinsics cannot throw
396     if (F->isIntrinsic())
397       return false;
398     StringRef Name = F->getName();
399     // leave setjmp and longjmp (mostly) alone, we process them properly later
400     if (Name == "setjmp" || Name == "longjmp" || Name == "emscripten_longjmp")
401       return false;
402     return !F->doesNotThrow();
403   }
404   // not a function, so an indirect call - can throw, we can't tell
405   return true;
406 }
407 
408 // Get a global variable with the given name. If it doesn't exist declare it,
409 // which will generate an import and assume that it will exist at link time.
410 static GlobalVariable *getGlobalVariable(Module &M, Type *Ty,
411                                          WebAssemblyTargetMachine &TM,
412                                          const char *Name) {
413   auto *GV = dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, Ty));
414   if (!GV)
415     report_fatal_error(Twine("unable to create global: ") + Name);
416 
417   // If the target supports TLS, make this variable thread-local. We can't just
418   // unconditionally make it thread-local and depend on
419   // CoalesceFeaturesAndStripAtomics to downgrade it, because stripping TLS has
420   // the side effect of disallowing the object from being linked into a
421   // shared-memory module, which we don't want to be responsible for.
422   auto *Subtarget = TM.getSubtargetImpl();
423   auto TLS = Subtarget->hasAtomics() && Subtarget->hasBulkMemory()
424                  ? GlobalValue::LocalExecTLSModel
425                  : GlobalValue::NotThreadLocal;
426   GV->setThreadLocalMode(TLS);
427   return GV;
428 }
429 
430 // Simple function name mangler.
431 // This function simply takes LLVM's string representation of parameter types
432 // and concatenate them with '_'. There are non-alphanumeric characters but llc
433 // is ok with it, and we need to postprocess these names after the lowering
434 // phase anyway.
435 static std::string getSignature(FunctionType *FTy) {
436   std::string Sig;
437   raw_string_ostream OS(Sig);
438   OS << *FTy->getReturnType();
439   for (Type *ParamTy : FTy->params())
440     OS << "_" << *ParamTy;
441   if (FTy->isVarArg())
442     OS << "_...";
443   Sig = OS.str();
444   erase_if(Sig, isSpace);
445   // When s2wasm parses .s file, a comma means the end of an argument. So a
446   // mangled function name can contain any character but a comma.
447   std::replace(Sig.begin(), Sig.end(), ',', '.');
448   return Sig;
449 }
450 
451 static Function *getEmscriptenFunction(FunctionType *Ty, const Twine &Name,
452                                        Module *M) {
453   Function* F = Function::Create(Ty, GlobalValue::ExternalLinkage, Name, M);
454   // Tell the linker that this function is expected to be imported from the
455   // 'env' module.
456   if (!F->hasFnAttribute("wasm-import-module")) {
457     llvm::AttrBuilder B;
458     B.addAttribute("wasm-import-module", "env");
459     F->addFnAttrs(B);
460   }
461   if (!F->hasFnAttribute("wasm-import-name")) {
462     llvm::AttrBuilder B;
463     B.addAttribute("wasm-import-name", F->getName());
464     F->addFnAttrs(B);
465   }
466   return F;
467 }
468 
469 // Returns an integer type for the target architecture's address space.
470 // i32 for wasm32 and i64 for wasm64.
471 static Type *getAddrIntType(Module *M) {
472   IRBuilder<> IRB(M->getContext());
473   return IRB.getIntNTy(M->getDataLayout().getPointerSizeInBits());
474 }
475 
476 // Returns an integer pointer type for the target architecture's address space.
477 // i32* for wasm32 and i64* for wasm64.
478 static Type *getAddrPtrType(Module *M) {
479   return Type::getIntNPtrTy(M->getContext(),
480                             M->getDataLayout().getPointerSizeInBits());
481 }
482 
483 // Returns an integer whose type is the integer type for the target's address
484 // space. Returns (i32 C) for wasm32 and (i64 C) for wasm64, when C is the
485 // integer.
486 static Value *getAddrSizeInt(Module *M, uint64_t C) {
487   IRBuilder<> IRB(M->getContext());
488   return IRB.getIntN(M->getDataLayout().getPointerSizeInBits(), C);
489 }
490 
491 // Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
492 // This is because a landingpad instruction contains two more arguments, a
493 // personality function and a cleanup bit, and __cxa_find_matching_catch_N
494 // functions are named after the number of arguments in the original landingpad
495 // instruction.
496 Function *
497 WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
498                                                        unsigned NumClauses) {
499   if (FindMatchingCatches.count(NumClauses))
500     return FindMatchingCatches[NumClauses];
501   PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
502   SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
503   FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
504   Function *F = getEmscriptenFunction(
505       FTy, "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M);
506   FindMatchingCatches[NumClauses] = F;
507   return F;
508 }
509 
510 // Generate invoke wrapper seqence with preamble and postamble
511 // Preamble:
512 // __THREW__ = 0;
513 // Postamble:
514 // %__THREW__.val = __THREW__; __THREW__ = 0;
515 // Returns %__THREW__.val, which indicates whether an exception is thrown (or
516 // whether longjmp occurred), for future use.
517 Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) {
518   Module *M = CI->getModule();
519   LLVMContext &C = M->getContext();
520 
521   IRBuilder<> IRB(C);
522   IRB.SetInsertPoint(CI);
523 
524   // Pre-invoke
525   // __THREW__ = 0;
526   IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
527 
528   // Invoke function wrapper in JavaScript
529   SmallVector<Value *, 16> Args;
530   // Put the pointer to the callee as first argument, so it can be called
531   // within the invoke wrapper later
532   Args.push_back(CI->getCalledOperand());
533   Args.append(CI->arg_begin(), CI->arg_end());
534   CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
535   NewCall->takeName(CI);
536   NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke);
537   NewCall->setDebugLoc(CI->getDebugLoc());
538 
539   // Because we added the pointer to the callee as first argument, all
540   // argument attribute indices have to be incremented by one.
541   SmallVector<AttributeSet, 8> ArgAttributes;
542   const AttributeList &InvokeAL = CI->getAttributes();
543 
544   // No attributes for the callee pointer.
545   ArgAttributes.push_back(AttributeSet());
546   // Copy the argument attributes from the original
547   for (unsigned I = 0, E = CI->arg_size(); I < E; ++I)
548     ArgAttributes.push_back(InvokeAL.getParamAttrs(I));
549 
550   AttrBuilder FnAttrs(InvokeAL.getFnAttrs());
551   if (FnAttrs.contains(Attribute::AllocSize)) {
552     // The allocsize attribute (if any) referes to parameters by index and needs
553     // to be adjusted.
554     unsigned SizeArg;
555     Optional<unsigned> NEltArg;
556     std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs();
557     SizeArg += 1;
558     if (NEltArg.hasValue())
559       NEltArg = NEltArg.getValue() + 1;
560     FnAttrs.addAllocSizeAttr(SizeArg, NEltArg);
561   }
562 
563   // Reconstruct the AttributesList based on the vector we constructed.
564   AttributeList NewCallAL = AttributeList::get(
565       C, AttributeSet::get(C, FnAttrs), InvokeAL.getRetAttrs(), ArgAttributes);
566   NewCall->setAttributes(NewCallAL);
567 
568   CI->replaceAllUsesWith(NewCall);
569 
570   // Post-invoke
571   // %__THREW__.val = __THREW__; __THREW__ = 0;
572   Value *Threw =
573       IRB.CreateLoad(getAddrIntType(M), ThrewGV, ThrewGV->getName() + ".val");
574   IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
575   return Threw;
576 }
577 
578 // Get matching invoke wrapper based on callee signature
579 Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallBase *CI) {
580   Module *M = CI->getModule();
581   SmallVector<Type *, 16> ArgTys;
582   FunctionType *CalleeFTy = CI->getFunctionType();
583 
584   std::string Sig = getSignature(CalleeFTy);
585   if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
586     return InvokeWrappers[Sig];
587 
588   // Put the pointer to the callee as first argument
589   ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
590   // Add argument types
591   ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
592 
593   FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
594                                         CalleeFTy->isVarArg());
595   Function *F = getEmscriptenFunction(FTy, "__invoke_" + Sig, M);
596   InvokeWrappers[Sig] = F;
597   return F;
598 }
599 
600 static bool canLongjmp(const Value *Callee) {
601   if (auto *CalleeF = dyn_cast<Function>(Callee))
602     if (CalleeF->isIntrinsic())
603       return false;
604 
605   // Attempting to transform inline assembly will result in something like:
606   //     call void @__invoke_void(void ()* asm ...)
607   // which is invalid because inline assembly blocks do not have addresses
608   // and can't be passed by pointer. The result is a crash with illegal IR.
609   if (isa<InlineAsm>(Callee))
610     return false;
611   StringRef CalleeName = Callee->getName();
612 
613   // The reason we include malloc/free here is to exclude the malloc/free
614   // calls generated in setjmp prep / cleanup routines.
615   if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free")
616     return false;
617 
618   // There are functions in Emscripten's JS glue code or compiler-rt
619   if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" ||
620       CalleeName == "saveSetjmp" || CalleeName == "testSetjmp" ||
621       CalleeName == "getTempRet0" || CalleeName == "setTempRet0")
622     return false;
623 
624   // __cxa_find_matching_catch_N functions cannot longjmp
625   if (Callee->getName().startswith("__cxa_find_matching_catch_"))
626     return false;
627 
628   // Exception-catching related functions
629   if (CalleeName == "__cxa_begin_catch" || CalleeName == "__cxa_end_catch" ||
630       CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" ||
631       CalleeName == "__clang_call_terminate")
632     return false;
633 
634   // Otherwise we don't know
635   return true;
636 }
637 
638 static bool isEmAsmCall(const Value *Callee) {
639   StringRef CalleeName = Callee->getName();
640   // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>.
641   return CalleeName == "emscripten_asm_const_int" ||
642          CalleeName == "emscripten_asm_const_double" ||
643          CalleeName == "emscripten_asm_const_int_sync_on_main_thread" ||
644          CalleeName == "emscripten_asm_const_double_sync_on_main_thread" ||
645          CalleeName == "emscripten_asm_const_async_on_main_thread";
646 }
647 
648 // Generate testSetjmp function call seqence with preamble and postamble.
649 // The code this generates is equivalent to the following JavaScript code:
650 // %__threwValue.val = __threwValue;
651 // if (%__THREW__.val != 0 & %__threwValue.val != 0) {
652 //   %label = testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
653 //   if (%label == 0)
654 //     emscripten_longjmp(%__THREW__.val, %__threwValue.val);
655 //   setTempRet0(%__threwValue.val);
656 // } else {
657 //   %label = -1;
658 // }
659 // %longjmp_result = getTempRet0();
660 //
661 // As output parameters. returns %label, %longjmp_result, and the BB the last
662 // instruction (%longjmp_result = ...) is in.
663 void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
664     BasicBlock *BB, DebugLoc DL, Value *Threw, Value *SetjmpTable,
665     Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
666     BasicBlock *&CallEmLongjmpBB, PHINode *&CallEmLongjmpBBThrewPHI,
667     PHINode *&CallEmLongjmpBBThrewValuePHI, BasicBlock *&EndBB) {
668   Function *F = BB->getParent();
669   Module *M = F->getParent();
670   LLVMContext &C = M->getContext();
671   IRBuilder<> IRB(C);
672   IRB.SetCurrentDebugLocation(DL);
673 
674   // if (%__THREW__.val != 0 & %__threwValue.val != 0)
675   IRB.SetInsertPoint(BB);
676   BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
677   BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
678   BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
679   Value *ThrewCmp = IRB.CreateICmpNE(Threw, getAddrSizeInt(M, 0));
680   Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
681                                      ThrewValueGV->getName() + ".val");
682   Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
683   Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
684   IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
685 
686   // Generate call.em.longjmp BB once and share it within the function
687   if (!CallEmLongjmpBB) {
688     // emscripten_longjmp(%__THREW__.val, %__threwValue.val);
689     CallEmLongjmpBB = BasicBlock::Create(C, "call.em.longjmp", F);
690     IRB.SetInsertPoint(CallEmLongjmpBB);
691     CallEmLongjmpBBThrewPHI = IRB.CreatePHI(getAddrIntType(M), 4, "threw.phi");
692     CallEmLongjmpBBThrewValuePHI =
693         IRB.CreatePHI(IRB.getInt32Ty(), 4, "threwvalue.phi");
694     CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1);
695     CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1);
696     IRB.CreateCall(EmLongjmpF,
697                    {CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI});
698     IRB.CreateUnreachable();
699   } else {
700     CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1);
701     CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1);
702   }
703 
704   // %label = testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
705   // if (%label == 0)
706   IRB.SetInsertPoint(ThenBB1);
707   BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
708   Value *ThrewPtr =
709       IRB.CreateIntToPtr(Threw, getAddrPtrType(M), Threw->getName() + ".p");
710   Value *LoadedThrew = IRB.CreateLoad(getAddrIntType(M), ThrewPtr,
711                                       ThrewPtr->getName() + ".loaded");
712   Value *ThenLabel = IRB.CreateCall(
713       TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
714   Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
715   IRB.CreateCondBr(Cmp2, CallEmLongjmpBB, EndBB2);
716 
717   // setTempRet0(%__threwValue.val);
718   IRB.SetInsertPoint(EndBB2);
719   IRB.CreateCall(SetTempRet0F, ThrewValue);
720   IRB.CreateBr(EndBB1);
721 
722   IRB.SetInsertPoint(ElseBB1);
723   IRB.CreateBr(EndBB1);
724 
725   // longjmp_result = getTempRet0();
726   IRB.SetInsertPoint(EndBB1);
727   PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
728   LabelPHI->addIncoming(ThenLabel, EndBB2);
729 
730   LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
731 
732   // Output parameter assignment
733   Label = LabelPHI;
734   EndBB = EndBB1;
735   LongjmpResult = IRB.CreateCall(GetTempRet0F, None, "longjmp_result");
736 }
737 
738 void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
739   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
740   DT.recalculate(F); // CFG has been changed
741 
742   SSAUpdaterBulk SSA;
743   for (BasicBlock &BB : F) {
744     for (Instruction &I : BB) {
745       unsigned VarID = SSA.AddVariable(I.getName(), I.getType());
746       // If a value is defined by an invoke instruction, it is only available in
747       // its normal destination and not in its unwind destination.
748       if (auto *II = dyn_cast<InvokeInst>(&I))
749         SSA.AddAvailableValue(VarID, II->getNormalDest(), II);
750       else
751         SSA.AddAvailableValue(VarID, &BB, &I);
752       for (auto &U : I.uses()) {
753         auto *User = cast<Instruction>(U.getUser());
754         if (auto *UserPN = dyn_cast<PHINode>(User))
755           if (UserPN->getIncomingBlock(U) == &BB)
756             continue;
757         if (DT.dominates(&I, User))
758           continue;
759         SSA.AddUse(VarID, &U);
760       }
761     }
762   }
763   SSA.RewriteAllUses(&DT);
764 }
765 
766 // Replace uses of longjmp with a new longjmp function in Emscripten library.
767 // In Emscripten SjLj, the new function is
768 //   void emscripten_longjmp(uintptr_t, i32)
769 // In Wasm SjLj, the new function is
770 //   void __wasm_longjmp(i8*, i32)
771 // Because the original libc longjmp function takes (jmp_buf*, i32), we need a
772 // ptrtoint/bitcast instruction here to make the type match. jmp_buf* will
773 // eventually be lowered to i32/i64 in the wasm backend.
774 void WebAssemblyLowerEmscriptenEHSjLj::replaceLongjmpWith(Function *LongjmpF,
775                                                           Function *NewF) {
776   assert(NewF == EmLongjmpF || NewF == WasmLongjmpF);
777   Module *M = LongjmpF->getParent();
778   SmallVector<CallInst *, 8> ToErase;
779   LLVMContext &C = LongjmpF->getParent()->getContext();
780   IRBuilder<> IRB(C);
781 
782   // For calls to longjmp, replace it with emscripten_longjmp/__wasm_longjmp and
783   // cast its first argument (jmp_buf*) appropriately
784   for (User *U : LongjmpF->users()) {
785     auto *CI = dyn_cast<CallInst>(U);
786     if (CI && CI->getCalledFunction() == LongjmpF) {
787       IRB.SetInsertPoint(CI);
788       Value *Env = nullptr;
789       if (NewF == EmLongjmpF)
790         Env =
791             IRB.CreatePtrToInt(CI->getArgOperand(0), getAddrIntType(M), "env");
792       else // WasmLongjmpF
793         Env =
794             IRB.CreateBitCast(CI->getArgOperand(0), IRB.getInt8PtrTy(), "env");
795       IRB.CreateCall(NewF, {Env, CI->getArgOperand(1)});
796       ToErase.push_back(CI);
797     }
798   }
799   for (auto *I : ToErase)
800     I->eraseFromParent();
801 
802   // If we have any remaining uses of longjmp's function pointer, replace it
803   // with (void(*)(jmp_buf*, int))emscripten_longjmp / __wasm_longjmp.
804   if (!LongjmpF->uses().empty()) {
805     Value *NewLongjmp =
806         IRB.CreateBitCast(NewF, LongjmpF->getType(), "longjmp.cast");
807     LongjmpF->replaceAllUsesWith(NewLongjmp);
808   }
809 }
810 
811 static bool containsLongjmpableCalls(const Function *F) {
812   for (const auto &BB : *F)
813     for (const auto &I : BB)
814       if (const auto *CB = dyn_cast<CallBase>(&I))
815         if (canLongjmp(CB->getCalledOperand()))
816           return true;
817   return false;
818 }
819 
820 // When a function contains a setjmp call but not other calls that can longjmp,
821 // we don't do setjmp transformation for that setjmp. But we need to convert the
822 // setjmp calls into "i32 0" so they don't cause link time errors. setjmp always
823 // returns 0 when called directly.
824 static void nullifySetjmp(Function *F) {
825   Module &M = *F->getParent();
826   IRBuilder<> IRB(M.getContext());
827   Function *SetjmpF = M.getFunction("setjmp");
828   SmallVector<Instruction *, 1> ToErase;
829 
830   for (User *U : SetjmpF->users()) {
831     auto *CI = dyn_cast<CallInst>(U);
832     // FIXME 'invoke' to setjmp can happen when we use Wasm EH + Wasm SjLj, but
833     // we don't support two being used together yet.
834     if (!CI)
835       report_fatal_error("Wasm EH + Wasm SjLj is not fully supported yet");
836     BasicBlock *BB = CI->getParent();
837     if (BB->getParent() != F) // in other function
838       continue;
839     ToErase.push_back(CI);
840     CI->replaceAllUsesWith(IRB.getInt32(0));
841   }
842   for (auto *I : ToErase)
843     I->eraseFromParent();
844 }
845 
846 bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
847   LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
848 
849   LLVMContext &C = M.getContext();
850   IRBuilder<> IRB(C);
851 
852   Function *SetjmpF = M.getFunction("setjmp");
853   Function *LongjmpF = M.getFunction("longjmp");
854 
855   // In some platforms _setjmp and _longjmp are used instead. Change these to
856   // use setjmp/longjmp instead, because we later detect these functions by
857   // their names.
858   Function *SetjmpF2 = M.getFunction("_setjmp");
859   Function *LongjmpF2 = M.getFunction("_longjmp");
860   if (SetjmpF2) {
861     if (SetjmpF) {
862       if (SetjmpF->getFunctionType() != SetjmpF2->getFunctionType())
863         report_fatal_error("setjmp and _setjmp have different function types");
864     } else {
865       SetjmpF = Function::Create(SetjmpF2->getFunctionType(),
866                                  GlobalValue::ExternalLinkage, "setjmp", M);
867     }
868     SetjmpF2->replaceAllUsesWith(SetjmpF);
869   }
870   if (LongjmpF2) {
871     if (LongjmpF) {
872       if (LongjmpF->getFunctionType() != LongjmpF2->getFunctionType())
873         report_fatal_error(
874             "longjmp and _longjmp have different function types");
875     } else {
876       LongjmpF = Function::Create(LongjmpF2->getFunctionType(),
877                                   GlobalValue::ExternalLinkage, "setjmp", M);
878     }
879     LongjmpF2->replaceAllUsesWith(LongjmpF);
880   }
881 
882   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
883   assert(TPC && "Expected a TargetPassConfig");
884   auto &TM = TPC->getTM<WebAssemblyTargetMachine>();
885 
886   // Declare (or get) global variables __THREW__, __threwValue, and
887   // getTempRet0/setTempRet0 function which are used in common for both
888   // exception handling and setjmp/longjmp handling
889   ThrewGV = getGlobalVariable(M, getAddrIntType(&M), TM, "__THREW__");
890   ThrewValueGV = getGlobalVariable(M, IRB.getInt32Ty(), TM, "__threwValue");
891   GetTempRet0F = getEmscriptenFunction(
892       FunctionType::get(IRB.getInt32Ty(), false), "getTempRet0", &M);
893   SetTempRet0F = getEmscriptenFunction(
894       FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
895       "setTempRet0", &M);
896   GetTempRet0F->setDoesNotThrow();
897   SetTempRet0F->setDoesNotThrow();
898 
899   bool Changed = false;
900 
901   // Function registration for exception handling
902   if (EnableEmEH) {
903     // Register __resumeException function
904     FunctionType *ResumeFTy =
905         FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
906     ResumeF = getEmscriptenFunction(ResumeFTy, "__resumeException", &M);
907     ResumeF->addFnAttr(Attribute::NoReturn);
908 
909     // Register llvm_eh_typeid_for function
910     FunctionType *EHTypeIDTy =
911         FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
912     EHTypeIDF = getEmscriptenFunction(EHTypeIDTy, "llvm_eh_typeid_for", &M);
913   }
914 
915   // Functions that contains calls to setjmp but don't have other longjmpable
916   // calls within them.
917   SmallPtrSet<Function *, 4> SetjmpUsersToNullify;
918 
919   if ((EnableEmSjLj || EnableWasmSjLj) && SetjmpF) {
920     // Precompute setjmp users
921     for (User *U : SetjmpF->users()) {
922       if (auto *CB = dyn_cast<CallBase>(U)) {
923         auto *UserF = CB->getFunction();
924         // If a function that calls setjmp does not contain any other calls that
925         // can longjmp, we don't need to do any transformation on that function,
926         // so can ignore it
927         if (containsLongjmpableCalls(UserF))
928           SetjmpUsers.insert(UserF);
929         else
930           SetjmpUsersToNullify.insert(UserF);
931       } else {
932         std::string S;
933         raw_string_ostream SS(S);
934         SS << *U;
935         report_fatal_error(Twine("Indirect use of setjmp is not supported: ") +
936                            SS.str());
937       }
938     }
939   }
940 
941   bool SetjmpUsed = SetjmpF && !SetjmpUsers.empty();
942   bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
943   DoSjLj = (EnableEmSjLj | EnableWasmSjLj) && (SetjmpUsed || LongjmpUsed);
944 
945   // Function registration and data pre-gathering for setjmp/longjmp handling
946   if (DoSjLj) {
947     assert(EnableEmSjLj || EnableWasmSjLj);
948     if (EnableEmSjLj) {
949       // Register emscripten_longjmp function
950       FunctionType *FTy = FunctionType::get(
951           IRB.getVoidTy(), {getAddrIntType(&M), IRB.getInt32Ty()}, false);
952       EmLongjmpF = getEmscriptenFunction(FTy, "emscripten_longjmp", &M);
953       EmLongjmpF->addFnAttr(Attribute::NoReturn);
954     } else { // EnableWasmSjLj
955       // Register __wasm_longjmp function, which calls __builtin_wasm_longjmp.
956       FunctionType *FTy = FunctionType::get(
957           IRB.getVoidTy(), {IRB.getInt8PtrTy(), IRB.getInt32Ty()}, false);
958       WasmLongjmpF = getEmscriptenFunction(FTy, "__wasm_longjmp", &M);
959       WasmLongjmpF->addFnAttr(Attribute::NoReturn);
960     }
961 
962     if (SetjmpF) {
963       // Register saveSetjmp function
964       FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
965       FunctionType *FTy =
966           FunctionType::get(Type::getInt32PtrTy(C),
967                             {SetjmpFTy->getParamType(0), IRB.getInt32Ty(),
968                              Type::getInt32PtrTy(C), IRB.getInt32Ty()},
969                             false);
970       SaveSetjmpF = getEmscriptenFunction(FTy, "saveSetjmp", &M);
971 
972       // Register testSetjmp function
973       FTy = FunctionType::get(
974           IRB.getInt32Ty(),
975           {getAddrIntType(&M), Type::getInt32PtrTy(C), IRB.getInt32Ty()},
976           false);
977       TestSetjmpF = getEmscriptenFunction(FTy, "testSetjmp", &M);
978 
979       // wasm.catch() will be lowered down to wasm 'catch' instruction in
980       // instruction selection.
981       CatchF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_catch);
982       // Type for struct __WasmLongjmpArgs
983       LongjmpArgsTy = StructType::get(IRB.getInt8PtrTy(), // env
984                                       IRB.getInt32Ty()    // val
985       );
986     }
987   }
988 
989   // Exception handling transformation
990   if (EnableEmEH) {
991     for (Function &F : M) {
992       if (F.isDeclaration())
993         continue;
994       Changed |= runEHOnFunction(F);
995     }
996   }
997 
998   // Setjmp/longjmp handling transformation
999   if (DoSjLj) {
1000     Changed = true; // We have setjmp or longjmp somewhere
1001     if (LongjmpF)
1002       replaceLongjmpWith(LongjmpF, EnableEmSjLj ? EmLongjmpF : WasmLongjmpF);
1003     // Only traverse functions that uses setjmp in order not to insert
1004     // unnecessary prep / cleanup code in every function
1005     if (SetjmpF)
1006       for (Function *F : SetjmpUsers)
1007         runSjLjOnFunction(*F);
1008   }
1009 
1010   // Replace unnecessary setjmp calls with 0
1011   if ((EnableEmSjLj || EnableWasmSjLj) && !SetjmpUsersToNullify.empty()) {
1012     Changed = true;
1013     assert(SetjmpF);
1014     for (Function *F : SetjmpUsersToNullify)
1015       nullifySetjmp(F);
1016   }
1017 
1018   if (!Changed) {
1019     // Delete unused global variables and functions
1020     if (ResumeF)
1021       ResumeF->eraseFromParent();
1022     if (EHTypeIDF)
1023       EHTypeIDF->eraseFromParent();
1024     if (EmLongjmpF)
1025       EmLongjmpF->eraseFromParent();
1026     if (SaveSetjmpF)
1027       SaveSetjmpF->eraseFromParent();
1028     if (TestSetjmpF)
1029       TestSetjmpF->eraseFromParent();
1030     return false;
1031   }
1032 
1033   return true;
1034 }
1035 
1036 bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
1037   Module &M = *F.getParent();
1038   LLVMContext &C = F.getContext();
1039   IRBuilder<> IRB(C);
1040   bool Changed = false;
1041   SmallVector<Instruction *, 64> ToErase;
1042   SmallPtrSet<LandingPadInst *, 32> LandingPads;
1043 
1044   // rethrow.longjmp BB that will be shared within the function.
1045   BasicBlock *RethrowLongjmpBB = nullptr;
1046   // PHI node for the loaded value of __THREW__ global variable in
1047   // rethrow.longjmp BB
1048   PHINode *RethrowLongjmpBBThrewPHI = nullptr;
1049 
1050   for (BasicBlock &BB : F) {
1051     auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
1052     if (!II)
1053       continue;
1054     Changed = true;
1055     LandingPads.insert(II->getLandingPadInst());
1056     IRB.SetInsertPoint(II);
1057 
1058     const Value *Callee = II->getCalledOperand();
1059     bool NeedInvoke = supportsException(&F) && canThrow(Callee);
1060     if (NeedInvoke) {
1061       // Wrap invoke with invoke wrapper and generate preamble/postamble
1062       Value *Threw = wrapInvoke(II);
1063       ToErase.push_back(II);
1064 
1065       // If setjmp/longjmp handling is enabled, the thrown value can be not an
1066       // exception but a longjmp. If the current function contains calls to
1067       // setjmp, it will be appropriately handled in runSjLjOnFunction. But even
1068       // if the function does not contain setjmp calls, we shouldn't silently
1069       // ignore longjmps; we should rethrow them so they can be correctly
1070       // handled in somewhere up the call chain where setjmp is. __THREW__'s
1071       // value is 0 when nothing happened, 1 when an exception is thrown, and
1072       // other values when longjmp is thrown.
1073       //
1074       // if (%__THREW__.val == 0 || %__THREW__.val == 1)
1075       //   goto %tail
1076       // else
1077       //   goto %longjmp.rethrow
1078       //
1079       // rethrow.longjmp: ;; This is longjmp. Rethrow it
1080       //   %__threwValue.val = __threwValue
1081       //   emscripten_longjmp(%__THREW__.val, %__threwValue.val);
1082       //
1083       // tail: ;; Nothing happened or an exception is thrown
1084       //   ... Continue exception handling ...
1085       if (DoSjLj && EnableEmSjLj && !SetjmpUsers.count(&F) &&
1086           canLongjmp(Callee)) {
1087         // Create longjmp.rethrow BB once and share it within the function
1088         if (!RethrowLongjmpBB) {
1089           RethrowLongjmpBB = BasicBlock::Create(C, "rethrow.longjmp", &F);
1090           IRB.SetInsertPoint(RethrowLongjmpBB);
1091           RethrowLongjmpBBThrewPHI =
1092               IRB.CreatePHI(getAddrIntType(&M), 4, "threw.phi");
1093           RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB);
1094           Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
1095                                              ThrewValueGV->getName() + ".val");
1096           IRB.CreateCall(EmLongjmpF, {RethrowLongjmpBBThrewPHI, ThrewValue});
1097           IRB.CreateUnreachable();
1098         } else {
1099           RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB);
1100         }
1101 
1102         IRB.SetInsertPoint(II); // Restore the insert point back
1103         BasicBlock *Tail = BasicBlock::Create(C, "tail", &F);
1104         Value *CmpEqOne =
1105             IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
1106         Value *CmpEqZero =
1107             IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 0), "cmp.eq.zero");
1108         Value *Or = IRB.CreateOr(CmpEqZero, CmpEqOne, "or");
1109         IRB.CreateCondBr(Or, Tail, RethrowLongjmpBB);
1110         IRB.SetInsertPoint(Tail);
1111         BB.replaceSuccessorsPhiUsesWith(&BB, Tail);
1112       }
1113 
1114       // Insert a branch based on __THREW__ variable
1115       Value *Cmp = IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp");
1116       IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
1117 
1118     } else {
1119       // This can't throw, and we don't need this invoke, just replace it with a
1120       // call+branch
1121       SmallVector<Value *, 16> Args(II->args());
1122       CallInst *NewCall =
1123           IRB.CreateCall(II->getFunctionType(), II->getCalledOperand(), Args);
1124       NewCall->takeName(II);
1125       NewCall->setCallingConv(II->getCallingConv());
1126       NewCall->setDebugLoc(II->getDebugLoc());
1127       NewCall->setAttributes(II->getAttributes());
1128       II->replaceAllUsesWith(NewCall);
1129       ToErase.push_back(II);
1130 
1131       IRB.CreateBr(II->getNormalDest());
1132 
1133       // Remove any PHI node entries from the exception destination
1134       II->getUnwindDest()->removePredecessor(&BB);
1135     }
1136   }
1137 
1138   // Process resume instructions
1139   for (BasicBlock &BB : F) {
1140     // Scan the body of the basic block for resumes
1141     for (Instruction &I : BB) {
1142       auto *RI = dyn_cast<ResumeInst>(&I);
1143       if (!RI)
1144         continue;
1145       Changed = true;
1146 
1147       // Split the input into legal values
1148       Value *Input = RI->getValue();
1149       IRB.SetInsertPoint(RI);
1150       Value *Low = IRB.CreateExtractValue(Input, 0, "low");
1151       // Create a call to __resumeException function
1152       IRB.CreateCall(ResumeF, {Low});
1153       // Add a terminator to the block
1154       IRB.CreateUnreachable();
1155       ToErase.push_back(RI);
1156     }
1157   }
1158 
1159   // Process llvm.eh.typeid.for intrinsics
1160   for (BasicBlock &BB : F) {
1161     for (Instruction &I : BB) {
1162       auto *CI = dyn_cast<CallInst>(&I);
1163       if (!CI)
1164         continue;
1165       const Function *Callee = CI->getCalledFunction();
1166       if (!Callee)
1167         continue;
1168       if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
1169         continue;
1170       Changed = true;
1171 
1172       IRB.SetInsertPoint(CI);
1173       CallInst *NewCI =
1174           IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
1175       CI->replaceAllUsesWith(NewCI);
1176       ToErase.push_back(CI);
1177     }
1178   }
1179 
1180   // Look for orphan landingpads, can occur in blocks with no predecessors
1181   for (BasicBlock &BB : F) {
1182     Instruction *I = BB.getFirstNonPHI();
1183     if (auto *LPI = dyn_cast<LandingPadInst>(I))
1184       LandingPads.insert(LPI);
1185   }
1186   Changed |= !LandingPads.empty();
1187 
1188   // Handle all the landingpad for this function together, as multiple invokes
1189   // may share a single lp
1190   for (LandingPadInst *LPI : LandingPads) {
1191     IRB.SetInsertPoint(LPI);
1192     SmallVector<Value *, 16> FMCArgs;
1193     for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
1194       Constant *Clause = LPI->getClause(I);
1195       // TODO Handle filters (= exception specifications).
1196       // https://bugs.llvm.org/show_bug.cgi?id=50396
1197       if (LPI->isCatch(I))
1198         FMCArgs.push_back(Clause);
1199     }
1200 
1201     // Create a call to __cxa_find_matching_catch_N function
1202     Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
1203     CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
1204     Value *Undef = UndefValue::get(LPI->getType());
1205     Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
1206     Value *TempRet0 = IRB.CreateCall(GetTempRet0F, None, "tempret0");
1207     Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
1208 
1209     LPI->replaceAllUsesWith(Pair1);
1210     ToErase.push_back(LPI);
1211   }
1212 
1213   // Erase everything we no longer need in this function
1214   for (Instruction *I : ToErase)
1215     I->eraseFromParent();
1216 
1217   return Changed;
1218 }
1219 
1220 // This tries to get debug info from the instruction before which a new
1221 // instruction will be inserted, and if there's no debug info in that
1222 // instruction, tries to get the info instead from the previous instruction (if
1223 // any). If none of these has debug info and a DISubprogram is provided, it
1224 // creates a dummy debug info with the first line of the function, because IR
1225 // verifier requires all inlinable callsites should have debug info when both a
1226 // caller and callee have DISubprogram. If none of these conditions are met,
1227 // returns empty info.
1228 static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore,
1229                                     DISubprogram *SP) {
1230   assert(InsertBefore);
1231   if (InsertBefore->getDebugLoc())
1232     return InsertBefore->getDebugLoc();
1233   const Instruction *Prev = InsertBefore->getPrevNode();
1234   if (Prev && Prev->getDebugLoc())
1235     return Prev->getDebugLoc();
1236   if (SP)
1237     return DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
1238   return DebugLoc();
1239 }
1240 
1241 bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
1242   assert(EnableEmSjLj || EnableWasmSjLj);
1243   Module &M = *F.getParent();
1244   LLVMContext &C = F.getContext();
1245   IRBuilder<> IRB(C);
1246   SmallVector<Instruction *, 64> ToErase;
1247   // Vector of %setjmpTable values
1248   SmallVector<Instruction *, 4> SetjmpTableInsts;
1249   // Vector of %setjmpTableSize values
1250   SmallVector<Instruction *, 4> SetjmpTableSizeInsts;
1251 
1252   // Setjmp preparation
1253 
1254   // This instruction effectively means %setjmpTableSize = 4.
1255   // We create this as an instruction intentionally, and we don't want to fold
1256   // this instruction to a constant 4, because this value will be used in
1257   // SSAUpdater.AddAvailableValue(...) later.
1258   BasicBlock *Entry = &F.getEntryBlock();
1259   DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram());
1260   SplitBlock(Entry, &*Entry->getFirstInsertionPt());
1261 
1262   BinaryOperator *SetjmpTableSize =
1263       BinaryOperator::Create(Instruction::Add, IRB.getInt32(4), IRB.getInt32(0),
1264                              "setjmpTableSize", Entry->getTerminator());
1265   SetjmpTableSize->setDebugLoc(FirstDL);
1266   // setjmpTable = (int *) malloc(40);
1267   Instruction *SetjmpTable = CallInst::CreateMalloc(
1268       SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
1269       nullptr, nullptr, "setjmpTable");
1270   SetjmpTable->setDebugLoc(FirstDL);
1271   // CallInst::CreateMalloc may return a bitcast instruction if the result types
1272   // mismatch. We need to set the debug loc for the original call too.
1273   auto *MallocCall = SetjmpTable->stripPointerCasts();
1274   if (auto *MallocCallI = dyn_cast<Instruction>(MallocCall)) {
1275     MallocCallI->setDebugLoc(FirstDL);
1276   }
1277   // setjmpTable[0] = 0;
1278   IRB.SetInsertPoint(SetjmpTableSize);
1279   IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
1280   SetjmpTableInsts.push_back(SetjmpTable);
1281   SetjmpTableSizeInsts.push_back(SetjmpTableSize);
1282 
1283   // Setjmp transformation
1284   SmallVector<PHINode *, 4> SetjmpRetPHIs;
1285   Function *SetjmpF = M.getFunction("setjmp");
1286   for (User *U : SetjmpF->users()) {
1287     auto *CI = dyn_cast<CallInst>(U);
1288     // FIXME 'invoke' to setjmp can happen when we use Wasm EH + Wasm SjLj, but
1289     // we don't support two being used together yet.
1290     if (!CI)
1291       report_fatal_error("Wasm EH + Wasm SjLj is not fully supported yet");
1292     BasicBlock *BB = CI->getParent();
1293     if (BB->getParent() != &F) // in other function
1294       continue;
1295 
1296     // The tail is everything right after the call, and will be reached once
1297     // when setjmp is called, and later when longjmp returns to the setjmp
1298     BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
1299     // Add a phi to the tail, which will be the output of setjmp, which
1300     // indicates if this is the first call or a longjmp back. The phi directly
1301     // uses the right value based on where we arrive from
1302     IRB.SetInsertPoint(Tail->getFirstNonPHI());
1303     PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
1304 
1305     // setjmp initial call returns 0
1306     SetjmpRet->addIncoming(IRB.getInt32(0), BB);
1307     // The proper output is now this, not the setjmp call itself
1308     CI->replaceAllUsesWith(SetjmpRet);
1309     // longjmp returns to the setjmp will add themselves to this phi
1310     SetjmpRetPHIs.push_back(SetjmpRet);
1311 
1312     // Fix call target
1313     // Our index in the function is our place in the array + 1 to avoid index
1314     // 0, because index 0 means the longjmp is not ours to handle.
1315     IRB.SetInsertPoint(CI);
1316     Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
1317                      SetjmpTable, SetjmpTableSize};
1318     Instruction *NewSetjmpTable =
1319         IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
1320     Instruction *NewSetjmpTableSize =
1321         IRB.CreateCall(GetTempRet0F, None, "setjmpTableSize");
1322     SetjmpTableInsts.push_back(NewSetjmpTable);
1323     SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
1324     ToErase.push_back(CI);
1325   }
1326 
1327   // Handle longjmpable calls.
1328   if (EnableEmSjLj)
1329     handleLongjmpableCallsForEmscriptenSjLj(
1330         F, SetjmpTableInsts, SetjmpTableSizeInsts, SetjmpRetPHIs);
1331   else // EnableWasmSjLj
1332     handleLongjmpableCallsForWasmSjLj(F, SetjmpTableInsts, SetjmpTableSizeInsts,
1333                                       SetjmpRetPHIs);
1334 
1335   // Erase everything we no longer need in this function
1336   for (Instruction *I : ToErase)
1337     I->eraseFromParent();
1338 
1339   // Free setjmpTable buffer before each return instruction + function-exiting
1340   // call
1341   SmallVector<Instruction *, 16> ExitingInsts;
1342   for (BasicBlock &BB : F) {
1343     Instruction *TI = BB.getTerminator();
1344     if (isa<ReturnInst>(TI))
1345       ExitingInsts.push_back(TI);
1346     // Any 'call' instruction with 'noreturn' attribute exits the function at
1347     // this point. If this throws but unwinds to another EH pad within this
1348     // function instead of exiting, this would have been an 'invoke', which
1349     // happens if we use Wasm EH or Wasm SjLJ.
1350     for (auto &I : BB) {
1351       if (auto *CI = dyn_cast<CallInst>(&I)) {
1352         bool IsNoReturn = CI->hasFnAttr(Attribute::NoReturn);
1353         if (Function *CalleeF = CI->getCalledFunction())
1354           IsNoReturn |= CalleeF->hasFnAttribute(Attribute::NoReturn);
1355         if (IsNoReturn)
1356           ExitingInsts.push_back(&I);
1357       }
1358     }
1359   }
1360   for (auto *I : ExitingInsts) {
1361     DebugLoc DL = getOrCreateDebugLoc(I, F.getSubprogram());
1362     // If this existing instruction is a call within a catchpad, we should add
1363     // it as "funclet" to the operand bundle of 'free' call
1364     SmallVector<OperandBundleDef, 1> Bundles;
1365     if (auto *CB = dyn_cast<CallBase>(I))
1366       if (auto Bundle = CB->getOperandBundle(LLVMContext::OB_funclet))
1367         Bundles.push_back(OperandBundleDef(*Bundle));
1368     auto *Free = CallInst::CreateFree(SetjmpTable, Bundles, I);
1369     Free->setDebugLoc(DL);
1370     // CallInst::CreateFree may create a bitcast instruction if its argument
1371     // types mismatch. We need to set the debug loc for the bitcast too.
1372     if (auto *FreeCallI = dyn_cast<CallInst>(Free)) {
1373       if (auto *BitCastI = dyn_cast<BitCastInst>(FreeCallI->getArgOperand(0)))
1374         BitCastI->setDebugLoc(DL);
1375     }
1376   }
1377 
1378   // Every call to saveSetjmp can change setjmpTable and setjmpTableSize
1379   // (when buffer reallocation occurs)
1380   // entry:
1381   //   setjmpTableSize = 4;
1382   //   setjmpTable = (int *) malloc(40);
1383   //   setjmpTable[0] = 0;
1384   // ...
1385   // somebb:
1386   //   setjmpTable = saveSetjmp(env, label, setjmpTable, setjmpTableSize);
1387   //   setjmpTableSize = getTempRet0();
1388   // So we need to make sure the SSA for these variables is valid so that every
1389   // saveSetjmp and testSetjmp calls have the correct arguments.
1390   SSAUpdater SetjmpTableSSA;
1391   SSAUpdater SetjmpTableSizeSSA;
1392   SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
1393   SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
1394   for (Instruction *I : SetjmpTableInsts)
1395     SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
1396   for (Instruction *I : SetjmpTableSizeInsts)
1397     SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
1398 
1399   for (auto &U : make_early_inc_range(SetjmpTable->uses()))
1400     if (auto *I = dyn_cast<Instruction>(U.getUser()))
1401       if (I->getParent() != Entry)
1402         SetjmpTableSSA.RewriteUse(U);
1403   for (auto &U : make_early_inc_range(SetjmpTableSize->uses()))
1404     if (auto *I = dyn_cast<Instruction>(U.getUser()))
1405       if (I->getParent() != Entry)
1406         SetjmpTableSizeSSA.RewriteUse(U);
1407 
1408   // Finally, our modifications to the cfg can break dominance of SSA variables.
1409   // For example, in this code,
1410   // if (x()) { .. setjmp() .. }
1411   // if (y()) { .. longjmp() .. }
1412   // We must split the longjmp block, and it can jump into the block splitted
1413   // from setjmp one. But that means that when we split the setjmp block, it's
1414   // first part no longer dominates its second part - there is a theoretically
1415   // possible control flow path where x() is false, then y() is true and we
1416   // reach the second part of the setjmp block, without ever reaching the first
1417   // part. So, we rebuild SSA form here.
1418   rebuildSSA(F);
1419   return true;
1420 }
1421 
1422 // Update each call that can longjmp so it can return to the corresponding
1423 // setjmp. Refer to 4) of "Emscripten setjmp/longjmp handling" section in the
1424 // comments at top of the file for details.
1425 void WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForEmscriptenSjLj(
1426     Function &F, InstVector &SetjmpTableInsts, InstVector &SetjmpTableSizeInsts,
1427     SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1428   Module &M = *F.getParent();
1429   LLVMContext &C = F.getContext();
1430   IRBuilder<> IRB(C);
1431   SmallVector<Instruction *, 64> ToErase;
1432 
1433   // We need to pass setjmpTable and setjmpTableSize to testSetjmp function.
1434   // These values are defined in the beginning of the function and also in each
1435   // setjmp callsite, but we don't know which values we should use at this
1436   // point. So here we arbitraily use the ones defined in the beginning of the
1437   // function, and SSAUpdater will later update them to the correct values.
1438   Instruction *SetjmpTable = *SetjmpTableInsts.begin();
1439   Instruction *SetjmpTableSize = *SetjmpTableSizeInsts.begin();
1440 
1441   // call.em.longjmp BB that will be shared within the function.
1442   BasicBlock *CallEmLongjmpBB = nullptr;
1443   // PHI node for the loaded value of __THREW__ global variable in
1444   // call.em.longjmp BB
1445   PHINode *CallEmLongjmpBBThrewPHI = nullptr;
1446   // PHI node for the loaded value of __threwValue global variable in
1447   // call.em.longjmp BB
1448   PHINode *CallEmLongjmpBBThrewValuePHI = nullptr;
1449   // rethrow.exn BB that will be shared within the function.
1450   BasicBlock *RethrowExnBB = nullptr;
1451 
1452   // Because we are creating new BBs while processing and don't want to make
1453   // all these newly created BBs candidates again for longjmp processing, we
1454   // first make the vector of candidate BBs.
1455   std::vector<BasicBlock *> BBs;
1456   for (BasicBlock &BB : F)
1457     BBs.push_back(&BB);
1458 
1459   // BBs.size() will change within the loop, so we query it every time
1460   for (unsigned I = 0; I < BBs.size(); I++) {
1461     BasicBlock *BB = BBs[I];
1462     for (Instruction &I : *BB) {
1463       if (isa<InvokeInst>(&I))
1464         report_fatal_error("When using Wasm EH with Emscripten SjLj, there is "
1465                            "a restriction that `setjmp` function call and "
1466                            "exception cannot be used within the same function");
1467       auto *CI = dyn_cast<CallInst>(&I);
1468       if (!CI)
1469         continue;
1470 
1471       const Value *Callee = CI->getCalledOperand();
1472       if (!canLongjmp(Callee))
1473         continue;
1474       if (isEmAsmCall(Callee))
1475         report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
1476                                F.getName() +
1477                                ". Please consider using EM_JS, or move the "
1478                                "EM_ASM into another function.",
1479                            false);
1480 
1481       Value *Threw = nullptr;
1482       BasicBlock *Tail;
1483       if (Callee->getName().startswith("__invoke_")) {
1484         // If invoke wrapper has already been generated for this call in
1485         // previous EH phase, search for the load instruction
1486         // %__THREW__.val = __THREW__;
1487         // in postamble after the invoke wrapper call
1488         LoadInst *ThrewLI = nullptr;
1489         StoreInst *ThrewResetSI = nullptr;
1490         for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
1491              I != IE; ++I) {
1492           if (auto *LI = dyn_cast<LoadInst>(I))
1493             if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
1494               if (GV == ThrewGV) {
1495                 Threw = ThrewLI = LI;
1496                 break;
1497               }
1498         }
1499         // Search for the store instruction after the load above
1500         // __THREW__ = 0;
1501         for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
1502              I != IE; ++I) {
1503           if (auto *SI = dyn_cast<StoreInst>(I)) {
1504             if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) {
1505               if (GV == ThrewGV &&
1506                   SI->getValueOperand() == getAddrSizeInt(&M, 0)) {
1507                 ThrewResetSI = SI;
1508                 break;
1509               }
1510             }
1511           }
1512         }
1513         assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
1514         assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
1515         Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
1516 
1517       } else {
1518         // Wrap call with invoke wrapper and generate preamble/postamble
1519         Threw = wrapInvoke(CI);
1520         ToErase.push_back(CI);
1521         Tail = SplitBlock(BB, CI->getNextNode());
1522 
1523         // If exception handling is enabled, the thrown value can be not a
1524         // longjmp but an exception, in which case we shouldn't silently ignore
1525         // exceptions; we should rethrow them.
1526         // __THREW__'s value is 0 when nothing happened, 1 when an exception is
1527         // thrown, other values when longjmp is thrown.
1528         //
1529         // if (%__THREW__.val == 1)
1530         //   goto %eh.rethrow
1531         // else
1532         //   goto %normal
1533         //
1534         // eh.rethrow: ;; Rethrow exception
1535         //   %exn = call @__cxa_find_matching_catch_2() ;; Retrieve thrown ptr
1536         //   __resumeException(%exn)
1537         //
1538         // normal:
1539         //   <-- Insertion point. Will insert sjlj handling code from here
1540         //   goto %tail
1541         //
1542         // tail:
1543         //   ...
1544         if (supportsException(&F) && canThrow(Callee)) {
1545           // We will add a new conditional branch. So remove the branch created
1546           // when we split the BB
1547           ToErase.push_back(BB->getTerminator());
1548 
1549           // Generate rethrow.exn BB once and share it within the function
1550           if (!RethrowExnBB) {
1551             RethrowExnBB = BasicBlock::Create(C, "rethrow.exn", &F);
1552             IRB.SetInsertPoint(RethrowExnBB);
1553             CallInst *Exn =
1554                 IRB.CreateCall(getFindMatchingCatch(M, 0), {}, "exn");
1555             IRB.CreateCall(ResumeF, {Exn});
1556             IRB.CreateUnreachable();
1557           }
1558 
1559           IRB.SetInsertPoint(CI);
1560           BasicBlock *NormalBB = BasicBlock::Create(C, "normal", &F);
1561           Value *CmpEqOne =
1562               IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
1563           IRB.CreateCondBr(CmpEqOne, RethrowExnBB, NormalBB);
1564 
1565           IRB.SetInsertPoint(NormalBB);
1566           IRB.CreateBr(Tail);
1567           BB = NormalBB; // New insertion point to insert testSetjmp()
1568         }
1569       }
1570 
1571       // We need to replace the terminator in Tail - SplitBlock makes BB go
1572       // straight to Tail, we need to check if a longjmp occurred, and go to the
1573       // right setjmp-tail if so
1574       ToErase.push_back(BB->getTerminator());
1575 
1576       // Generate a function call to testSetjmp function and preamble/postamble
1577       // code to figure out (1) whether longjmp occurred (2) if longjmp
1578       // occurred, which setjmp it corresponds to
1579       Value *Label = nullptr;
1580       Value *LongjmpResult = nullptr;
1581       BasicBlock *EndBB = nullptr;
1582       wrapTestSetjmp(BB, CI->getDebugLoc(), Threw, SetjmpTable, SetjmpTableSize,
1583                      Label, LongjmpResult, CallEmLongjmpBB,
1584                      CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI,
1585                      EndBB);
1586       assert(Label && LongjmpResult && EndBB);
1587 
1588       // Create switch instruction
1589       IRB.SetInsertPoint(EndBB);
1590       IRB.SetCurrentDebugLocation(EndBB->getInstList().back().getDebugLoc());
1591       SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1592       // -1 means no longjmp happened, continue normally (will hit the default
1593       // switch case). 0 means a longjmp that is not ours to handle, needs a
1594       // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1595       // 0).
1596       for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1597         SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1598         SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB);
1599       }
1600 
1601       // We are splitting the block here, and must continue to find other calls
1602       // in the block - which is now split. so continue to traverse in the Tail
1603       BBs.push_back(Tail);
1604     }
1605   }
1606 
1607   for (Instruction *I : ToErase)
1608     I->eraseFromParent();
1609 }
1610 
1611 // Create a catchpad in which we catch a longjmp's env and val arguments, test
1612 // if the longjmp corresponds to one of setjmps in the current function, and if
1613 // so, jump to the setjmp dispatch BB from which we go to one of post-setjmp
1614 // BBs. Refer to 4) of "Wasm setjmp/longjmp handling" section in the comments at
1615 // top of the file for details.
1616 void WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForWasmSjLj(
1617     Function &F, InstVector &SetjmpTableInsts, InstVector &SetjmpTableSizeInsts,
1618     SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1619   Module &M = *F.getParent();
1620   LLVMContext &C = F.getContext();
1621   IRBuilder<> IRB(C);
1622 
1623   // A function with catchswitch/catchpad instruction should have a personality
1624   // function attached to it. Search for the wasm personality function, and if
1625   // it exists, use it, and if it doesn't, create a dummy personality function.
1626   // (SjLj is not going to call it anyway.)
1627   if (!F.hasPersonalityFn()) {
1628     StringRef PersName = getEHPersonalityName(EHPersonality::Wasm_CXX);
1629     FunctionType *PersType =
1630         FunctionType::get(IRB.getInt32Ty(), /* isVarArg */ true);
1631     Value *PersF = M.getOrInsertFunction(PersName, PersType).getCallee();
1632     F.setPersonalityFn(
1633         cast<Constant>(IRB.CreateBitCast(PersF, IRB.getInt8PtrTy())));
1634   }
1635 
1636   // Use the entry BB's debugloc as a fallback
1637   BasicBlock *Entry = &F.getEntryBlock();
1638   DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram());
1639   IRB.SetCurrentDebugLocation(FirstDL);
1640 
1641   // Arbitrarily use the ones defined in the beginning of the function.
1642   // SSAUpdater will later update them to the correct values.
1643   Instruction *SetjmpTable = *SetjmpTableInsts.begin();
1644   Instruction *SetjmpTableSize = *SetjmpTableSizeInsts.begin();
1645 
1646   // Add setjmp.dispatch BB right after the entry block. Because we have
1647   // initialized setjmpTable/setjmpTableSize in the entry block and split the
1648   // rest into another BB, here 'OrigEntry' is the function's original entry
1649   // block before the transformation.
1650   //
1651   // entry:
1652   //   setjmpTable / setjmpTableSize initialization
1653   // setjmp.dispatch:
1654   //   switch will be inserted here later
1655   // entry.split: (OrigEntry)
1656   //   the original function starts here
1657   BasicBlock *OrigEntry = Entry->getNextNode();
1658   BasicBlock *SetjmpDispatchBB =
1659       BasicBlock::Create(C, "setjmp.dispatch", &F, OrigEntry);
1660   cast<BranchInst>(Entry->getTerminator())->setSuccessor(0, SetjmpDispatchBB);
1661 
1662   // Create catch.dispatch.longjmp BB a catchswitch instruction
1663   BasicBlock *CatchSwitchBB =
1664       BasicBlock::Create(C, "catch.dispatch.longjmp", &F);
1665   IRB.SetInsertPoint(CatchSwitchBB);
1666   CatchSwitchInst *CatchSwitch =
1667       IRB.CreateCatchSwitch(ConstantTokenNone::get(C), nullptr, 1);
1668 
1669   // Create catch.longjmp BB and a catchpad instruction
1670   BasicBlock *CatchLongjmpBB = BasicBlock::Create(C, "catch.longjmp", &F);
1671   CatchSwitch->addHandler(CatchLongjmpBB);
1672   IRB.SetInsertPoint(CatchLongjmpBB);
1673   CatchPadInst *CatchPad = IRB.CreateCatchPad(CatchSwitch, {});
1674 
1675   // Wasm throw and catch instructions can throw and catch multiple values, but
1676   // that requires multivalue support in the toolchain, which is currently not
1677   // very reliable. We instead throw and catch a pointer to a struct value of
1678   // type 'struct __WasmLongjmpArgs', which is defined in Emscripten.
1679   Instruction *CatchCI =
1680       IRB.CreateCall(CatchF, {IRB.getInt32(WebAssembly::C_LONGJMP)}, "thrown");
1681   Value *LongjmpArgs =
1682       IRB.CreateBitCast(CatchCI, LongjmpArgsTy->getPointerTo(), "longjmp.args");
1683   Value *EnvField =
1684       IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 0, "env_gep");
1685   Value *ValField =
1686       IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 1, "val_gep");
1687   // void *env = __wasm_longjmp_args.env;
1688   Instruction *Env = IRB.CreateLoad(IRB.getInt8PtrTy(), EnvField, "env");
1689   // int val = __wasm_longjmp_args.val;
1690   Instruction *Val = IRB.CreateLoad(IRB.getInt32Ty(), ValField, "val");
1691 
1692   // %label = testSetjmp(mem[%env], setjmpTable, setjmpTableSize);
1693   // if (%label == 0)
1694   //   __wasm_longjmp(%env, %val)
1695   // catchret to %setjmp.dispatch
1696   BasicBlock *ThenBB = BasicBlock::Create(C, "if.then", &F);
1697   BasicBlock *EndBB = BasicBlock::Create(C, "if.end", &F);
1698   Value *EnvP = IRB.CreateBitCast(Env, getAddrPtrType(&M), "env.p");
1699   Value *SetjmpID = IRB.CreateLoad(getAddrIntType(&M), EnvP, "setjmp.id");
1700   Value *Label =
1701       IRB.CreateCall(TestSetjmpF, {SetjmpID, SetjmpTable, SetjmpTableSize},
1702                      OperandBundleDef("funclet", CatchPad), "label");
1703   Value *Cmp = IRB.CreateICmpEQ(Label, IRB.getInt32(0));
1704   IRB.CreateCondBr(Cmp, ThenBB, EndBB);
1705 
1706   IRB.SetInsertPoint(ThenBB);
1707   CallInst *WasmLongjmpCI = IRB.CreateCall(
1708       WasmLongjmpF, {Env, Val}, OperandBundleDef("funclet", CatchPad));
1709   IRB.CreateUnreachable();
1710 
1711   IRB.SetInsertPoint(EndBB);
1712   // Jump to setjmp.dispatch block
1713   IRB.CreateCatchRet(CatchPad, SetjmpDispatchBB);
1714 
1715   // Go back to setjmp.dispatch BB
1716   // setjmp.dispatch:
1717   //   switch %label {
1718   //     label 1: goto post-setjmp BB 1
1719   //     label 2: goto post-setjmp BB 2
1720   //     ...
1721   //     default: goto splitted next BB
1722   //   }
1723   IRB.SetInsertPoint(SetjmpDispatchBB);
1724   PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label.phi");
1725   LabelPHI->addIncoming(Label, EndBB);
1726   LabelPHI->addIncoming(IRB.getInt32(-1), Entry);
1727   SwitchInst *SI = IRB.CreateSwitch(LabelPHI, OrigEntry, SetjmpRetPHIs.size());
1728   // -1 means no longjmp happened, continue normally (will hit the default
1729   // switch case). 0 means a longjmp that is not ours to handle, needs a
1730   // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1731   // 0).
1732   for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1733     SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1734     SetjmpRetPHIs[I]->addIncoming(Val, SetjmpDispatchBB);
1735   }
1736 
1737   // Convert all longjmpable call instructions to invokes that unwind to the
1738   // newly created catch.dispatch.longjmp BB.
1739   SmallVector<Instruction *, 64> ToErase;
1740   for (auto *BB = &*F.begin(); BB; BB = BB->getNextNode()) {
1741     for (Instruction &I : *BB) {
1742       auto *CI = dyn_cast<CallInst>(&I);
1743       if (!CI)
1744         continue;
1745       const Value *Callee = CI->getCalledOperand();
1746       if (!canLongjmp(Callee))
1747         continue;
1748       if (isEmAsmCall(Callee))
1749         report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
1750                                F.getName() +
1751                                ". Please consider using EM_JS, or move the "
1752                                "EM_ASM into another function.",
1753                            false);
1754       // This is __wasm_longjmp() call we inserted in this function, which
1755       // rethrows the longjmp when the longjmp does not correspond to one of
1756       // setjmps in this function. We should not convert this call to an invoke.
1757       if (CI == WasmLongjmpCI)
1758         continue;
1759       ToErase.push_back(CI);
1760 
1761       // Even if the callee function has attribute 'nounwind', which is true for
1762       // all C functions, it can longjmp, which means it can throw a Wasm
1763       // exception now.
1764       CI->removeFnAttr(Attribute::NoUnwind);
1765       if (Function *CalleeF = CI->getCalledFunction()) {
1766         CalleeF->removeFnAttr(Attribute::NoUnwind);
1767       }
1768 
1769       IRB.SetInsertPoint(CI);
1770       BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
1771       // We will add a new invoke. So remove the branch created when we split
1772       // the BB
1773       ToErase.push_back(BB->getTerminator());
1774       SmallVector<Value *, 8> Args(CI->args());
1775       InvokeInst *II =
1776           IRB.CreateInvoke(CI->getFunctionType(), CI->getCalledOperand(), Tail,
1777                            CatchSwitchBB, Args);
1778       II->takeName(CI);
1779       II->setDebugLoc(CI->getDebugLoc());
1780       II->setAttributes(CI->getAttributes());
1781       CI->replaceAllUsesWith(II);
1782     }
1783   }
1784 
1785   for (Instruction *I : ToErase)
1786     I->eraseFromParent();
1787 }
1788