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