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