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   if (DoSjLj && TM.Options.ExceptionModel == ExceptionHandling::Wasm)
681     report_fatal_error("Emscripten SjLj is not supported with Wasm EH yet");
682 
683   // Declare (or get) global variables __THREW__, __threwValue, and
684   // getTempRet0/setTempRet0 function which are used in common for both
685   // exception handling and setjmp/longjmp handling
686   ThrewGV = getGlobalVariableI32(M, IRB, TM, "__THREW__");
687   ThrewValueGV = getGlobalVariableI32(M, IRB, TM, "__threwValue");
688   GetTempRet0Func = getEmscriptenFunction(
689       FunctionType::get(IRB.getInt32Ty(), false), "getTempRet0", &M);
690   SetTempRet0Func = getEmscriptenFunction(
691       FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
692       "setTempRet0", &M);
693   GetTempRet0Func->setDoesNotThrow();
694   SetTempRet0Func->setDoesNotThrow();
695 
696   bool Changed = false;
697 
698   // Exception handling
699   if (EnableEH) {
700     // Register __resumeException function
701     FunctionType *ResumeFTy =
702         FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
703     ResumeF = getEmscriptenFunction(ResumeFTy, "__resumeException", &M);
704 
705     // Register llvm_eh_typeid_for function
706     FunctionType *EHTypeIDTy =
707         FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
708     EHTypeIDF = getEmscriptenFunction(EHTypeIDTy, "llvm_eh_typeid_for", &M);
709 
710     for (Function &F : M) {
711       if (F.isDeclaration())
712         continue;
713       Changed |= runEHOnFunction(F);
714     }
715   }
716 
717   // Setjmp/longjmp handling
718   if (DoSjLj) {
719     Changed = true; // We have setjmp or longjmp somewhere
720 
721     // Register emscripten_longjmp function
722     FunctionType *FTy = FunctionType::get(
723         IRB.getVoidTy(), {IRB.getInt32Ty(), IRB.getInt32Ty()}, false);
724     EmLongjmpF = getEmscriptenFunction(FTy, "emscripten_longjmp", &M);
725 
726     if (LongjmpF)
727       replaceLongjmpWithEmscriptenLongjmp(LongjmpF, EmLongjmpF);
728 
729     if (SetjmpF) {
730       // Register saveSetjmp function
731       FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
732       FTy = FunctionType::get(Type::getInt32PtrTy(C),
733                               {SetjmpFTy->getParamType(0), IRB.getInt32Ty(),
734                                Type::getInt32PtrTy(C), IRB.getInt32Ty()},
735                               false);
736       SaveSetjmpF = getEmscriptenFunction(FTy, "saveSetjmp", &M);
737 
738       // Register testSetjmp function
739       FTy = FunctionType::get(
740           IRB.getInt32Ty(),
741           {IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()}, false);
742       TestSetjmpF = getEmscriptenFunction(FTy, "testSetjmp", &M);
743 
744       // Only traverse functions that uses setjmp in order not to insert
745       // unnecessary prep / cleanup code in every function
746       SmallPtrSet<Function *, 8> SetjmpUsers;
747       for (User *U : SetjmpF->users()) {
748         auto *UI = cast<Instruction>(U);
749         SetjmpUsers.insert(UI->getFunction());
750       }
751       for (Function *F : SetjmpUsers)
752         runSjLjOnFunction(*F);
753     }
754   }
755 
756   if (!Changed) {
757     // Delete unused global variables and functions
758     if (ResumeF)
759       ResumeF->eraseFromParent();
760     if (EHTypeIDF)
761       EHTypeIDF->eraseFromParent();
762     if (EmLongjmpF)
763       EmLongjmpF->eraseFromParent();
764     if (SaveSetjmpF)
765       SaveSetjmpF->eraseFromParent();
766     if (TestSetjmpF)
767       TestSetjmpF->eraseFromParent();
768     return false;
769   }
770 
771   return true;
772 }
773 
774 bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
775   Module &M = *F.getParent();
776   LLVMContext &C = F.getContext();
777   IRBuilder<> IRB(C);
778   bool Changed = false;
779   SmallVector<Instruction *, 64> ToErase;
780   SmallPtrSet<LandingPadInst *, 32> LandingPads;
781   bool AllowExceptions = areAllExceptionsAllowed() ||
782                          EHAllowlistSet.count(std::string(F.getName()));
783 
784   for (BasicBlock &BB : F) {
785     auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
786     if (!II)
787       continue;
788     Changed = true;
789     LandingPads.insert(II->getLandingPadInst());
790     IRB.SetInsertPoint(II);
791 
792     bool NeedInvoke = AllowExceptions && canThrow(II->getCalledOperand());
793     if (NeedInvoke) {
794       // Wrap invoke with invoke wrapper and generate preamble/postamble
795       Value *Threw = wrapInvoke(II);
796       ToErase.push_back(II);
797 
798       // Insert a branch based on __THREW__ variable
799       Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(1), "cmp");
800       IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
801 
802     } else {
803       // This can't throw, and we don't need this invoke, just replace it with a
804       // call+branch
805       SmallVector<Value *, 16> Args(II->args());
806       CallInst *NewCall =
807           IRB.CreateCall(II->getFunctionType(), II->getCalledOperand(), Args);
808       NewCall->takeName(II);
809       NewCall->setCallingConv(II->getCallingConv());
810       NewCall->setDebugLoc(II->getDebugLoc());
811       NewCall->setAttributes(II->getAttributes());
812       II->replaceAllUsesWith(NewCall);
813       ToErase.push_back(II);
814 
815       IRB.CreateBr(II->getNormalDest());
816 
817       // Remove any PHI node entries from the exception destination
818       II->getUnwindDest()->removePredecessor(&BB);
819     }
820   }
821 
822   // Process resume instructions
823   for (BasicBlock &BB : F) {
824     // Scan the body of the basic block for resumes
825     for (Instruction &I : BB) {
826       auto *RI = dyn_cast<ResumeInst>(&I);
827       if (!RI)
828         continue;
829       Changed = true;
830 
831       // Split the input into legal values
832       Value *Input = RI->getValue();
833       IRB.SetInsertPoint(RI);
834       Value *Low = IRB.CreateExtractValue(Input, 0, "low");
835       // Create a call to __resumeException function
836       IRB.CreateCall(ResumeF, {Low});
837       // Add a terminator to the block
838       IRB.CreateUnreachable();
839       ToErase.push_back(RI);
840     }
841   }
842 
843   // Process llvm.eh.typeid.for intrinsics
844   for (BasicBlock &BB : F) {
845     for (Instruction &I : BB) {
846       auto *CI = dyn_cast<CallInst>(&I);
847       if (!CI)
848         continue;
849       const Function *Callee = CI->getCalledFunction();
850       if (!Callee)
851         continue;
852       if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
853         continue;
854       Changed = true;
855 
856       IRB.SetInsertPoint(CI);
857       CallInst *NewCI =
858           IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
859       CI->replaceAllUsesWith(NewCI);
860       ToErase.push_back(CI);
861     }
862   }
863 
864   // Look for orphan landingpads, can occur in blocks with no predecessors
865   for (BasicBlock &BB : F) {
866     Instruction *I = BB.getFirstNonPHI();
867     if (auto *LPI = dyn_cast<LandingPadInst>(I))
868       LandingPads.insert(LPI);
869   }
870   Changed |= !LandingPads.empty();
871 
872   // Handle all the landingpad for this function together, as multiple invokes
873   // may share a single lp
874   for (LandingPadInst *LPI : LandingPads) {
875     IRB.SetInsertPoint(LPI);
876     SmallVector<Value *, 16> FMCArgs;
877     for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
878       Constant *Clause = LPI->getClause(I);
879       // As a temporary workaround for the lack of aggregate varargs support
880       // in the interface between JS and wasm, break out filter operands into
881       // their component elements.
882       if (LPI->isFilter(I)) {
883         auto *ATy = cast<ArrayType>(Clause->getType());
884         for (unsigned J = 0, E = ATy->getNumElements(); J < E; ++J) {
885           Value *EV = IRB.CreateExtractValue(Clause, makeArrayRef(J), "filter");
886           FMCArgs.push_back(EV);
887         }
888       } else
889         FMCArgs.push_back(Clause);
890     }
891 
892     // Create a call to __cxa_find_matching_catch_N function
893     Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
894     CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
895     Value *Undef = UndefValue::get(LPI->getType());
896     Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
897     Value *TempRet0 = IRB.CreateCall(GetTempRet0Func, None, "tempret0");
898     Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
899 
900     LPI->replaceAllUsesWith(Pair1);
901     ToErase.push_back(LPI);
902   }
903 
904   // Erase everything we no longer need in this function
905   for (Instruction *I : ToErase)
906     I->eraseFromParent();
907 
908   return Changed;
909 }
910 
911 // This tries to get debug info from the instruction before which a new
912 // instruction will be inserted, and if there's no debug info in that
913 // instruction, tries to get the info instead from the previous instruction (if
914 // any). If none of these has debug info and a DISubprogram is provided, it
915 // creates a dummy debug info with the first line of the function, because IR
916 // verifier requires all inlinable callsites should have debug info when both a
917 // caller and callee have DISubprogram. If none of these conditions are met,
918 // returns empty info.
919 static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore,
920                                     DISubprogram *SP) {
921   assert(InsertBefore);
922   if (InsertBefore->getDebugLoc())
923     return InsertBefore->getDebugLoc();
924   const Instruction *Prev = InsertBefore->getPrevNode();
925   if (Prev && Prev->getDebugLoc())
926     return Prev->getDebugLoc();
927   if (SP)
928     return DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
929   return DebugLoc();
930 }
931 
932 bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
933   Module &M = *F.getParent();
934   LLVMContext &C = F.getContext();
935   IRBuilder<> IRB(C);
936   SmallVector<Instruction *, 64> ToErase;
937   // Vector of %setjmpTable values
938   std::vector<Instruction *> SetjmpTableInsts;
939   // Vector of %setjmpTableSize values
940   std::vector<Instruction *> SetjmpTableSizeInsts;
941 
942   // Setjmp preparation
943 
944   // This instruction effectively means %setjmpTableSize = 4.
945   // We create this as an instruction intentionally, and we don't want to fold
946   // this instruction to a constant 4, because this value will be used in
947   // SSAUpdater.AddAvailableValue(...) later.
948   BasicBlock &EntryBB = F.getEntryBlock();
949   DebugLoc FirstDL = getOrCreateDebugLoc(&*EntryBB.begin(), F.getSubprogram());
950   BinaryOperator *SetjmpTableSize = BinaryOperator::Create(
951       Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize",
952       &*EntryBB.getFirstInsertionPt());
953   SetjmpTableSize->setDebugLoc(FirstDL);
954   // setjmpTable = (int *) malloc(40);
955   Instruction *SetjmpTable = CallInst::CreateMalloc(
956       SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
957       nullptr, nullptr, "setjmpTable");
958   SetjmpTable->setDebugLoc(FirstDL);
959   // CallInst::CreateMalloc may return a bitcast instruction if the result types
960   // mismatch. We need to set the debug loc for the original call too.
961   auto *MallocCall = SetjmpTable->stripPointerCasts();
962   if (auto *MallocCallI = dyn_cast<Instruction>(MallocCall)) {
963     MallocCallI->setDebugLoc(FirstDL);
964   }
965   // setjmpTable[0] = 0;
966   IRB.SetInsertPoint(SetjmpTableSize);
967   IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
968   SetjmpTableInsts.push_back(SetjmpTable);
969   SetjmpTableSizeInsts.push_back(SetjmpTableSize);
970 
971   // Setjmp transformation
972   std::vector<PHINode *> SetjmpRetPHIs;
973   Function *SetjmpF = M.getFunction("setjmp");
974   for (User *U : SetjmpF->users()) {
975     auto *CI = dyn_cast<CallInst>(U);
976     if (!CI)
977       report_fatal_error("Does not support indirect calls to setjmp");
978 
979     BasicBlock *BB = CI->getParent();
980     if (BB->getParent() != &F) // in other function
981       continue;
982 
983     // The tail is everything right after the call, and will be reached once
984     // when setjmp is called, and later when longjmp returns to the setjmp
985     BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
986     // Add a phi to the tail, which will be the output of setjmp, which
987     // indicates if this is the first call or a longjmp back. The phi directly
988     // uses the right value based on where we arrive from
989     IRB.SetInsertPoint(Tail->getFirstNonPHI());
990     PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
991 
992     // setjmp initial call returns 0
993     SetjmpRet->addIncoming(IRB.getInt32(0), BB);
994     // The proper output is now this, not the setjmp call itself
995     CI->replaceAllUsesWith(SetjmpRet);
996     // longjmp returns to the setjmp will add themselves to this phi
997     SetjmpRetPHIs.push_back(SetjmpRet);
998 
999     // Fix call target
1000     // Our index in the function is our place in the array + 1 to avoid index
1001     // 0, because index 0 means the longjmp is not ours to handle.
1002     IRB.SetInsertPoint(CI);
1003     Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
1004                      SetjmpTable, SetjmpTableSize};
1005     Instruction *NewSetjmpTable =
1006         IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
1007     Instruction *NewSetjmpTableSize =
1008         IRB.CreateCall(GetTempRet0Func, None, "setjmpTableSize");
1009     SetjmpTableInsts.push_back(NewSetjmpTable);
1010     SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
1011     ToErase.push_back(CI);
1012   }
1013 
1014   // Update each call that can longjmp so it can return to a setjmp where
1015   // relevant.
1016 
1017   // Because we are creating new BBs while processing and don't want to make
1018   // all these newly created BBs candidates again for longjmp processing, we
1019   // first make the vector of candidate BBs.
1020   std::vector<BasicBlock *> BBs;
1021   for (BasicBlock &BB : F)
1022     BBs.push_back(&BB);
1023 
1024   // BBs.size() will change within the loop, so we query it every time
1025   for (unsigned I = 0; I < BBs.size(); I++) {
1026     BasicBlock *BB = BBs[I];
1027     for (Instruction &I : *BB) {
1028       assert(!isa<InvokeInst>(&I));
1029       auto *CI = dyn_cast<CallInst>(&I);
1030       if (!CI)
1031         continue;
1032 
1033       const Value *Callee = CI->getCalledOperand();
1034       if (!canLongjmp(M, Callee))
1035         continue;
1036       if (isEmAsmCall(M, Callee))
1037         report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
1038                                F.getName() +
1039                                ". Please consider using EM_JS, or move the "
1040                                "EM_ASM into another function.",
1041                            false);
1042 
1043       Value *Threw = nullptr;
1044       BasicBlock *Tail;
1045       if (Callee->getName().startswith("__invoke_")) {
1046         // If invoke wrapper has already been generated for this call in
1047         // previous EH phase, search for the load instruction
1048         // %__THREW__.val = __THREW__;
1049         // in postamble after the invoke wrapper call
1050         LoadInst *ThrewLI = nullptr;
1051         StoreInst *ThrewResetSI = nullptr;
1052         for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
1053              I != IE; ++I) {
1054           if (auto *LI = dyn_cast<LoadInst>(I))
1055             if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
1056               if (GV == ThrewGV) {
1057                 Threw = ThrewLI = LI;
1058                 break;
1059               }
1060         }
1061         // Search for the store instruction after the load above
1062         // __THREW__ = 0;
1063         for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
1064              I != IE; ++I) {
1065           if (auto *SI = dyn_cast<StoreInst>(I))
1066             if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand()))
1067               if (GV == ThrewGV && SI->getValueOperand() == IRB.getInt32(0)) {
1068                 ThrewResetSI = SI;
1069                 break;
1070               }
1071         }
1072         assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
1073         assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
1074         Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
1075 
1076       } else {
1077         // Wrap call with invoke wrapper and generate preamble/postamble
1078         Threw = wrapInvoke(CI);
1079         ToErase.push_back(CI);
1080         Tail = SplitBlock(BB, CI->getNextNode());
1081       }
1082 
1083       // We need to replace the terminator in Tail - SplitBlock makes BB go
1084       // straight to Tail, we need to check if a longjmp occurred, and go to the
1085       // right setjmp-tail if so
1086       ToErase.push_back(BB->getTerminator());
1087 
1088       // Generate a function call to testSetjmp function and preamble/postamble
1089       // code to figure out (1) whether longjmp occurred (2) if longjmp
1090       // occurred, which setjmp it corresponds to
1091       Value *Label = nullptr;
1092       Value *LongjmpResult = nullptr;
1093       BasicBlock *EndBB = nullptr;
1094       wrapTestSetjmp(BB, CI->getDebugLoc(), Threw, SetjmpTable, SetjmpTableSize,
1095                      Label, LongjmpResult, EndBB);
1096       assert(Label && LongjmpResult && EndBB);
1097 
1098       // Create switch instruction
1099       IRB.SetInsertPoint(EndBB);
1100       IRB.SetCurrentDebugLocation(EndBB->getInstList().back().getDebugLoc());
1101       SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1102       // -1 means no longjmp happened, continue normally (will hit the default
1103       // switch case). 0 means a longjmp that is not ours to handle, needs a
1104       // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1105       // 0).
1106       for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1107         SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1108         SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB);
1109       }
1110 
1111       // We are splitting the block here, and must continue to find other calls
1112       // in the block - which is now split. so continue to traverse in the Tail
1113       BBs.push_back(Tail);
1114     }
1115   }
1116 
1117   // Erase everything we no longer need in this function
1118   for (Instruction *I : ToErase)
1119     I->eraseFromParent();
1120 
1121   // Free setjmpTable buffer before each return instruction
1122   for (BasicBlock &BB : F) {
1123     Instruction *TI = BB.getTerminator();
1124     if (isa<ReturnInst>(TI)) {
1125       DebugLoc DL = getOrCreateDebugLoc(TI, F.getSubprogram());
1126       auto *Free = CallInst::CreateFree(SetjmpTable, TI);
1127       Free->setDebugLoc(DL);
1128       // CallInst::CreateFree may create a bitcast instruction if its argument
1129       // types mismatch. We need to set the debug loc for the bitcast too.
1130       if (auto *FreeCallI = dyn_cast<CallInst>(Free)) {
1131         if (auto *BitCastI = dyn_cast<BitCastInst>(FreeCallI->getArgOperand(0)))
1132           BitCastI->setDebugLoc(DL);
1133       }
1134     }
1135   }
1136 
1137   // Every call to saveSetjmp can change setjmpTable and setjmpTableSize
1138   // (when buffer reallocation occurs)
1139   // entry:
1140   //   setjmpTableSize = 4;
1141   //   setjmpTable = (int *) malloc(40);
1142   //   setjmpTable[0] = 0;
1143   // ...
1144   // somebb:
1145   //   setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
1146   //   setjmpTableSize = getTempRet0();
1147   // So we need to make sure the SSA for these variables is valid so that every
1148   // saveSetjmp and testSetjmp calls have the correct arguments.
1149   SSAUpdater SetjmpTableSSA;
1150   SSAUpdater SetjmpTableSizeSSA;
1151   SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
1152   SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
1153   for (Instruction *I : SetjmpTableInsts)
1154     SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
1155   for (Instruction *I : SetjmpTableSizeInsts)
1156     SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
1157 
1158   for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end();
1159        UI != UE;) {
1160     // Grab the use before incrementing the iterator.
1161     Use &U = *UI;
1162     // Increment the iterator before removing the use from the list.
1163     ++UI;
1164     if (auto *I = dyn_cast<Instruction>(U.getUser()))
1165       if (I->getParent() != &EntryBB)
1166         SetjmpTableSSA.RewriteUse(U);
1167   }
1168   for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end();
1169        UI != UE;) {
1170     Use &U = *UI;
1171     ++UI;
1172     if (auto *I = dyn_cast<Instruction>(U.getUser()))
1173       if (I->getParent() != &EntryBB)
1174         SetjmpTableSizeSSA.RewriteUse(U);
1175   }
1176 
1177   // Finally, our modifications to the cfg can break dominance of SSA variables.
1178   // For example, in this code,
1179   // if (x()) { .. setjmp() .. }
1180   // if (y()) { .. longjmp() .. }
1181   // We must split the longjmp block, and it can jump into the block splitted
1182   // from setjmp one. But that means that when we split the setjmp block, it's
1183   // first part no longer dominates its second part - there is a theoretically
1184   // possible control flow path where x() is false, then y() is true and we
1185   // reach the second part of the setjmp block, without ever reaching the first
1186   // part. So, we rebuild SSA form here.
1187   rebuildSSA(F);
1188   return true;
1189 }
1190