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
11 /// function calls in order to use Emscripten's JavaScript try and catch
12 /// mechanism.
13 ///
14 /// To handle exceptions and setjmp/longjmps, this scheme relies on JavaScript's
15 /// try and catch syntax and relevant exception-related libraries implemented
16 /// in JavaScript glue code that will be produced by Emscripten. This is similar
17 /// to the current Emscripten asm.js exception handling in fastcomp. For
18 /// fastcomp's EH / SjLj scheme, see these files in fastcomp LLVM branch:
19 /// (Location: https://github.com/kripken/emscripten-fastcomp)
20 /// lib/Target/JSBackend/NaCl/LowerEmExceptionsPass.cpp
21 /// lib/Target/JSBackend/NaCl/LowerEmSetjmp.cpp
22 /// lib/Target/JSBackend/JSBackend.cpp
23 /// lib/Target/JSBackend/CallHandlers.h
24 ///
25 /// * Exception handling
26 /// This pass lowers invokes and landingpads into library functions in JS glue
27 /// code. Invokes are lowered into function wrappers called invoke wrappers that
28 /// exist in JS side, which wraps the original function call with JS try-catch.
29 /// If an exception occurred, cxa_throw() function in JS side sets some
30 /// variables (see below) so we can check whether an exception occurred from
31 /// wasm code and handle it appropriately.
32 ///
33 /// * Setjmp-longjmp handling
34 /// This pass lowers setjmp to a reasonably-performant approach for emscripten.
35 /// The idea is that each block with a setjmp is broken up into two parts: the
36 /// part containing setjmp and the part right after the setjmp. The latter part
37 /// is either reached from the setjmp, or later from a longjmp. To handle the
38 /// longjmp, all calls that might longjmp are also called using invoke wrappers
39 /// and thus JS / try-catch. JS longjmp() function also sets some variables so
40 /// we can check / whether a longjmp occurred from wasm code. Each block with a
41 /// function call that might longjmp is also split up after the longjmp call.
42 /// After the longjmp call, we check whether a longjmp occurred, and if it did,
43 /// which setjmp it corresponds to, and jump to the right post-setjmp block.
44 /// We assume setjmp-longjmp handling always run after EH handling, which means
45 /// we don't expect any exception-related instructions when SjLj runs.
46 /// FIXME Currently this scheme does not support indirect call of setjmp,
47 /// because of the limitation of the scheme itself. fastcomp does not support it
48 /// either.
49 ///
50 /// In detail, this pass does following things:
51 ///
52 /// 1) Assumes the existence of global variables: __THREW__, __threwValue
53 ///    __THREW__ and __threwValue will be set in invoke wrappers
54 ///    in JS glue code. For what invoke wrappers are, refer to 3). These
55 ///    variables are used for both exceptions and setjmp/longjmps.
56 ///    __THREW__ indicates whether an exception or a longjmp occurred or not. 0
57 ///    means nothing occurred, 1 means an exception occurred, and other numbers
58 ///    mean a longjmp occurred. In the case of longjmp, __threwValue variable
59 ///    indicates the corresponding setjmp buffer the longjmp corresponds to.
60 ///
61 /// * Exception handling
62 ///
63 /// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions
64 ///    at link time.
65 ///    The global variables in 1) will exist in wasm address space,
66 ///    but their values should be set in JS code, so these functions
67 ///    as interfaces to JS glue code. These functions are equivalent to the
68 ///    following JS functions, which actually exist in asm.js version of JS
69 ///    library.
70 ///
71 ///    function setThrew(threw, value) {
72 ///      if (__THREW__ == 0) {
73 ///        __THREW__ = threw;
74 ///        __threwValue = value;
75 ///      }
76 ///    }
77 //
78 ///    setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
79 ///
80 ///    In exception handling, getTempRet0 indicates the type of an exception
81 ///    caught, and in setjmp/longjmp, it means the second argument to longjmp
82 ///    function.
83 ///
84 /// 3) Lower
85 ///      invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
86 ///    into
87 ///      __THREW__ = 0;
88 ///      call @__invoke_SIG(func, arg1, arg2)
89 ///      %__THREW__.val = __THREW__;
90 ///      __THREW__ = 0;
91 ///      if (%__THREW__.val == 1)
92 ///        goto %lpad
93 ///      else
94 ///         goto %invoke.cont
95 ///    SIG is a mangled string generated based on the LLVM IR-level function
96 ///    signature. After LLVM IR types are lowered to the target wasm types,
97 ///    the names for these wrappers will change based on wasm types as well,
98 ///    as in invoke_vi (function takes an int and returns void). The bodies of
99 ///    these wrappers will be generated in JS glue code, and inside those
100 ///    wrappers we use JS try-catch to generate actual exception effects. It
101 ///    also calls the original callee function. An example wrapper in JS code
102 ///    would look like this:
103 ///      function invoke_vi(index,a1) {
104 ///        try {
105 ///          Module["dynCall_vi"](index,a1); // This calls original callee
106 ///        } catch(e) {
107 ///          if (typeof e !== 'number' && e !== 'longjmp') throw e;
108 ///          asm["setThrew"](1, 0); // setThrew is called here
109 ///        }
110 ///      }
111 ///    If an exception is thrown, __THREW__ will be set to true in a wrapper,
112 ///    so we can jump to the right BB based on this value.
113 ///
114 /// 4) Lower
115 ///      %val = landingpad catch c1 catch c2 catch c3 ...
116 ///      ... use %val ...
117 ///    into
118 ///      %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
119 ///      %val = {%fmc, getTempRet0()}
120 ///      ... use %val ...
121 ///    Here N is a number calculated based on the number of clauses.
122 ///    setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
123 ///
124 /// 5) Lower
125 ///      resume {%a, %b}
126 ///    into
127 ///      call @__resumeException(%a)
128 ///    where __resumeException() is a function in JS glue code.
129 ///
130 /// 6) Lower
131 ///      call @llvm.eh.typeid.for(type) (intrinsic)
132 ///    into
133 ///      call @llvm_eh_typeid_for(type)
134 ///    llvm_eh_typeid_for function will be generated in JS glue code.
135 ///
136 /// * Setjmp / Longjmp handling
137 ///
138 /// In case calls to longjmp() exists
139 ///
140 /// 1) Lower
141 ///      longjmp(buf, value)
142 ///    into
143 ///      emscripten_longjmp(buf, value)
144 ///
145 /// In case calls to setjmp() exists
146 ///
147 /// 2) In the function entry that calls setjmp, initialize setjmpTable and
148 ///    sejmpTableSize as follows:
149 ///      setjmpTableSize = 4;
150 ///      setjmpTable = (int *) malloc(40);
151 ///      setjmpTable[0] = 0;
152 ///    setjmpTable and setjmpTableSize are used in saveSetjmp() function in JS
153 ///    code.
154 ///
155 /// 3) Lower
156 ///      setjmp(buf)
157 ///    into
158 ///      setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
159 ///      setjmpTableSize = getTempRet0();
160 ///    For each dynamic setjmp call, setjmpTable stores its ID (a number which
161 ///    is incrementally assigned from 0) and its label (a unique number that
162 ///    represents each callsite of setjmp). When we need more entries in
163 ///    setjmpTable, it is reallocated in saveSetjmp() in JS code and it will
164 ///    return the new table address, and assign the new table size in
165 ///    setTempRet0(). saveSetjmp also stores the setjmp's ID into the buffer
166 ///    buf. A BB with setjmp is split into two after setjmp call in order to
167 ///    make the post-setjmp BB the possible destination of longjmp BB.
168 ///
169 ///
170 /// 4) Lower every call that might longjmp into
171 ///      __THREW__ = 0;
172 ///      call @__invoke_SIG(func, arg1, arg2)
173 ///      %__THREW__.val = __THREW__;
174 ///      __THREW__ = 0;
175 ///      if (%__THREW__.val != 0 & __threwValue != 0) {
176 ///        %label = testSetjmp(mem[%__THREW__.val], setjmpTable,
177 ///                            setjmpTableSize);
178 ///        if (%label == 0)
179 ///          emscripten_longjmp(%__THREW__.val, __threwValue);
180 ///        setTempRet0(__threwValue);
181 ///      } else {
182 ///        %label = -1;
183 ///      }
184 ///      longjmp_result = getTempRet0();
185 ///      switch label {
186 ///        label 1: goto post-setjmp BB 1
187 ///        label 2: goto post-setjmp BB 2
188 ///        ...
189 ///        default: goto splitted next BB
190 ///      }
191 ///    testSetjmp examines setjmpTable to see if there is a matching setjmp
192 ///    call. After calling an invoke wrapper, if a longjmp occurred, __THREW__
193 ///    will be the address of matching jmp_buf buffer and __threwValue be the
194 ///    second argument to longjmp. mem[__THREW__.val] is a setjmp ID that is
195 ///    stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to
196 ///    each setjmp callsite. Label 0 means this longjmp buffer does not
197 ///    correspond to one of the setjmp callsites in this function, so in this
198 ///    case we just chain the longjmp to the caller. Label -1 means no longjmp
199 ///    occurred. Otherwise we jump to the right post-setjmp BB based on the
200 ///    label.
201 ///
202 ///===----------------------------------------------------------------------===//
203 
204 #include "WebAssembly.h"
205 #include "WebAssemblyTargetMachine.h"
206 #include "llvm/ADT/StringExtras.h"
207 #include "llvm/CodeGen/TargetPassConfig.h"
208 #include "llvm/IR/DebugInfoMetadata.h"
209 #include "llvm/IR/Dominators.h"
210 #include "llvm/IR/IRBuilder.h"
211 #include "llvm/Support/CommandLine.h"
212 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
213 #include "llvm/Transforms/Utils/SSAUpdater.h"
214 
215 using namespace llvm;
216 
217 #define DEBUG_TYPE "wasm-lower-em-ehsjlj"
218 
219 static cl::list<std::string>
220     EHAllowlist("emscripten-cxx-exceptions-allowed",
221                 cl::desc("The list of function names in which Emscripten-style "
222                          "exception handling is enabled (see emscripten "
223                          "EMSCRIPTEN_CATCHING_ALLOWED options)"),
224                 cl::CommaSeparated);
225 
226 namespace {
227 class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
228   bool EnableEH;   // Enable exception handling
229   bool EnableSjLj; // Enable setjmp/longjmp handling
230 
231   GlobalVariable *ThrewGV = nullptr;
232   GlobalVariable *ThrewValueGV = nullptr;
233   Function *GetTempRet0Func = nullptr;
234   Function *SetTempRet0Func = nullptr;
235   Function *ResumeF = nullptr;
236   Function *EHTypeIDF = nullptr;
237   Function *EmLongjmpF = nullptr;
238   Function *SaveSetjmpF = nullptr;
239   Function *TestSetjmpF = nullptr;
240 
241   // __cxa_find_matching_catch_N functions.
242   // Indexed by the number of clauses in an original landingpad instruction.
243   DenseMap<int, Function *> FindMatchingCatches;
244   // Map of <function signature string, invoke_ wrappers>
245   StringMap<Function *> InvokeWrappers;
246   // Set of allowed function names for exception handling
247   std::set<std::string> EHAllowlistSet;
248 
249   StringRef getPassName() const override {
250     return "WebAssembly Lower Emscripten Exceptions";
251   }
252 
253   bool runEHOnFunction(Function &F);
254   bool runSjLjOnFunction(Function &F);
255   Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
256 
257   Value *wrapInvoke(CallBase *CI);
258   void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw,
259                       Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
260                       Value *&LongjmpResult, BasicBlock *&EndBB);
261   Function *getInvokeWrapper(CallBase *CI);
262 
263   bool areAllExceptionsAllowed() const { return EHAllowlistSet.empty(); }
264   bool canLongjmp(Module &M, const Value *Callee) const;
265   bool isEmAsmCall(Module &M, const Value *Callee) const;
266 
267   void rebuildSSA(Function &F);
268 
269 public:
270   static char ID;
271 
272   WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH = true, bool EnableSjLj = true)
273       : ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj) {
274     EHAllowlistSet.insert(EHAllowlist.begin(), EHAllowlist.end());
275   }
276   bool runOnModule(Module &M) override;
277 
278   void getAnalysisUsage(AnalysisUsage &AU) const override {
279     AU.addRequired<DominatorTreeWrapperPass>();
280   }
281 };
282 } // End anonymous namespace
283 
284 char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
285 INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
286                 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
287                 false, false)
288 
289 ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH,
290                                                          bool EnableSjLj) {
291   return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj);
292 }
293 
294 static bool canThrow(const Value *V) {
295   if (const auto *F = dyn_cast<const Function>(V)) {
296     // Intrinsics cannot throw
297     if (F->isIntrinsic())
298       return false;
299     StringRef Name = F->getName();
300     // leave setjmp and longjmp (mostly) alone, we process them properly later
301     if (Name == "setjmp" || Name == "longjmp")
302       return false;
303     return !F->doesNotThrow();
304   }
305   // not a function, so an indirect call - can throw, we can't tell
306   return true;
307 }
308 
309 // Get a global variable with the given name.  If it doesn't exist declare it,
310 // which will generate an import and asssumes that it will exist at link time.
311 static GlobalVariable *getGlobalVariableI32(Module &M, IRBuilder<> &IRB,
312                                             WebAssemblyTargetMachine &TM,
313                                             const char *Name) {
314   auto Int32Ty = IRB.getInt32Ty();
315   auto *GV = dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, Int32Ty));
316   if (!GV)
317     report_fatal_error(Twine("unable to create global: ") + Name);
318 
319   // If the target supports TLS, make this variable thread-local. We can't just
320   // unconditionally make it thread-local and depend on
321   // CoalesceFeaturesAndStripAtomics to downgrade it, because stripping TLS has
322   // the side effect of disallowing the object from being linked into a
323   // shared-memory module, which we don't want to be responsible for.
324   auto *Subtarget = TM.getSubtargetImpl();
325   auto TLS = Subtarget->hasAtomics() && Subtarget->hasBulkMemory()
326                  ? GlobalValue::LocalExecTLSModel
327                  : GlobalValue::NotThreadLocal;
328   GV->setThreadLocalMode(TLS);
329   return GV;
330 }
331 
332 // Simple function name mangler.
333 // This function simply takes LLVM's string representation of parameter types
334 // and concatenate them with '_'. There are non-alphanumeric characters but llc
335 // is ok with it, and we need to postprocess these names after the lowering
336 // phase anyway.
337 static std::string getSignature(FunctionType *FTy) {
338   std::string Sig;
339   raw_string_ostream OS(Sig);
340   OS << *FTy->getReturnType();
341   for (Type *ParamTy : FTy->params())
342     OS << "_" << *ParamTy;
343   if (FTy->isVarArg())
344     OS << "_...";
345   Sig = OS.str();
346   Sig.erase(remove_if(Sig, isSpace), Sig.end());
347   // When s2wasm parses .s file, a comma means the end of an argument. So a
348   // mangled function name can contain any character but a comma.
349   std::replace(Sig.begin(), Sig.end(), ',', '.');
350   return Sig;
351 }
352 
353 static Function *getEmscriptenFunction(FunctionType *Ty, const Twine &Name,
354                                        Module *M) {
355   Function* F = Function::Create(Ty, GlobalValue::ExternalLinkage, Name, M);
356   // Tell the linker that this function is expected to be imported from the
357   // 'env' module.
358   if (!F->hasFnAttribute("wasm-import-module")) {
359     llvm::AttrBuilder B;
360     B.addAttribute("wasm-import-module", "env");
361     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
362   }
363   if (!F->hasFnAttribute("wasm-import-name")) {
364     llvm::AttrBuilder B;
365     B.addAttribute("wasm-import-name", F->getName());
366     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
367   }
368   return F;
369 }
370 
371 // Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
372 // This is because a landingpad instruction contains two more arguments, a
373 // personality function and a cleanup bit, and __cxa_find_matching_catch_N
374 // functions are named after the number of arguments in the original landingpad
375 // instruction.
376 Function *
377 WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
378                                                        unsigned NumClauses) {
379   if (FindMatchingCatches.count(NumClauses))
380     return FindMatchingCatches[NumClauses];
381   PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
382   SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
383   FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
384   Function *F = getEmscriptenFunction(
385       FTy, "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M);
386   FindMatchingCatches[NumClauses] = F;
387   return F;
388 }
389 
390 // Generate invoke wrapper seqence with preamble and postamble
391 // Preamble:
392 // __THREW__ = 0;
393 // Postamble:
394 // %__THREW__.val = __THREW__; __THREW__ = 0;
395 // Returns %__THREW__.val, which indicates whether an exception is thrown (or
396 // whether longjmp occurred), for future use.
397 Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) {
398   LLVMContext &C = CI->getModule()->getContext();
399 
400   // If we are calling a function that is noreturn, we must remove that
401   // attribute. The code we insert here does expect it to return, after we
402   // catch the exception.
403   if (CI->doesNotReturn()) {
404     if (auto *F = CI->getCalledFunction())
405       F->removeFnAttr(Attribute::NoReturn);
406     CI->removeAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
407   }
408 
409   IRBuilder<> IRB(C);
410   IRB.SetInsertPoint(CI);
411 
412   // Pre-invoke
413   // __THREW__ = 0;
414   IRB.CreateStore(IRB.getInt32(0), ThrewGV);
415 
416   // Invoke function wrapper in JavaScript
417   SmallVector<Value *, 16> Args;
418   // Put the pointer to the callee as first argument, so it can be called
419   // within the invoke wrapper later
420   Args.push_back(CI->getCalledOperand());
421   Args.append(CI->arg_begin(), CI->arg_end());
422   CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
423   NewCall->takeName(CI);
424   NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke);
425   NewCall->setDebugLoc(CI->getDebugLoc());
426 
427   // Because we added the pointer to the callee as first argument, all
428   // argument attribute indices have to be incremented by one.
429   SmallVector<AttributeSet, 8> ArgAttributes;
430   const AttributeList &InvokeAL = CI->getAttributes();
431 
432   // No attributes for the callee pointer.
433   ArgAttributes.push_back(AttributeSet());
434   // Copy the argument attributes from the original
435   for (unsigned I = 0, E = CI->getNumArgOperands(); I < E; ++I)
436     ArgAttributes.push_back(InvokeAL.getParamAttributes(I));
437 
438   AttrBuilder FnAttrs(InvokeAL.getFnAttributes());
439   if (FnAttrs.contains(Attribute::AllocSize)) {
440     // The allocsize attribute (if any) referes to parameters by index and needs
441     // to be adjusted.
442     unsigned SizeArg;
443     Optional<unsigned> NEltArg;
444     std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs();
445     SizeArg += 1;
446     if (NEltArg.hasValue())
447       NEltArg = NEltArg.getValue() + 1;
448     FnAttrs.addAllocSizeAttr(SizeArg, NEltArg);
449   }
450 
451   // Reconstruct the AttributesList based on the vector we constructed.
452   AttributeList NewCallAL =
453       AttributeList::get(C, AttributeSet::get(C, FnAttrs),
454                          InvokeAL.getRetAttributes(), ArgAttributes);
455   NewCall->setAttributes(NewCallAL);
456 
457   CI->replaceAllUsesWith(NewCall);
458 
459   // Post-invoke
460   // %__THREW__.val = __THREW__; __THREW__ = 0;
461   Value *Threw =
462       IRB.CreateLoad(IRB.getInt32Ty(), ThrewGV, ThrewGV->getName() + ".val");
463   IRB.CreateStore(IRB.getInt32(0), ThrewGV);
464   return Threw;
465 }
466 
467 // Get matching invoke wrapper based on callee signature
468 Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallBase *CI) {
469   Module *M = CI->getModule();
470   SmallVector<Type *, 16> ArgTys;
471   FunctionType *CalleeFTy = CI->getFunctionType();
472 
473   std::string Sig = getSignature(CalleeFTy);
474   if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
475     return InvokeWrappers[Sig];
476 
477   // Put the pointer to the callee as first argument
478   ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
479   // Add argument types
480   ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
481 
482   FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
483                                         CalleeFTy->isVarArg());
484   Function *F = getEmscriptenFunction(FTy, "__invoke_" + Sig, M);
485   InvokeWrappers[Sig] = F;
486   return F;
487 }
488 
489 bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(Module &M,
490                                                   const Value *Callee) const {
491   if (auto *CalleeF = dyn_cast<Function>(Callee))
492     if (CalleeF->isIntrinsic())
493       return false;
494 
495   // Attempting to transform inline assembly will result in something like:
496   //     call void @__invoke_void(void ()* asm ...)
497   // which is invalid because inline assembly blocks do not have addresses
498   // and can't be passed by pointer. The result is a crash with illegal IR.
499   if (isa<InlineAsm>(Callee))
500     return false;
501   StringRef CalleeName = Callee->getName();
502 
503   // The reason we include malloc/free here is to exclude the malloc/free
504   // calls generated in setjmp prep / cleanup routines.
505   if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free")
506     return false;
507 
508   // There are functions in JS glue code
509   if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" ||
510       CalleeName == "saveSetjmp" || CalleeName == "testSetjmp" ||
511       CalleeName == "getTempRet0" || CalleeName == "setTempRet0")
512     return false;
513 
514   // __cxa_find_matching_catch_N functions cannot longjmp
515   if (Callee->getName().startswith("__cxa_find_matching_catch_"))
516     return false;
517 
518   // Exception-catching related functions
519   if (CalleeName == "__cxa_begin_catch" || CalleeName == "__cxa_end_catch" ||
520       CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" ||
521       CalleeName == "__clang_call_terminate")
522     return false;
523 
524   // Otherwise we don't know
525   return true;
526 }
527 
528 bool WebAssemblyLowerEmscriptenEHSjLj::isEmAsmCall(Module &M,
529                                                    const Value *Callee) const {
530   StringRef CalleeName = Callee->getName();
531   // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>.
532   return CalleeName == "emscripten_asm_const_int" ||
533          CalleeName == "emscripten_asm_const_double" ||
534          CalleeName == "emscripten_asm_const_int_sync_on_main_thread" ||
535          CalleeName == "emscripten_asm_const_double_sync_on_main_thread" ||
536          CalleeName == "emscripten_asm_const_async_on_main_thread";
537 }
538 
539 // Generate testSetjmp function call seqence with preamble and postamble.
540 // The code this generates is equivalent to the following JavaScript code:
541 // if (%__THREW__.val != 0 & threwValue != 0) {
542 //   %label = _testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
543 //   if (%label == 0)
544 //     emscripten_longjmp(%__THREW__.val, threwValue);
545 //   setTempRet0(threwValue);
546 // } else {
547 //   %label = -1;
548 // }
549 // %longjmp_result = getTempRet0();
550 //
551 // As output parameters. returns %label, %longjmp_result, and the BB the last
552 // instruction (%longjmp_result = ...) is in.
553 void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
554     BasicBlock *BB, DebugLoc DL, Value *Threw, Value *SetjmpTable,
555     Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
556     BasicBlock *&EndBB) {
557   Function *F = BB->getParent();
558   LLVMContext &C = BB->getModule()->getContext();
559   IRBuilder<> IRB(C);
560   IRB.SetCurrentDebugLocation(DL);
561 
562   // if (%__THREW__.val != 0 & threwValue != 0)
563   IRB.SetInsertPoint(BB);
564   BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
565   BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
566   BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
567   Value *ThrewCmp = IRB.CreateICmpNE(Threw, IRB.getInt32(0));
568   Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
569                                      ThrewValueGV->getName() + ".val");
570   Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
571   Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
572   IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
573 
574   // %label = _testSetjmp(mem[%__THREW__.val], _setjmpTable, _setjmpTableSize);
575   // if (%label == 0)
576   IRB.SetInsertPoint(ThenBB1);
577   BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F);
578   BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
579   Value *ThrewInt = IRB.CreateIntToPtr(Threw, Type::getInt32PtrTy(C),
580                                        Threw->getName() + ".i32p");
581   Value *LoadedThrew = IRB.CreateLoad(IRB.getInt32Ty(), ThrewInt,
582                                       ThrewInt->getName() + ".loaded");
583   Value *ThenLabel = IRB.CreateCall(
584       TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
585   Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
586   IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2);
587 
588   // emscripten_longjmp(%__THREW__.val, threwValue);
589   IRB.SetInsertPoint(ThenBB2);
590   IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue});
591   IRB.CreateUnreachable();
592 
593   // setTempRet0(threwValue);
594   IRB.SetInsertPoint(EndBB2);
595   IRB.CreateCall(SetTempRet0Func, ThrewValue);
596   IRB.CreateBr(EndBB1);
597 
598   IRB.SetInsertPoint(ElseBB1);
599   IRB.CreateBr(EndBB1);
600 
601   // longjmp_result = getTempRet0();
602   IRB.SetInsertPoint(EndBB1);
603   PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
604   LabelPHI->addIncoming(ThenLabel, EndBB2);
605 
606   LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
607 
608   // Output parameter assignment
609   Label = LabelPHI;
610   EndBB = EndBB1;
611   LongjmpResult = IRB.CreateCall(GetTempRet0Func, None, "longjmp_result");
612 }
613 
614 void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
615   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
616   DT.recalculate(F); // CFG has been changed
617   SSAUpdater SSA;
618   for (BasicBlock &BB : F) {
619     for (Instruction &I : BB) {
620       SSA.Initialize(I.getType(), I.getName());
621       SSA.AddAvailableValue(&BB, &I);
622       for (auto UI = I.use_begin(), UE = I.use_end(); UI != UE;) {
623         Use &U = *UI;
624         ++UI;
625         auto *User = cast<Instruction>(U.getUser());
626         if (auto *UserPN = dyn_cast<PHINode>(User))
627           if (UserPN->getIncomingBlock(U) == &BB)
628             continue;
629 
630         if (DT.dominates(&I, User))
631           continue;
632         SSA.RewriteUseAfterInsertions(U);
633       }
634     }
635   }
636 }
637 
638 // Replace uses of longjmp with emscripten_longjmp. emscripten_longjmp takes
639 // arguments of type {i32, i32} and longjmp takes {jmp_buf*, i32}, so we need a
640 // ptrtoint instruction here to make the type match. jmp_buf* will eventually be
641 // lowered to i32 in the wasm backend.
642 static void replaceLongjmpWithEmscriptenLongjmp(Function *LongjmpF,
643                                                 Function *EmLongjmpF) {
644   SmallVector<CallInst *, 8> ToErase;
645   LLVMContext &C = LongjmpF->getParent()->getContext();
646   IRBuilder<> IRB(C);
647   for (User *U : LongjmpF->users()) {
648     auto *CI = dyn_cast<CallInst>(U);
649     if (!CI)
650       report_fatal_error("Does not support indirect calls to longjmp");
651     IRB.SetInsertPoint(CI);
652     Value *Jmpbuf =
653         IRB.CreatePtrToInt(CI->getArgOperand(0), IRB.getInt32Ty(), "jmpbuf");
654     IRB.CreateCall(EmLongjmpF, {Jmpbuf, CI->getArgOperand(1)});
655     ToErase.push_back(CI);
656   }
657 
658   for (auto *I : ToErase)
659     I->eraseFromParent();
660 }
661 
662 bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
663   LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
664 
665   LLVMContext &C = M.getContext();
666   IRBuilder<> IRB(C);
667 
668   Function *SetjmpF = M.getFunction("setjmp");
669   Function *LongjmpF = M.getFunction("longjmp");
670   bool SetjmpUsed = SetjmpF && !SetjmpF->use_empty();
671   bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
672   bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed);
673 
674   if ((EnableEH || DoSjLj) &&
675       Triple(M.getTargetTriple()).getArch() == Triple::wasm64)
676     report_fatal_error("Emscripten EH/SjLj is not supported with wasm64 yet");
677 
678   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
679   assert(TPC && "Expected a TargetPassConfig");
680   auto &TM = TPC->getTM<WebAssemblyTargetMachine>();
681 
682   // Declare (or get) global variables __THREW__, __threwValue, and
683   // getTempRet0/setTempRet0 function which are used in common for both
684   // exception handling and setjmp/longjmp handling
685   ThrewGV = getGlobalVariableI32(M, IRB, TM, "__THREW__");
686   ThrewValueGV = getGlobalVariableI32(M, IRB, TM, "__threwValue");
687   GetTempRet0Func = getEmscriptenFunction(
688       FunctionType::get(IRB.getInt32Ty(), false), "getTempRet0", &M);
689   SetTempRet0Func = getEmscriptenFunction(
690       FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
691       "setTempRet0", &M);
692   GetTempRet0Func->setDoesNotThrow();
693   SetTempRet0Func->setDoesNotThrow();
694 
695   bool Changed = false;
696 
697   // Exception handling
698   if (EnableEH) {
699     // Register __resumeException function
700     FunctionType *ResumeFTy =
701         FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
702     ResumeF = getEmscriptenFunction(ResumeFTy, "__resumeException", &M);
703 
704     // Register llvm_eh_typeid_for function
705     FunctionType *EHTypeIDTy =
706         FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
707     EHTypeIDF = getEmscriptenFunction(EHTypeIDTy, "llvm_eh_typeid_for", &M);
708 
709     for (Function &F : M) {
710       if (F.isDeclaration())
711         continue;
712       Changed |= runEHOnFunction(F);
713     }
714   }
715 
716   // Setjmp/longjmp handling
717   if (DoSjLj) {
718     Changed = true; // We have setjmp or longjmp somewhere
719 
720     // Register emscripten_longjmp function
721     FunctionType *FTy = FunctionType::get(
722         IRB.getVoidTy(), {IRB.getInt32Ty(), IRB.getInt32Ty()}, false);
723     EmLongjmpF = getEmscriptenFunction(FTy, "emscripten_longjmp", &M);
724 
725     if (LongjmpF)
726       replaceLongjmpWithEmscriptenLongjmp(LongjmpF, EmLongjmpF);
727 
728     if (SetjmpF) {
729       // Register saveSetjmp function
730       FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
731       FTy = FunctionType::get(Type::getInt32PtrTy(C),
732                               {SetjmpFTy->getParamType(0), IRB.getInt32Ty(),
733                                Type::getInt32PtrTy(C), IRB.getInt32Ty()},
734                               false);
735       SaveSetjmpF = getEmscriptenFunction(FTy, "saveSetjmp", &M);
736 
737       // Register testSetjmp function
738       FTy = FunctionType::get(
739           IRB.getInt32Ty(),
740           {IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()}, false);
741       TestSetjmpF = getEmscriptenFunction(FTy, "testSetjmp", &M);
742 
743       // Only traverse functions that uses setjmp in order not to insert
744       // unnecessary prep / cleanup code in every function
745       SmallPtrSet<Function *, 8> SetjmpUsers;
746       for (User *U : SetjmpF->users()) {
747         auto *UI = cast<Instruction>(U);
748         SetjmpUsers.insert(UI->getFunction());
749       }
750       for (Function *F : SetjmpUsers)
751         runSjLjOnFunction(*F);
752     }
753   }
754 
755   if (!Changed) {
756     // Delete unused global variables and functions
757     if (ResumeF)
758       ResumeF->eraseFromParent();
759     if (EHTypeIDF)
760       EHTypeIDF->eraseFromParent();
761     if (EmLongjmpF)
762       EmLongjmpF->eraseFromParent();
763     if (SaveSetjmpF)
764       SaveSetjmpF->eraseFromParent();
765     if (TestSetjmpF)
766       TestSetjmpF->eraseFromParent();
767     return false;
768   }
769 
770   return true;
771 }
772 
773 bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
774   Module &M = *F.getParent();
775   LLVMContext &C = F.getContext();
776   IRBuilder<> IRB(C);
777   bool Changed = false;
778   SmallVector<Instruction *, 64> ToErase;
779   SmallPtrSet<LandingPadInst *, 32> LandingPads;
780   bool AllowExceptions = areAllExceptionsAllowed() ||
781                          EHAllowlistSet.count(std::string(F.getName()));
782 
783   for (BasicBlock &BB : F) {
784     auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
785     if (!II)
786       continue;
787     Changed = true;
788     LandingPads.insert(II->getLandingPadInst());
789     IRB.SetInsertPoint(II);
790 
791     bool NeedInvoke = AllowExceptions && canThrow(II->getCalledOperand());
792     if (NeedInvoke) {
793       // Wrap invoke with invoke wrapper and generate preamble/postamble
794       Value *Threw = wrapInvoke(II);
795       ToErase.push_back(II);
796 
797       // Insert a branch based on __THREW__ variable
798       Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(1), "cmp");
799       IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
800 
801     } else {
802       // This can't throw, and we don't need this invoke, just replace it with a
803       // call+branch
804       SmallVector<Value *, 16> Args(II->arg_begin(), II->arg_end());
805       CallInst *NewCall =
806           IRB.CreateCall(II->getFunctionType(), II->getCalledOperand(), Args);
807       NewCall->takeName(II);
808       NewCall->setCallingConv(II->getCallingConv());
809       NewCall->setDebugLoc(II->getDebugLoc());
810       NewCall->setAttributes(II->getAttributes());
811       II->replaceAllUsesWith(NewCall);
812       ToErase.push_back(II);
813 
814       IRB.CreateBr(II->getNormalDest());
815 
816       // Remove any PHI node entries from the exception destination
817       II->getUnwindDest()->removePredecessor(&BB);
818     }
819   }
820 
821   // Process resume instructions
822   for (BasicBlock &BB : F) {
823     // Scan the body of the basic block for resumes
824     for (Instruction &I : BB) {
825       auto *RI = dyn_cast<ResumeInst>(&I);
826       if (!RI)
827         continue;
828       Changed = true;
829 
830       // Split the input into legal values
831       Value *Input = RI->getValue();
832       IRB.SetInsertPoint(RI);
833       Value *Low = IRB.CreateExtractValue(Input, 0, "low");
834       // Create a call to __resumeException function
835       IRB.CreateCall(ResumeF, {Low});
836       // Add a terminator to the block
837       IRB.CreateUnreachable();
838       ToErase.push_back(RI);
839     }
840   }
841 
842   // Process llvm.eh.typeid.for intrinsics
843   for (BasicBlock &BB : F) {
844     for (Instruction &I : BB) {
845       auto *CI = dyn_cast<CallInst>(&I);
846       if (!CI)
847         continue;
848       const Function *Callee = CI->getCalledFunction();
849       if (!Callee)
850         continue;
851       if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
852         continue;
853       Changed = true;
854 
855       IRB.SetInsertPoint(CI);
856       CallInst *NewCI =
857           IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
858       CI->replaceAllUsesWith(NewCI);
859       ToErase.push_back(CI);
860     }
861   }
862 
863   // Look for orphan landingpads, can occur in blocks with no predecessors
864   for (BasicBlock &BB : F) {
865     Instruction *I = BB.getFirstNonPHI();
866     if (auto *LPI = dyn_cast<LandingPadInst>(I))
867       LandingPads.insert(LPI);
868   }
869   Changed |= !LandingPads.empty();
870 
871   // Handle all the landingpad for this function together, as multiple invokes
872   // may share a single lp
873   for (LandingPadInst *LPI : LandingPads) {
874     IRB.SetInsertPoint(LPI);
875     SmallVector<Value *, 16> FMCArgs;
876     for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
877       Constant *Clause = LPI->getClause(I);
878       // As a temporary workaround for the lack of aggregate varargs support
879       // in the interface between JS and wasm, break out filter operands into
880       // their component elements.
881       if (LPI->isFilter(I)) {
882         auto *ATy = cast<ArrayType>(Clause->getType());
883         for (unsigned J = 0, E = ATy->getNumElements(); J < E; ++J) {
884           Value *EV = IRB.CreateExtractValue(Clause, makeArrayRef(J), "filter");
885           FMCArgs.push_back(EV);
886         }
887       } else
888         FMCArgs.push_back(Clause);
889     }
890 
891     // Create a call to __cxa_find_matching_catch_N function
892     Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
893     CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
894     Value *Undef = UndefValue::get(LPI->getType());
895     Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
896     Value *TempRet0 = IRB.CreateCall(GetTempRet0Func, None, "tempret0");
897     Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
898 
899     LPI->replaceAllUsesWith(Pair1);
900     ToErase.push_back(LPI);
901   }
902 
903   // Erase everything we no longer need in this function
904   for (Instruction *I : ToErase)
905     I->eraseFromParent();
906 
907   return Changed;
908 }
909 
910 // This tries to get debug info from the instruction before which a new
911 // instruction will be inserted, and if there's no debug info in that
912 // instruction, tries to get the info instead from the previous instruction (if
913 // any). If none of these has debug info and a DISubprogram is provided, it
914 // creates a dummy debug info with the first line of the function, because IR
915 // verifier requires all inlinable callsites should have debug info when both a
916 // caller and callee have DISubprogram. If none of these conditions are met,
917 // returns empty info.
918 static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore,
919                                     DISubprogram *SP) {
920   assert(InsertBefore);
921   if (InsertBefore->getDebugLoc())
922     return InsertBefore->getDebugLoc();
923   const Instruction *Prev = InsertBefore->getPrevNode();
924   if (Prev && Prev->getDebugLoc())
925     return Prev->getDebugLoc();
926   if (SP)
927     return DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
928   return DebugLoc();
929 }
930 
931 bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
932   Module &M = *F.getParent();
933   LLVMContext &C = F.getContext();
934   IRBuilder<> IRB(C);
935   SmallVector<Instruction *, 64> ToErase;
936   // Vector of %setjmpTable values
937   std::vector<Instruction *> SetjmpTableInsts;
938   // Vector of %setjmpTableSize values
939   std::vector<Instruction *> SetjmpTableSizeInsts;
940 
941   // Setjmp preparation
942 
943   // This instruction effectively means %setjmpTableSize = 4.
944   // We create this as an instruction intentionally, and we don't want to fold
945   // this instruction to a constant 4, because this value will be used in
946   // SSAUpdater.AddAvailableValue(...) later.
947   BasicBlock &EntryBB = F.getEntryBlock();
948   DebugLoc FirstDL = getOrCreateDebugLoc(&*EntryBB.begin(), F.getSubprogram());
949   BinaryOperator *SetjmpTableSize = BinaryOperator::Create(
950       Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize",
951       &*EntryBB.getFirstInsertionPt());
952   SetjmpTableSize->setDebugLoc(FirstDL);
953   // setjmpTable = (int *) malloc(40);
954   Instruction *SetjmpTable = CallInst::CreateMalloc(
955       SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
956       nullptr, nullptr, "setjmpTable");
957   SetjmpTable->setDebugLoc(FirstDL);
958   // CallInst::CreateMalloc may return a bitcast instruction if the result types
959   // mismatch. We need to set the debug loc for the original call too.
960   auto *MallocCall = SetjmpTable->stripPointerCasts();
961   if (auto *MallocCallI = dyn_cast<Instruction>(MallocCall)) {
962     MallocCallI->setDebugLoc(FirstDL);
963   }
964   // setjmpTable[0] = 0;
965   IRB.SetInsertPoint(SetjmpTableSize);
966   IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
967   SetjmpTableInsts.push_back(SetjmpTable);
968   SetjmpTableSizeInsts.push_back(SetjmpTableSize);
969 
970   // Setjmp transformation
971   std::vector<PHINode *> SetjmpRetPHIs;
972   Function *SetjmpF = M.getFunction("setjmp");
973   for (User *U : SetjmpF->users()) {
974     auto *CI = dyn_cast<CallInst>(U);
975     if (!CI)
976       report_fatal_error("Does not support indirect calls to setjmp");
977 
978     BasicBlock *BB = CI->getParent();
979     if (BB->getParent() != &F) // in other function
980       continue;
981 
982     // The tail is everything right after the call, and will be reached once
983     // when setjmp is called, and later when longjmp returns to the setjmp
984     BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
985     // Add a phi to the tail, which will be the output of setjmp, which
986     // indicates if this is the first call or a longjmp back. The phi directly
987     // uses the right value based on where we arrive from
988     IRB.SetInsertPoint(Tail->getFirstNonPHI());
989     PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
990 
991     // setjmp initial call returns 0
992     SetjmpRet->addIncoming(IRB.getInt32(0), BB);
993     // The proper output is now this, not the setjmp call itself
994     CI->replaceAllUsesWith(SetjmpRet);
995     // longjmp returns to the setjmp will add themselves to this phi
996     SetjmpRetPHIs.push_back(SetjmpRet);
997 
998     // Fix call target
999     // Our index in the function is our place in the array + 1 to avoid index
1000     // 0, because index 0 means the longjmp is not ours to handle.
1001     IRB.SetInsertPoint(CI);
1002     Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
1003                      SetjmpTable, SetjmpTableSize};
1004     Instruction *NewSetjmpTable =
1005         IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
1006     Instruction *NewSetjmpTableSize =
1007         IRB.CreateCall(GetTempRet0Func, None, "setjmpTableSize");
1008     SetjmpTableInsts.push_back(NewSetjmpTable);
1009     SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
1010     ToErase.push_back(CI);
1011   }
1012 
1013   // Update each call that can longjmp so it can return to a setjmp where
1014   // relevant.
1015 
1016   // Because we are creating new BBs while processing and don't want to make
1017   // all these newly created BBs candidates again for longjmp processing, we
1018   // first make the vector of candidate BBs.
1019   std::vector<BasicBlock *> BBs;
1020   for (BasicBlock &BB : F)
1021     BBs.push_back(&BB);
1022 
1023   // BBs.size() will change within the loop, so we query it every time
1024   for (unsigned I = 0; I < BBs.size(); I++) {
1025     BasicBlock *BB = BBs[I];
1026     for (Instruction &I : *BB) {
1027       assert(!isa<InvokeInst>(&I));
1028       auto *CI = dyn_cast<CallInst>(&I);
1029       if (!CI)
1030         continue;
1031 
1032       const Value *Callee = CI->getCalledOperand();
1033       if (!canLongjmp(M, Callee))
1034         continue;
1035       if (isEmAsmCall(M, Callee))
1036         report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
1037                                F.getName() +
1038                                ". Please consider using EM_JS, or move the "
1039                                "EM_ASM into another function.",
1040                            false);
1041 
1042       Value *Threw = nullptr;
1043       BasicBlock *Tail;
1044       if (Callee->getName().startswith("__invoke_")) {
1045         // If invoke wrapper has already been generated for this call in
1046         // previous EH phase, search for the load instruction
1047         // %__THREW__.val = __THREW__;
1048         // in postamble after the invoke wrapper call
1049         LoadInst *ThrewLI = nullptr;
1050         StoreInst *ThrewResetSI = nullptr;
1051         for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
1052              I != IE; ++I) {
1053           if (auto *LI = dyn_cast<LoadInst>(I))
1054             if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
1055               if (GV == ThrewGV) {
1056                 Threw = ThrewLI = LI;
1057                 break;
1058               }
1059         }
1060         // Search for the store instruction after the load above
1061         // __THREW__ = 0;
1062         for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
1063              I != IE; ++I) {
1064           if (auto *SI = dyn_cast<StoreInst>(I))
1065             if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand()))
1066               if (GV == ThrewGV && SI->getValueOperand() == IRB.getInt32(0)) {
1067                 ThrewResetSI = SI;
1068                 break;
1069               }
1070         }
1071         assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
1072         assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
1073         Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
1074 
1075       } else {
1076         // Wrap call with invoke wrapper and generate preamble/postamble
1077         Threw = wrapInvoke(CI);
1078         ToErase.push_back(CI);
1079         Tail = SplitBlock(BB, CI->getNextNode());
1080       }
1081 
1082       // We need to replace the terminator in Tail - SplitBlock makes BB go
1083       // straight to Tail, we need to check if a longjmp occurred, and go to the
1084       // right setjmp-tail if so
1085       ToErase.push_back(BB->getTerminator());
1086 
1087       // Generate a function call to testSetjmp function and preamble/postamble
1088       // code to figure out (1) whether longjmp occurred (2) if longjmp
1089       // occurred, which setjmp it corresponds to
1090       Value *Label = nullptr;
1091       Value *LongjmpResult = nullptr;
1092       BasicBlock *EndBB = nullptr;
1093       wrapTestSetjmp(BB, CI->getDebugLoc(), Threw, SetjmpTable, SetjmpTableSize,
1094                      Label, LongjmpResult, EndBB);
1095       assert(Label && LongjmpResult && EndBB);
1096 
1097       // Create switch instruction
1098       IRB.SetInsertPoint(EndBB);
1099       IRB.SetCurrentDebugLocation(EndBB->getInstList().back().getDebugLoc());
1100       SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1101       // -1 means no longjmp happened, continue normally (will hit the default
1102       // switch case). 0 means a longjmp that is not ours to handle, needs a
1103       // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1104       // 0).
1105       for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1106         SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1107         SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB);
1108       }
1109 
1110       // We are splitting the block here, and must continue to find other calls
1111       // in the block - which is now split. so continue to traverse in the Tail
1112       BBs.push_back(Tail);
1113     }
1114   }
1115 
1116   // Erase everything we no longer need in this function
1117   for (Instruction *I : ToErase)
1118     I->eraseFromParent();
1119 
1120   // Free setjmpTable buffer before each return instruction
1121   for (BasicBlock &BB : F) {
1122     Instruction *TI = BB.getTerminator();
1123     if (isa<ReturnInst>(TI)) {
1124       DebugLoc DL = getOrCreateDebugLoc(TI, F.getSubprogram());
1125       auto *Free = CallInst::CreateFree(SetjmpTable, TI);
1126       Free->setDebugLoc(DL);
1127       // CallInst::CreateFree may create a bitcast instruction if its argument
1128       // types mismatch. We need to set the debug loc for the bitcast too.
1129       if (auto *FreeCallI = dyn_cast<CallInst>(Free)) {
1130         if (auto *BitCastI = dyn_cast<BitCastInst>(FreeCallI->getArgOperand(0)))
1131           BitCastI->setDebugLoc(DL);
1132       }
1133     }
1134   }
1135 
1136   // Every call to saveSetjmp can change setjmpTable and setjmpTableSize
1137   // (when buffer reallocation occurs)
1138   // entry:
1139   //   setjmpTableSize = 4;
1140   //   setjmpTable = (int *) malloc(40);
1141   //   setjmpTable[0] = 0;
1142   // ...
1143   // somebb:
1144   //   setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
1145   //   setjmpTableSize = getTempRet0();
1146   // So we need to make sure the SSA for these variables is valid so that every
1147   // saveSetjmp and testSetjmp calls have the correct arguments.
1148   SSAUpdater SetjmpTableSSA;
1149   SSAUpdater SetjmpTableSizeSSA;
1150   SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
1151   SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
1152   for (Instruction *I : SetjmpTableInsts)
1153     SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
1154   for (Instruction *I : SetjmpTableSizeInsts)
1155     SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
1156 
1157   for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end();
1158        UI != UE;) {
1159     // Grab the use before incrementing the iterator.
1160     Use &U = *UI;
1161     // Increment the iterator before removing the use from the list.
1162     ++UI;
1163     if (auto *I = dyn_cast<Instruction>(U.getUser()))
1164       if (I->getParent() != &EntryBB)
1165         SetjmpTableSSA.RewriteUse(U);
1166   }
1167   for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end();
1168        UI != UE;) {
1169     Use &U = *UI;
1170     ++UI;
1171     if (auto *I = dyn_cast<Instruction>(U.getUser()))
1172       if (I->getParent() != &EntryBB)
1173         SetjmpTableSizeSSA.RewriteUse(U);
1174   }
1175 
1176   // Finally, our modifications to the cfg can break dominance of SSA variables.
1177   // For example, in this code,
1178   // if (x()) { .. setjmp() .. }
1179   // if (y()) { .. longjmp() .. }
1180   // We must split the longjmp block, and it can jump into the block splitted
1181   // from setjmp one. But that means that when we split the setjmp block, it's
1182   // first part no longer dominates its second part - there is a theoretically
1183   // possible control flow path where x() is false, then y() is true and we
1184   // reach the second part of the setjmp block, without ever reaching the first
1185   // part. So, we rebuild SSA form here.
1186   rebuildSSA(F);
1187   return true;
1188 }
1189