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