xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
17330f729Sjoerg //=== WebAssemblyLowerEmscriptenEHSjLj.cpp - Lower exceptions for Emscripten =//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg ///
97330f729Sjoerg /// \file
107330f729Sjoerg /// This file lowers exception-related instructions and setjmp/longjmp
117330f729Sjoerg /// function calls in order to use Emscripten's JavaScript try and catch
127330f729Sjoerg /// mechanism.
137330f729Sjoerg ///
147330f729Sjoerg /// To handle exceptions and setjmp/longjmps, this scheme relies on JavaScript's
157330f729Sjoerg /// try and catch syntax and relevant exception-related libraries implemented
16*82d56013Sjoerg /// in JavaScript glue code that will be produced by Emscripten.
177330f729Sjoerg ///
187330f729Sjoerg /// * Exception handling
197330f729Sjoerg /// This pass lowers invokes and landingpads into library functions in JS glue
207330f729Sjoerg /// code. Invokes are lowered into function wrappers called invoke wrappers that
217330f729Sjoerg /// exist in JS side, which wraps the original function call with JS try-catch.
227330f729Sjoerg /// If an exception occurred, cxa_throw() function in JS side sets some
237330f729Sjoerg /// variables (see below) so we can check whether an exception occurred from
247330f729Sjoerg /// wasm code and handle it appropriately.
257330f729Sjoerg ///
267330f729Sjoerg /// * Setjmp-longjmp handling
277330f729Sjoerg /// This pass lowers setjmp to a reasonably-performant approach for emscripten.
287330f729Sjoerg /// The idea is that each block with a setjmp is broken up into two parts: the
297330f729Sjoerg /// part containing setjmp and the part right after the setjmp. The latter part
307330f729Sjoerg /// is either reached from the setjmp, or later from a longjmp. To handle the
317330f729Sjoerg /// longjmp, all calls that might longjmp are also called using invoke wrappers
327330f729Sjoerg /// and thus JS / try-catch. JS longjmp() function also sets some variables so
337330f729Sjoerg /// we can check / whether a longjmp occurred from wasm code. Each block with a
347330f729Sjoerg /// function call that might longjmp is also split up after the longjmp call.
357330f729Sjoerg /// After the longjmp call, we check whether a longjmp occurred, and if it did,
367330f729Sjoerg /// which setjmp it corresponds to, and jump to the right post-setjmp block.
377330f729Sjoerg /// We assume setjmp-longjmp handling always run after EH handling, which means
387330f729Sjoerg /// we don't expect any exception-related instructions when SjLj runs.
397330f729Sjoerg /// FIXME Currently this scheme does not support indirect call of setjmp,
407330f729Sjoerg /// because of the limitation of the scheme itself. fastcomp does not support it
417330f729Sjoerg /// either.
427330f729Sjoerg ///
437330f729Sjoerg /// In detail, this pass does following things:
447330f729Sjoerg ///
457330f729Sjoerg /// 1) Assumes the existence of global variables: __THREW__, __threwValue
46*82d56013Sjoerg ///    __THREW__ and __threwValue are defined in compiler-rt in Emscripten.
47*82d56013Sjoerg ///    These variables are used for both exceptions and setjmp/longjmps.
487330f729Sjoerg ///    __THREW__ indicates whether an exception or a longjmp occurred or not. 0
497330f729Sjoerg ///    means nothing occurred, 1 means an exception occurred, and other numbers
50*82d56013Sjoerg ///    mean a longjmp occurred. In the case of longjmp, __THREW__ variable
517330f729Sjoerg ///    indicates the corresponding setjmp buffer the longjmp corresponds to.
527330f729Sjoerg ///
537330f729Sjoerg /// * Exception handling
547330f729Sjoerg ///
557330f729Sjoerg /// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions
56*82d56013Sjoerg ///    at link time. setThrew exists in Emscripten's compiler-rt:
577330f729Sjoerg ///
58*82d56013Sjoerg ///    void setThrew(uintptr_t threw, int value) {
597330f729Sjoerg ///      if (__THREW__ == 0) {
607330f729Sjoerg ///        __THREW__ = threw;
617330f729Sjoerg ///        __threwValue = value;
627330f729Sjoerg ///      }
637330f729Sjoerg ///    }
647330f729Sjoerg //
657330f729Sjoerg ///    setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
667330f729Sjoerg ///    In exception handling, getTempRet0 indicates the type of an exception
677330f729Sjoerg ///    caught, and in setjmp/longjmp, it means the second argument to longjmp
687330f729Sjoerg ///    function.
697330f729Sjoerg ///
707330f729Sjoerg /// 3) Lower
717330f729Sjoerg ///      invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
727330f729Sjoerg ///    into
737330f729Sjoerg ///      __THREW__ = 0;
747330f729Sjoerg ///      call @__invoke_SIG(func, arg1, arg2)
757330f729Sjoerg ///      %__THREW__.val = __THREW__;
767330f729Sjoerg ///      __THREW__ = 0;
777330f729Sjoerg ///      if (%__THREW__.val == 1)
787330f729Sjoerg ///        goto %lpad
797330f729Sjoerg ///      else
807330f729Sjoerg ///         goto %invoke.cont
817330f729Sjoerg ///    SIG is a mangled string generated based on the LLVM IR-level function
827330f729Sjoerg ///    signature. After LLVM IR types are lowered to the target wasm types,
837330f729Sjoerg ///    the names for these wrappers will change based on wasm types as well,
847330f729Sjoerg ///    as in invoke_vi (function takes an int and returns void). The bodies of
857330f729Sjoerg ///    these wrappers will be generated in JS glue code, and inside those
867330f729Sjoerg ///    wrappers we use JS try-catch to generate actual exception effects. It
877330f729Sjoerg ///    also calls the original callee function. An example wrapper in JS code
887330f729Sjoerg ///    would look like this:
897330f729Sjoerg ///      function invoke_vi(index,a1) {
907330f729Sjoerg ///        try {
917330f729Sjoerg ///          Module["dynCall_vi"](index,a1); // This calls original callee
927330f729Sjoerg ///        } catch(e) {
937330f729Sjoerg ///          if (typeof e !== 'number' && e !== 'longjmp') throw e;
94*82d56013Sjoerg ///          _setThrew(1, 0); // setThrew is called here
957330f729Sjoerg ///        }
967330f729Sjoerg ///      }
977330f729Sjoerg ///    If an exception is thrown, __THREW__ will be set to true in a wrapper,
987330f729Sjoerg ///    so we can jump to the right BB based on this value.
997330f729Sjoerg ///
1007330f729Sjoerg /// 4) Lower
1017330f729Sjoerg ///      %val = landingpad catch c1 catch c2 catch c3 ...
1027330f729Sjoerg ///      ... use %val ...
1037330f729Sjoerg ///    into
1047330f729Sjoerg ///      %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
1057330f729Sjoerg ///      %val = {%fmc, getTempRet0()}
1067330f729Sjoerg ///      ... use %val ...
1077330f729Sjoerg ///    Here N is a number calculated based on the number of clauses.
1087330f729Sjoerg ///    setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
1097330f729Sjoerg ///
1107330f729Sjoerg /// 5) Lower
1117330f729Sjoerg ///      resume {%a, %b}
1127330f729Sjoerg ///    into
1137330f729Sjoerg ///      call @__resumeException(%a)
1147330f729Sjoerg ///    where __resumeException() is a function in JS glue code.
1157330f729Sjoerg ///
1167330f729Sjoerg /// 6) Lower
1177330f729Sjoerg ///      call @llvm.eh.typeid.for(type) (intrinsic)
1187330f729Sjoerg ///    into
1197330f729Sjoerg ///      call @llvm_eh_typeid_for(type)
1207330f729Sjoerg ///    llvm_eh_typeid_for function will be generated in JS glue code.
1217330f729Sjoerg ///
1227330f729Sjoerg /// * Setjmp / Longjmp handling
1237330f729Sjoerg ///
1247330f729Sjoerg /// In case calls to longjmp() exists
1257330f729Sjoerg ///
1267330f729Sjoerg /// 1) Lower
1277330f729Sjoerg ///      longjmp(buf, value)
1287330f729Sjoerg ///    into
129*82d56013Sjoerg ///      emscripten_longjmp(buf, value)
1307330f729Sjoerg ///
1317330f729Sjoerg /// In case calls to setjmp() exists
1327330f729Sjoerg ///
1337330f729Sjoerg /// 2) In the function entry that calls setjmp, initialize setjmpTable and
1347330f729Sjoerg ///    sejmpTableSize as follows:
1357330f729Sjoerg ///      setjmpTableSize = 4;
1367330f729Sjoerg ///      setjmpTable = (int *) malloc(40);
1377330f729Sjoerg ///      setjmpTable[0] = 0;
138*82d56013Sjoerg ///    setjmpTable and setjmpTableSize are used to call saveSetjmp() function in
139*82d56013Sjoerg ///    Emscripten compiler-rt.
1407330f729Sjoerg ///
1417330f729Sjoerg /// 3) Lower
1427330f729Sjoerg ///      setjmp(buf)
1437330f729Sjoerg ///    into
1447330f729Sjoerg ///      setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
1457330f729Sjoerg ///      setjmpTableSize = getTempRet0();
1467330f729Sjoerg ///    For each dynamic setjmp call, setjmpTable stores its ID (a number which
1477330f729Sjoerg ///    is incrementally assigned from 0) and its label (a unique number that
1487330f729Sjoerg ///    represents each callsite of setjmp). When we need more entries in
149*82d56013Sjoerg ///    setjmpTable, it is reallocated in saveSetjmp() in Emscripten's
150*82d56013Sjoerg ///    compiler-rt and it will return the new table address, and assign the new
151*82d56013Sjoerg ///    table size in setTempRet0(). saveSetjmp also stores the setjmp's ID into
152*82d56013Sjoerg ///    the buffer buf. A BB with setjmp is split into two after setjmp call in
153*82d56013Sjoerg ///    order to make the post-setjmp BB the possible destination of longjmp BB.
1547330f729Sjoerg ///
1557330f729Sjoerg ///
1567330f729Sjoerg /// 4) Lower every call that might longjmp into
1577330f729Sjoerg ///      __THREW__ = 0;
1587330f729Sjoerg ///      call @__invoke_SIG(func, arg1, arg2)
1597330f729Sjoerg ///      %__THREW__.val = __THREW__;
1607330f729Sjoerg ///      __THREW__ = 0;
1617330f729Sjoerg ///      if (%__THREW__.val != 0 & __threwValue != 0) {
1627330f729Sjoerg ///        %label = testSetjmp(mem[%__THREW__.val], setjmpTable,
1637330f729Sjoerg ///                            setjmpTableSize);
1647330f729Sjoerg ///        if (%label == 0)
1657330f729Sjoerg ///          emscripten_longjmp(%__THREW__.val, __threwValue);
1667330f729Sjoerg ///        setTempRet0(__threwValue);
1677330f729Sjoerg ///      } else {
1687330f729Sjoerg ///        %label = -1;
1697330f729Sjoerg ///      }
1707330f729Sjoerg ///      longjmp_result = getTempRet0();
1717330f729Sjoerg ///      switch label {
1727330f729Sjoerg ///        label 1: goto post-setjmp BB 1
1737330f729Sjoerg ///        label 2: goto post-setjmp BB 2
1747330f729Sjoerg ///        ...
1757330f729Sjoerg ///        default: goto splitted next BB
1767330f729Sjoerg ///      }
1777330f729Sjoerg ///    testSetjmp examines setjmpTable to see if there is a matching setjmp
1787330f729Sjoerg ///    call. After calling an invoke wrapper, if a longjmp occurred, __THREW__
1797330f729Sjoerg ///    will be the address of matching jmp_buf buffer and __threwValue be the
1807330f729Sjoerg ///    second argument to longjmp. mem[__THREW__.val] is a setjmp ID that is
1817330f729Sjoerg ///    stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to
1827330f729Sjoerg ///    each setjmp callsite. Label 0 means this longjmp buffer does not
1837330f729Sjoerg ///    correspond to one of the setjmp callsites in this function, so in this
184*82d56013Sjoerg ///    case we just chain the longjmp to the caller. Label -1 means no longjmp
185*82d56013Sjoerg ///    occurred. Otherwise we jump to the right post-setjmp BB based on the
186*82d56013Sjoerg ///    label.
1877330f729Sjoerg ///
1887330f729Sjoerg ///===----------------------------------------------------------------------===//
1897330f729Sjoerg 
1907330f729Sjoerg #include "WebAssembly.h"
191*82d56013Sjoerg #include "WebAssemblyTargetMachine.h"
192*82d56013Sjoerg #include "llvm/ADT/StringExtras.h"
193*82d56013Sjoerg #include "llvm/CodeGen/TargetPassConfig.h"
194*82d56013Sjoerg #include "llvm/IR/DebugInfoMetadata.h"
1957330f729Sjoerg #include "llvm/IR/Dominators.h"
1967330f729Sjoerg #include "llvm/IR/IRBuilder.h"
197*82d56013Sjoerg #include "llvm/Support/CommandLine.h"
1987330f729Sjoerg #include "llvm/Transforms/Utils/BasicBlockUtils.h"
1997330f729Sjoerg #include "llvm/Transforms/Utils/SSAUpdater.h"
2007330f729Sjoerg 
2017330f729Sjoerg using namespace llvm;
2027330f729Sjoerg 
2037330f729Sjoerg #define DEBUG_TYPE "wasm-lower-em-ehsjlj"
2047330f729Sjoerg 
2057330f729Sjoerg static cl::list<std::string>
206*82d56013Sjoerg     EHAllowlist("emscripten-cxx-exceptions-allowed",
2077330f729Sjoerg                 cl::desc("The list of function names in which Emscripten-style "
2087330f729Sjoerg                          "exception handling is enabled (see emscripten "
209*82d56013Sjoerg                          "EMSCRIPTEN_CATCHING_ALLOWED options)"),
2107330f729Sjoerg                 cl::CommaSeparated);
2117330f729Sjoerg 
2127330f729Sjoerg namespace {
2137330f729Sjoerg class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
2147330f729Sjoerg   bool EnableEH;   // Enable exception handling
2157330f729Sjoerg   bool EnableSjLj; // Enable setjmp/longjmp handling
2167330f729Sjoerg 
2177330f729Sjoerg   GlobalVariable *ThrewGV = nullptr;
2187330f729Sjoerg   GlobalVariable *ThrewValueGV = nullptr;
2197330f729Sjoerg   Function *GetTempRet0Func = nullptr;
2207330f729Sjoerg   Function *SetTempRet0Func = nullptr;
2217330f729Sjoerg   Function *ResumeF = nullptr;
2227330f729Sjoerg   Function *EHTypeIDF = nullptr;
2237330f729Sjoerg   Function *EmLongjmpF = nullptr;
2247330f729Sjoerg   Function *SaveSetjmpF = nullptr;
2257330f729Sjoerg   Function *TestSetjmpF = nullptr;
2267330f729Sjoerg 
2277330f729Sjoerg   // __cxa_find_matching_catch_N functions.
2287330f729Sjoerg   // Indexed by the number of clauses in an original landingpad instruction.
2297330f729Sjoerg   DenseMap<int, Function *> FindMatchingCatches;
2307330f729Sjoerg   // Map of <function signature string, invoke_ wrappers>
2317330f729Sjoerg   StringMap<Function *> InvokeWrappers;
232*82d56013Sjoerg   // Set of allowed function names for exception handling
233*82d56013Sjoerg   std::set<std::string> EHAllowlistSet;
2347330f729Sjoerg 
getPassName() const2357330f729Sjoerg   StringRef getPassName() const override {
2367330f729Sjoerg     return "WebAssembly Lower Emscripten Exceptions";
2377330f729Sjoerg   }
2387330f729Sjoerg 
2397330f729Sjoerg   bool runEHOnFunction(Function &F);
2407330f729Sjoerg   bool runSjLjOnFunction(Function &F);
2417330f729Sjoerg   Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
2427330f729Sjoerg 
243*82d56013Sjoerg   Value *wrapInvoke(CallBase *CI);
244*82d56013Sjoerg   void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw,
2457330f729Sjoerg                       Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
2467330f729Sjoerg                       Value *&LongjmpResult, BasicBlock *&EndBB);
247*82d56013Sjoerg   Function *getInvokeWrapper(CallBase *CI);
2487330f729Sjoerg 
areAllExceptionsAllowed() const249*82d56013Sjoerg   bool areAllExceptionsAllowed() const { return EHAllowlistSet.empty(); }
2507330f729Sjoerg   bool canLongjmp(Module &M, const Value *Callee) const;
2517330f729Sjoerg   bool isEmAsmCall(Module &M, const Value *Callee) const;
2527330f729Sjoerg 
2537330f729Sjoerg   void rebuildSSA(Function &F);
2547330f729Sjoerg 
2557330f729Sjoerg public:
2567330f729Sjoerg   static char ID;
2577330f729Sjoerg 
WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH=true,bool EnableSjLj=true)2587330f729Sjoerg   WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH = true, bool EnableSjLj = true)
2597330f729Sjoerg       : ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj) {
260*82d56013Sjoerg     EHAllowlistSet.insert(EHAllowlist.begin(), EHAllowlist.end());
2617330f729Sjoerg   }
2627330f729Sjoerg   bool runOnModule(Module &M) override;
2637330f729Sjoerg 
getAnalysisUsage(AnalysisUsage & AU) const2647330f729Sjoerg   void getAnalysisUsage(AnalysisUsage &AU) const override {
2657330f729Sjoerg     AU.addRequired<DominatorTreeWrapperPass>();
2667330f729Sjoerg   }
2677330f729Sjoerg };
2687330f729Sjoerg } // End anonymous namespace
2697330f729Sjoerg 
2707330f729Sjoerg char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
2717330f729Sjoerg INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
2727330f729Sjoerg                 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
2737330f729Sjoerg                 false, false)
2747330f729Sjoerg 
createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH,bool EnableSjLj)2757330f729Sjoerg ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH,
2767330f729Sjoerg                                                          bool EnableSjLj) {
2777330f729Sjoerg   return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj);
2787330f729Sjoerg }
2797330f729Sjoerg 
canThrow(const Value * V)2807330f729Sjoerg static bool canThrow(const Value *V) {
2817330f729Sjoerg   if (const auto *F = dyn_cast<const Function>(V)) {
2827330f729Sjoerg     // Intrinsics cannot throw
2837330f729Sjoerg     if (F->isIntrinsic())
2847330f729Sjoerg       return false;
2857330f729Sjoerg     StringRef Name = F->getName();
2867330f729Sjoerg     // leave setjmp and longjmp (mostly) alone, we process them properly later
2877330f729Sjoerg     if (Name == "setjmp" || Name == "longjmp")
2887330f729Sjoerg       return false;
2897330f729Sjoerg     return !F->doesNotThrow();
2907330f729Sjoerg   }
2917330f729Sjoerg   // not a function, so an indirect call - can throw, we can't tell
2927330f729Sjoerg   return true;
2937330f729Sjoerg }
2947330f729Sjoerg 
2957330f729Sjoerg // Get a global variable with the given name. If it doesn't exist declare it,
296*82d56013Sjoerg // which will generate an import and assume that it will exist at link time.
getGlobalVariable(Module & M,Type * Ty,WebAssemblyTargetMachine & TM,const char * Name)297*82d56013Sjoerg static GlobalVariable *getGlobalVariable(Module &M, Type *Ty,
298*82d56013Sjoerg                                          WebAssemblyTargetMachine &TM,
2997330f729Sjoerg                                          const char *Name) {
300*82d56013Sjoerg   auto *GV = dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, Ty));
3017330f729Sjoerg   if (!GV)
3027330f729Sjoerg     report_fatal_error(Twine("unable to create global: ") + Name);
3037330f729Sjoerg 
304*82d56013Sjoerg   // If the target supports TLS, make this variable thread-local. We can't just
305*82d56013Sjoerg   // unconditionally make it thread-local and depend on
306*82d56013Sjoerg   // CoalesceFeaturesAndStripAtomics to downgrade it, because stripping TLS has
307*82d56013Sjoerg   // the side effect of disallowing the object from being linked into a
308*82d56013Sjoerg   // shared-memory module, which we don't want to be responsible for.
309*82d56013Sjoerg   auto *Subtarget = TM.getSubtargetImpl();
310*82d56013Sjoerg   auto TLS = Subtarget->hasAtomics() && Subtarget->hasBulkMemory()
311*82d56013Sjoerg                  ? GlobalValue::LocalExecTLSModel
312*82d56013Sjoerg                  : GlobalValue::NotThreadLocal;
313*82d56013Sjoerg   GV->setThreadLocalMode(TLS);
3147330f729Sjoerg   return GV;
3157330f729Sjoerg }
3167330f729Sjoerg 
3177330f729Sjoerg // Simple function name mangler.
3187330f729Sjoerg // This function simply takes LLVM's string representation of parameter types
3197330f729Sjoerg // and concatenate them with '_'. There are non-alphanumeric characters but llc
3207330f729Sjoerg // is ok with it, and we need to postprocess these names after the lowering
3217330f729Sjoerg // phase anyway.
getSignature(FunctionType * FTy)3227330f729Sjoerg static std::string getSignature(FunctionType *FTy) {
3237330f729Sjoerg   std::string Sig;
3247330f729Sjoerg   raw_string_ostream OS(Sig);
3257330f729Sjoerg   OS << *FTy->getReturnType();
3267330f729Sjoerg   for (Type *ParamTy : FTy->params())
3277330f729Sjoerg     OS << "_" << *ParamTy;
3287330f729Sjoerg   if (FTy->isVarArg())
3297330f729Sjoerg     OS << "_...";
3307330f729Sjoerg   Sig = OS.str();
331*82d56013Sjoerg   erase_if(Sig, isSpace);
3327330f729Sjoerg   // When s2wasm parses .s file, a comma means the end of an argument. So a
3337330f729Sjoerg   // mangled function name can contain any character but a comma.
3347330f729Sjoerg   std::replace(Sig.begin(), Sig.end(), ',', '.');
3357330f729Sjoerg   return Sig;
3367330f729Sjoerg }
3377330f729Sjoerg 
getEmscriptenFunction(FunctionType * Ty,const Twine & Name,Module * M)338*82d56013Sjoerg static Function *getEmscriptenFunction(FunctionType *Ty, const Twine &Name,
339*82d56013Sjoerg                                        Module *M) {
340*82d56013Sjoerg   Function* F = Function::Create(Ty, GlobalValue::ExternalLinkage, Name, M);
341*82d56013Sjoerg   // Tell the linker that this function is expected to be imported from the
342*82d56013Sjoerg   // 'env' module.
343*82d56013Sjoerg   if (!F->hasFnAttribute("wasm-import-module")) {
344*82d56013Sjoerg     llvm::AttrBuilder B;
345*82d56013Sjoerg     B.addAttribute("wasm-import-module", "env");
346*82d56013Sjoerg     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
347*82d56013Sjoerg   }
348*82d56013Sjoerg   if (!F->hasFnAttribute("wasm-import-name")) {
349*82d56013Sjoerg     llvm::AttrBuilder B;
350*82d56013Sjoerg     B.addAttribute("wasm-import-name", F->getName());
351*82d56013Sjoerg     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
352*82d56013Sjoerg   }
353*82d56013Sjoerg   return F;
354*82d56013Sjoerg }
355*82d56013Sjoerg 
356*82d56013Sjoerg // Returns an integer type for the target architecture's address space.
357*82d56013Sjoerg // i32 for wasm32 and i64 for wasm64.
getAddrIntType(Module * M)358*82d56013Sjoerg static Type *getAddrIntType(Module *M) {
359*82d56013Sjoerg   IRBuilder<> IRB(M->getContext());
360*82d56013Sjoerg   return IRB.getIntNTy(M->getDataLayout().getPointerSizeInBits());
361*82d56013Sjoerg }
362*82d56013Sjoerg 
363*82d56013Sjoerg // Returns an integer pointer type for the target architecture's address space.
364*82d56013Sjoerg // i32* for wasm32 and i64* for wasm64.
getAddrPtrType(Module * M)365*82d56013Sjoerg static Type *getAddrPtrType(Module *M) {
366*82d56013Sjoerg   return Type::getIntNPtrTy(M->getContext(),
367*82d56013Sjoerg                             M->getDataLayout().getPointerSizeInBits());
368*82d56013Sjoerg }
369*82d56013Sjoerg 
370*82d56013Sjoerg // Returns an integer whose type is the integer type for the target's address
371*82d56013Sjoerg // space. Returns (i32 C) for wasm32 and (i64 C) for wasm64, when C is the
372*82d56013Sjoerg // integer.
getAddrSizeInt(Module * M,uint64_t C)373*82d56013Sjoerg static Value *getAddrSizeInt(Module *M, uint64_t C) {
374*82d56013Sjoerg   IRBuilder<> IRB(M->getContext());
375*82d56013Sjoerg   return IRB.getIntN(M->getDataLayout().getPointerSizeInBits(), C);
376*82d56013Sjoerg }
377*82d56013Sjoerg 
3787330f729Sjoerg // Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
3797330f729Sjoerg // This is because a landingpad instruction contains two more arguments, a
3807330f729Sjoerg // personality function and a cleanup bit, and __cxa_find_matching_catch_N
3817330f729Sjoerg // functions are named after the number of arguments in the original landingpad
3827330f729Sjoerg // instruction.
3837330f729Sjoerg Function *
getFindMatchingCatch(Module & M,unsigned NumClauses)3847330f729Sjoerg WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
3857330f729Sjoerg                                                        unsigned NumClauses) {
3867330f729Sjoerg   if (FindMatchingCatches.count(NumClauses))
3877330f729Sjoerg     return FindMatchingCatches[NumClauses];
3887330f729Sjoerg   PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
3897330f729Sjoerg   SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
3907330f729Sjoerg   FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
391*82d56013Sjoerg   Function *F = getEmscriptenFunction(
392*82d56013Sjoerg       FTy, "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M);
3937330f729Sjoerg   FindMatchingCatches[NumClauses] = F;
3947330f729Sjoerg   return F;
3957330f729Sjoerg }
3967330f729Sjoerg 
3977330f729Sjoerg // Generate invoke wrapper seqence with preamble and postamble
3987330f729Sjoerg // Preamble:
3997330f729Sjoerg // __THREW__ = 0;
4007330f729Sjoerg // Postamble:
4017330f729Sjoerg // %__THREW__.val = __THREW__; __THREW__ = 0;
4027330f729Sjoerg // Returns %__THREW__.val, which indicates whether an exception is thrown (or
4037330f729Sjoerg // whether longjmp occurred), for future use.
wrapInvoke(CallBase * CI)404*82d56013Sjoerg Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) {
405*82d56013Sjoerg   Module *M = CI->getModule();
406*82d56013Sjoerg   LLVMContext &C = M->getContext();
4077330f729Sjoerg 
4087330f729Sjoerg   // If we are calling a function that is noreturn, we must remove that
4097330f729Sjoerg   // attribute. The code we insert here does expect it to return, after we
4107330f729Sjoerg   // catch the exception.
4117330f729Sjoerg   if (CI->doesNotReturn()) {
412*82d56013Sjoerg     if (auto *F = CI->getCalledFunction())
4137330f729Sjoerg       F->removeFnAttr(Attribute::NoReturn);
4147330f729Sjoerg     CI->removeAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
4157330f729Sjoerg   }
4167330f729Sjoerg 
4177330f729Sjoerg   IRBuilder<> IRB(C);
4187330f729Sjoerg   IRB.SetInsertPoint(CI);
4197330f729Sjoerg 
4207330f729Sjoerg   // Pre-invoke
4217330f729Sjoerg   // __THREW__ = 0;
422*82d56013Sjoerg   IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
4237330f729Sjoerg 
4247330f729Sjoerg   // Invoke function wrapper in JavaScript
4257330f729Sjoerg   SmallVector<Value *, 16> Args;
4267330f729Sjoerg   // Put the pointer to the callee as first argument, so it can be called
4277330f729Sjoerg   // within the invoke wrapper later
428*82d56013Sjoerg   Args.push_back(CI->getCalledOperand());
4297330f729Sjoerg   Args.append(CI->arg_begin(), CI->arg_end());
4307330f729Sjoerg   CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
4317330f729Sjoerg   NewCall->takeName(CI);
4327330f729Sjoerg   NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke);
4337330f729Sjoerg   NewCall->setDebugLoc(CI->getDebugLoc());
4347330f729Sjoerg 
4357330f729Sjoerg   // Because we added the pointer to the callee as first argument, all
4367330f729Sjoerg   // argument attribute indices have to be incremented by one.
4377330f729Sjoerg   SmallVector<AttributeSet, 8> ArgAttributes;
4387330f729Sjoerg   const AttributeList &InvokeAL = CI->getAttributes();
4397330f729Sjoerg 
4407330f729Sjoerg   // No attributes for the callee pointer.
4417330f729Sjoerg   ArgAttributes.push_back(AttributeSet());
4427330f729Sjoerg   // Copy the argument attributes from the original
4437330f729Sjoerg   for (unsigned I = 0, E = CI->getNumArgOperands(); I < E; ++I)
4447330f729Sjoerg     ArgAttributes.push_back(InvokeAL.getParamAttributes(I));
4457330f729Sjoerg 
4467330f729Sjoerg   AttrBuilder FnAttrs(InvokeAL.getFnAttributes());
4477330f729Sjoerg   if (FnAttrs.contains(Attribute::AllocSize)) {
4487330f729Sjoerg     // The allocsize attribute (if any) referes to parameters by index and needs
4497330f729Sjoerg     // to be adjusted.
4507330f729Sjoerg     unsigned SizeArg;
4517330f729Sjoerg     Optional<unsigned> NEltArg;
4527330f729Sjoerg     std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs();
4537330f729Sjoerg     SizeArg += 1;
4547330f729Sjoerg     if (NEltArg.hasValue())
4557330f729Sjoerg       NEltArg = NEltArg.getValue() + 1;
4567330f729Sjoerg     FnAttrs.addAllocSizeAttr(SizeArg, NEltArg);
4577330f729Sjoerg   }
4587330f729Sjoerg 
4597330f729Sjoerg   // Reconstruct the AttributesList based on the vector we constructed.
4607330f729Sjoerg   AttributeList NewCallAL =
4617330f729Sjoerg       AttributeList::get(C, AttributeSet::get(C, FnAttrs),
4627330f729Sjoerg                          InvokeAL.getRetAttributes(), ArgAttributes);
4637330f729Sjoerg   NewCall->setAttributes(NewCallAL);
4647330f729Sjoerg 
4657330f729Sjoerg   CI->replaceAllUsesWith(NewCall);
4667330f729Sjoerg 
4677330f729Sjoerg   // Post-invoke
4687330f729Sjoerg   // %__THREW__.val = __THREW__; __THREW__ = 0;
4697330f729Sjoerg   Value *Threw =
470*82d56013Sjoerg       IRB.CreateLoad(getAddrIntType(M), ThrewGV, ThrewGV->getName() + ".val");
471*82d56013Sjoerg   IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
4727330f729Sjoerg   return Threw;
4737330f729Sjoerg }
4747330f729Sjoerg 
4757330f729Sjoerg // Get matching invoke wrapper based on callee signature
getInvokeWrapper(CallBase * CI)476*82d56013Sjoerg Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallBase *CI) {
4777330f729Sjoerg   Module *M = CI->getModule();
4787330f729Sjoerg   SmallVector<Type *, 16> ArgTys;
479*82d56013Sjoerg   FunctionType *CalleeFTy = CI->getFunctionType();
4807330f729Sjoerg 
4817330f729Sjoerg   std::string Sig = getSignature(CalleeFTy);
4827330f729Sjoerg   if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
4837330f729Sjoerg     return InvokeWrappers[Sig];
4847330f729Sjoerg 
4857330f729Sjoerg   // Put the pointer to the callee as first argument
4867330f729Sjoerg   ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
4877330f729Sjoerg   // Add argument types
4887330f729Sjoerg   ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
4897330f729Sjoerg 
4907330f729Sjoerg   FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
4917330f729Sjoerg                                         CalleeFTy->isVarArg());
492*82d56013Sjoerg   Function *F = getEmscriptenFunction(FTy, "__invoke_" + Sig, M);
4937330f729Sjoerg   InvokeWrappers[Sig] = F;
4947330f729Sjoerg   return F;
4957330f729Sjoerg }
4967330f729Sjoerg 
canLongjmp(Module & M,const Value * Callee) const4977330f729Sjoerg bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(Module &M,
4987330f729Sjoerg                                                   const Value *Callee) const {
4997330f729Sjoerg   if (auto *CalleeF = dyn_cast<Function>(Callee))
5007330f729Sjoerg     if (CalleeF->isIntrinsic())
5017330f729Sjoerg       return false;
5027330f729Sjoerg 
5037330f729Sjoerg   // Attempting to transform inline assembly will result in something like:
5047330f729Sjoerg   //     call void @__invoke_void(void ()* asm ...)
5057330f729Sjoerg   // which is invalid because inline assembly blocks do not have addresses
5067330f729Sjoerg   // and can't be passed by pointer. The result is a crash with illegal IR.
5077330f729Sjoerg   if (isa<InlineAsm>(Callee))
5087330f729Sjoerg     return false;
5097330f729Sjoerg   StringRef CalleeName = Callee->getName();
5107330f729Sjoerg 
5117330f729Sjoerg   // The reason we include malloc/free here is to exclude the malloc/free
5127330f729Sjoerg   // calls generated in setjmp prep / cleanup routines.
5137330f729Sjoerg   if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free")
5147330f729Sjoerg     return false;
5157330f729Sjoerg 
516*82d56013Sjoerg   // There are functions in Emscripten's JS glue code or compiler-rt
5177330f729Sjoerg   if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" ||
5187330f729Sjoerg       CalleeName == "saveSetjmp" || CalleeName == "testSetjmp" ||
5197330f729Sjoerg       CalleeName == "getTempRet0" || CalleeName == "setTempRet0")
5207330f729Sjoerg     return false;
5217330f729Sjoerg 
5227330f729Sjoerg   // __cxa_find_matching_catch_N functions cannot longjmp
5237330f729Sjoerg   if (Callee->getName().startswith("__cxa_find_matching_catch_"))
5247330f729Sjoerg     return false;
5257330f729Sjoerg 
5267330f729Sjoerg   // Exception-catching related functions
5277330f729Sjoerg   if (CalleeName == "__cxa_begin_catch" || CalleeName == "__cxa_end_catch" ||
5287330f729Sjoerg       CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" ||
5297330f729Sjoerg       CalleeName == "__clang_call_terminate")
5307330f729Sjoerg     return false;
5317330f729Sjoerg 
5327330f729Sjoerg   // Otherwise we don't know
5337330f729Sjoerg   return true;
5347330f729Sjoerg }
5357330f729Sjoerg 
isEmAsmCall(Module & M,const Value * Callee) const5367330f729Sjoerg bool WebAssemblyLowerEmscriptenEHSjLj::isEmAsmCall(Module &M,
5377330f729Sjoerg                                                    const Value *Callee) const {
5387330f729Sjoerg   StringRef CalleeName = Callee->getName();
5397330f729Sjoerg   // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>.
5407330f729Sjoerg   return CalleeName == "emscripten_asm_const_int" ||
5417330f729Sjoerg          CalleeName == "emscripten_asm_const_double" ||
5427330f729Sjoerg          CalleeName == "emscripten_asm_const_int_sync_on_main_thread" ||
5437330f729Sjoerg          CalleeName == "emscripten_asm_const_double_sync_on_main_thread" ||
5447330f729Sjoerg          CalleeName == "emscripten_asm_const_async_on_main_thread";
5457330f729Sjoerg }
5467330f729Sjoerg 
5477330f729Sjoerg // Generate testSetjmp function call seqence with preamble and postamble.
5487330f729Sjoerg // The code this generates is equivalent to the following JavaScript code:
5497330f729Sjoerg // if (%__THREW__.val != 0 & threwValue != 0) {
5507330f729Sjoerg //   %label = _testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
5517330f729Sjoerg //   if (%label == 0)
5527330f729Sjoerg //     emscripten_longjmp(%__THREW__.val, threwValue);
5537330f729Sjoerg //   setTempRet0(threwValue);
5547330f729Sjoerg // } else {
5557330f729Sjoerg //   %label = -1;
5567330f729Sjoerg // }
5577330f729Sjoerg // %longjmp_result = getTempRet0();
5587330f729Sjoerg //
5597330f729Sjoerg // As output parameters. returns %label, %longjmp_result, and the BB the last
5607330f729Sjoerg // instruction (%longjmp_result = ...) is in.
wrapTestSetjmp(BasicBlock * BB,DebugLoc DL,Value * Threw,Value * SetjmpTable,Value * SetjmpTableSize,Value * & Label,Value * & LongjmpResult,BasicBlock * & EndBB)5617330f729Sjoerg void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
562*82d56013Sjoerg     BasicBlock *BB, DebugLoc DL, Value *Threw, Value *SetjmpTable,
5637330f729Sjoerg     Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
5647330f729Sjoerg     BasicBlock *&EndBB) {
5657330f729Sjoerg   Function *F = BB->getParent();
566*82d56013Sjoerg   Module *M = F->getParent();
567*82d56013Sjoerg   LLVMContext &C = M->getContext();
5687330f729Sjoerg   IRBuilder<> IRB(C);
569*82d56013Sjoerg   IRB.SetCurrentDebugLocation(DL);
5707330f729Sjoerg 
5717330f729Sjoerg   // if (%__THREW__.val != 0 & threwValue != 0)
5727330f729Sjoerg   IRB.SetInsertPoint(BB);
5737330f729Sjoerg   BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
5747330f729Sjoerg   BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
5757330f729Sjoerg   BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
576*82d56013Sjoerg   Value *ThrewCmp = IRB.CreateICmpNE(Threw, getAddrSizeInt(M, 0));
5777330f729Sjoerg   Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
5787330f729Sjoerg                                      ThrewValueGV->getName() + ".val");
5797330f729Sjoerg   Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
5807330f729Sjoerg   Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
5817330f729Sjoerg   IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
5827330f729Sjoerg 
5837330f729Sjoerg   // %label = _testSetjmp(mem[%__THREW__.val], _setjmpTable, _setjmpTableSize);
5847330f729Sjoerg   // if (%label == 0)
5857330f729Sjoerg   IRB.SetInsertPoint(ThenBB1);
5867330f729Sjoerg   BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F);
5877330f729Sjoerg   BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
588*82d56013Sjoerg   Value *ThrewPtr =
589*82d56013Sjoerg       IRB.CreateIntToPtr(Threw, getAddrPtrType(M), Threw->getName() + ".p");
590*82d56013Sjoerg   Value *LoadedThrew = IRB.CreateLoad(getAddrIntType(M), ThrewPtr,
591*82d56013Sjoerg                                       ThrewPtr->getName() + ".loaded");
5927330f729Sjoerg   Value *ThenLabel = IRB.CreateCall(
5937330f729Sjoerg       TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
5947330f729Sjoerg   Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
5957330f729Sjoerg   IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2);
5967330f729Sjoerg 
5977330f729Sjoerg   // emscripten_longjmp(%__THREW__.val, threwValue);
5987330f729Sjoerg   IRB.SetInsertPoint(ThenBB2);
5997330f729Sjoerg   IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue});
6007330f729Sjoerg   IRB.CreateUnreachable();
6017330f729Sjoerg 
6027330f729Sjoerg   // setTempRet0(threwValue);
6037330f729Sjoerg   IRB.SetInsertPoint(EndBB2);
6047330f729Sjoerg   IRB.CreateCall(SetTempRet0Func, ThrewValue);
6057330f729Sjoerg   IRB.CreateBr(EndBB1);
6067330f729Sjoerg 
6077330f729Sjoerg   IRB.SetInsertPoint(ElseBB1);
6087330f729Sjoerg   IRB.CreateBr(EndBB1);
6097330f729Sjoerg 
6107330f729Sjoerg   // longjmp_result = getTempRet0();
6117330f729Sjoerg   IRB.SetInsertPoint(EndBB1);
6127330f729Sjoerg   PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
6137330f729Sjoerg   LabelPHI->addIncoming(ThenLabel, EndBB2);
6147330f729Sjoerg 
6157330f729Sjoerg   LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
6167330f729Sjoerg 
6177330f729Sjoerg   // Output parameter assignment
6187330f729Sjoerg   Label = LabelPHI;
6197330f729Sjoerg   EndBB = EndBB1;
6207330f729Sjoerg   LongjmpResult = IRB.CreateCall(GetTempRet0Func, None, "longjmp_result");
6217330f729Sjoerg }
6227330f729Sjoerg 
rebuildSSA(Function & F)6237330f729Sjoerg void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
6247330f729Sjoerg   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
6257330f729Sjoerg   DT.recalculate(F); // CFG has been changed
6267330f729Sjoerg   SSAUpdater SSA;
6277330f729Sjoerg   for (BasicBlock &BB : F) {
6287330f729Sjoerg     for (Instruction &I : BB) {
6297330f729Sjoerg       SSA.Initialize(I.getType(), I.getName());
6307330f729Sjoerg       SSA.AddAvailableValue(&BB, &I);
6317330f729Sjoerg       for (auto UI = I.use_begin(), UE = I.use_end(); UI != UE;) {
6327330f729Sjoerg         Use &U = *UI;
6337330f729Sjoerg         ++UI;
6347330f729Sjoerg         auto *User = cast<Instruction>(U.getUser());
6357330f729Sjoerg         if (auto *UserPN = dyn_cast<PHINode>(User))
6367330f729Sjoerg           if (UserPN->getIncomingBlock(U) == &BB)
6377330f729Sjoerg             continue;
6387330f729Sjoerg 
6397330f729Sjoerg         if (DT.dominates(&I, User))
6407330f729Sjoerg           continue;
6417330f729Sjoerg         SSA.RewriteUseAfterInsertions(U);
6427330f729Sjoerg       }
6437330f729Sjoerg     }
6447330f729Sjoerg   }
6457330f729Sjoerg }
6467330f729Sjoerg 
647*82d56013Sjoerg // Replace uses of longjmp with emscripten_longjmp. emscripten_longjmp takes
648*82d56013Sjoerg // arguments of type {i32, i32} (wasm32) / {i64, i32} (wasm64) and longjmp takes
649*82d56013Sjoerg // {jmp_buf*, i32}, so we need a ptrtoint instruction here to make the type
650*82d56013Sjoerg // match. jmp_buf* will eventually be lowered to i32 in the wasm backend.
replaceLongjmpWithEmscriptenLongjmp(Function * LongjmpF,Function * EmLongjmpF)651*82d56013Sjoerg static void replaceLongjmpWithEmscriptenLongjmp(Function *LongjmpF,
652*82d56013Sjoerg                                                 Function *EmLongjmpF) {
653*82d56013Sjoerg   Module *M = LongjmpF->getParent();
654*82d56013Sjoerg   SmallVector<CallInst *, 8> ToErase;
655*82d56013Sjoerg   LLVMContext &C = LongjmpF->getParent()->getContext();
656*82d56013Sjoerg   IRBuilder<> IRB(C);
657*82d56013Sjoerg 
658*82d56013Sjoerg   // For calls to longjmp, replace it with emscripten_longjmp and cast its first
659*82d56013Sjoerg   // argument (jmp_buf*) to int
660*82d56013Sjoerg   for (User *U : LongjmpF->users()) {
661*82d56013Sjoerg     auto *CI = dyn_cast<CallInst>(U);
662*82d56013Sjoerg     if (CI && CI->getCalledFunction() == LongjmpF) {
663*82d56013Sjoerg       IRB.SetInsertPoint(CI);
664*82d56013Sjoerg       Value *Jmpbuf =
665*82d56013Sjoerg           IRB.CreatePtrToInt(CI->getArgOperand(0), getAddrIntType(M), "jmpbuf");
666*82d56013Sjoerg       IRB.CreateCall(EmLongjmpF, {Jmpbuf, CI->getArgOperand(1)});
667*82d56013Sjoerg       ToErase.push_back(CI);
668*82d56013Sjoerg     }
669*82d56013Sjoerg   }
670*82d56013Sjoerg   for (auto *I : ToErase)
671*82d56013Sjoerg     I->eraseFromParent();
672*82d56013Sjoerg 
673*82d56013Sjoerg   // If we have any remaining uses of longjmp's function pointer, replace it
674*82d56013Sjoerg   // with (int(*)(jmp_buf*, int))emscripten_longjmp.
675*82d56013Sjoerg   if (!LongjmpF->uses().empty()) {
676*82d56013Sjoerg     Value *EmLongjmp =
677*82d56013Sjoerg         IRB.CreateBitCast(EmLongjmpF, LongjmpF->getType(), "em_longjmp");
678*82d56013Sjoerg     LongjmpF->replaceAllUsesWith(EmLongjmp);
679*82d56013Sjoerg   }
680*82d56013Sjoerg }
681*82d56013Sjoerg 
runOnModule(Module & M)6827330f729Sjoerg bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
6837330f729Sjoerg   LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
6847330f729Sjoerg 
6857330f729Sjoerg   LLVMContext &C = M.getContext();
6867330f729Sjoerg   IRBuilder<> IRB(C);
6877330f729Sjoerg 
6887330f729Sjoerg   Function *SetjmpF = M.getFunction("setjmp");
6897330f729Sjoerg   Function *LongjmpF = M.getFunction("longjmp");
6907330f729Sjoerg   bool SetjmpUsed = SetjmpF && !SetjmpF->use_empty();
6917330f729Sjoerg   bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
6927330f729Sjoerg   bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed);
6937330f729Sjoerg 
694*82d56013Sjoerg   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
695*82d56013Sjoerg   assert(TPC && "Expected a TargetPassConfig");
696*82d56013Sjoerg   auto &TM = TPC->getTM<WebAssemblyTargetMachine>();
697*82d56013Sjoerg 
698*82d56013Sjoerg   if (EnableEH && TM.Options.ExceptionModel == ExceptionHandling::Wasm)
699*82d56013Sjoerg     report_fatal_error("-exception-model=wasm not allowed with "
700*82d56013Sjoerg                        "-enable-emscripten-cxx-exceptions");
701*82d56013Sjoerg 
7027330f729Sjoerg   // Declare (or get) global variables __THREW__, __threwValue, and
7037330f729Sjoerg   // getTempRet0/setTempRet0 function which are used in common for both
7047330f729Sjoerg   // exception handling and setjmp/longjmp handling
705*82d56013Sjoerg   ThrewGV = getGlobalVariable(M, getAddrIntType(&M), TM, "__THREW__");
706*82d56013Sjoerg   ThrewValueGV = getGlobalVariable(M, IRB.getInt32Ty(), TM, "__threwValue");
707*82d56013Sjoerg   GetTempRet0Func = getEmscriptenFunction(
708*82d56013Sjoerg       FunctionType::get(IRB.getInt32Ty(), false), "getTempRet0", &M);
709*82d56013Sjoerg   SetTempRet0Func = getEmscriptenFunction(
7107330f729Sjoerg       FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
711*82d56013Sjoerg       "setTempRet0", &M);
7127330f729Sjoerg   GetTempRet0Func->setDoesNotThrow();
7137330f729Sjoerg   SetTempRet0Func->setDoesNotThrow();
7147330f729Sjoerg 
7157330f729Sjoerg   bool Changed = false;
7167330f729Sjoerg 
7177330f729Sjoerg   // Exception handling
7187330f729Sjoerg   if (EnableEH) {
7197330f729Sjoerg     // Register __resumeException function
7207330f729Sjoerg     FunctionType *ResumeFTy =
7217330f729Sjoerg         FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
722*82d56013Sjoerg     ResumeF = getEmscriptenFunction(ResumeFTy, "__resumeException", &M);
7237330f729Sjoerg 
7247330f729Sjoerg     // Register llvm_eh_typeid_for function
7257330f729Sjoerg     FunctionType *EHTypeIDTy =
7267330f729Sjoerg         FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
727*82d56013Sjoerg     EHTypeIDF = getEmscriptenFunction(EHTypeIDTy, "llvm_eh_typeid_for", &M);
7287330f729Sjoerg 
7297330f729Sjoerg     for (Function &F : M) {
7307330f729Sjoerg       if (F.isDeclaration())
7317330f729Sjoerg         continue;
7327330f729Sjoerg       Changed |= runEHOnFunction(F);
7337330f729Sjoerg     }
7347330f729Sjoerg   }
7357330f729Sjoerg 
7367330f729Sjoerg   // Setjmp/longjmp handling
7377330f729Sjoerg   if (DoSjLj) {
7387330f729Sjoerg     Changed = true; // We have setjmp or longjmp somewhere
7397330f729Sjoerg 
740*82d56013Sjoerg     // Register emscripten_longjmp function
741*82d56013Sjoerg     FunctionType *FTy = FunctionType::get(
742*82d56013Sjoerg         IRB.getVoidTy(), {getAddrIntType(&M), IRB.getInt32Ty()}, false);
743*82d56013Sjoerg     EmLongjmpF = getEmscriptenFunction(FTy, "emscripten_longjmp", &M);
7447330f729Sjoerg 
745*82d56013Sjoerg     if (LongjmpF)
746*82d56013Sjoerg       replaceLongjmpWithEmscriptenLongjmp(LongjmpF, EmLongjmpF);
7477330f729Sjoerg 
7487330f729Sjoerg     if (SetjmpF) {
7497330f729Sjoerg       // Register saveSetjmp function
7507330f729Sjoerg       FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
751*82d56013Sjoerg       FTy = FunctionType::get(Type::getInt32PtrTy(C),
752*82d56013Sjoerg                               {SetjmpFTy->getParamType(0), IRB.getInt32Ty(),
753*82d56013Sjoerg                                Type::getInt32PtrTy(C), IRB.getInt32Ty()},
754*82d56013Sjoerg                               false);
755*82d56013Sjoerg       SaveSetjmpF = getEmscriptenFunction(FTy, "saveSetjmp", &M);
7567330f729Sjoerg 
7577330f729Sjoerg       // Register testSetjmp function
758*82d56013Sjoerg       FTy = FunctionType::get(
759*82d56013Sjoerg           IRB.getInt32Ty(),
760*82d56013Sjoerg           {getAddrIntType(&M), Type::getInt32PtrTy(C), IRB.getInt32Ty()},
761*82d56013Sjoerg           false);
762*82d56013Sjoerg       TestSetjmpF = getEmscriptenFunction(FTy, "testSetjmp", &M);
7637330f729Sjoerg 
7647330f729Sjoerg       // Only traverse functions that uses setjmp in order not to insert
7657330f729Sjoerg       // unnecessary prep / cleanup code in every function
7667330f729Sjoerg       SmallPtrSet<Function *, 8> SetjmpUsers;
7677330f729Sjoerg       for (User *U : SetjmpF->users()) {
7687330f729Sjoerg         auto *UI = cast<Instruction>(U);
7697330f729Sjoerg         SetjmpUsers.insert(UI->getFunction());
7707330f729Sjoerg       }
7717330f729Sjoerg       for (Function *F : SetjmpUsers)
7727330f729Sjoerg         runSjLjOnFunction(*F);
7737330f729Sjoerg     }
7747330f729Sjoerg   }
7757330f729Sjoerg 
7767330f729Sjoerg   if (!Changed) {
7777330f729Sjoerg     // Delete unused global variables and functions
7787330f729Sjoerg     if (ResumeF)
7797330f729Sjoerg       ResumeF->eraseFromParent();
7807330f729Sjoerg     if (EHTypeIDF)
7817330f729Sjoerg       EHTypeIDF->eraseFromParent();
7827330f729Sjoerg     if (EmLongjmpF)
7837330f729Sjoerg       EmLongjmpF->eraseFromParent();
7847330f729Sjoerg     if (SaveSetjmpF)
7857330f729Sjoerg       SaveSetjmpF->eraseFromParent();
7867330f729Sjoerg     if (TestSetjmpF)
7877330f729Sjoerg       TestSetjmpF->eraseFromParent();
7887330f729Sjoerg     return false;
7897330f729Sjoerg   }
7907330f729Sjoerg 
7917330f729Sjoerg   return true;
7927330f729Sjoerg }
7937330f729Sjoerg 
runEHOnFunction(Function & F)7947330f729Sjoerg bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
7957330f729Sjoerg   Module &M = *F.getParent();
7967330f729Sjoerg   LLVMContext &C = F.getContext();
7977330f729Sjoerg   IRBuilder<> IRB(C);
7987330f729Sjoerg   bool Changed = false;
7997330f729Sjoerg   SmallVector<Instruction *, 64> ToErase;
8007330f729Sjoerg   SmallPtrSet<LandingPadInst *, 32> LandingPads;
801*82d56013Sjoerg   bool AllowExceptions = areAllExceptionsAllowed() ||
802*82d56013Sjoerg                          EHAllowlistSet.count(std::string(F.getName()));
8037330f729Sjoerg 
8047330f729Sjoerg   for (BasicBlock &BB : F) {
8057330f729Sjoerg     auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
8067330f729Sjoerg     if (!II)
8077330f729Sjoerg       continue;
8087330f729Sjoerg     Changed = true;
8097330f729Sjoerg     LandingPads.insert(II->getLandingPadInst());
8107330f729Sjoerg     IRB.SetInsertPoint(II);
8117330f729Sjoerg 
812*82d56013Sjoerg     bool NeedInvoke = AllowExceptions && canThrow(II->getCalledOperand());
8137330f729Sjoerg     if (NeedInvoke) {
8147330f729Sjoerg       // Wrap invoke with invoke wrapper and generate preamble/postamble
8157330f729Sjoerg       Value *Threw = wrapInvoke(II);
8167330f729Sjoerg       ToErase.push_back(II);
8177330f729Sjoerg 
8187330f729Sjoerg       // Insert a branch based on __THREW__ variable
819*82d56013Sjoerg       Value *Cmp = IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp");
8207330f729Sjoerg       IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
8217330f729Sjoerg 
8227330f729Sjoerg     } else {
8237330f729Sjoerg       // This can't throw, and we don't need this invoke, just replace it with a
8247330f729Sjoerg       // call+branch
825*82d56013Sjoerg       SmallVector<Value *, 16> Args(II->args());
8267330f729Sjoerg       CallInst *NewCall =
827*82d56013Sjoerg           IRB.CreateCall(II->getFunctionType(), II->getCalledOperand(), Args);
8287330f729Sjoerg       NewCall->takeName(II);
8297330f729Sjoerg       NewCall->setCallingConv(II->getCallingConv());
8307330f729Sjoerg       NewCall->setDebugLoc(II->getDebugLoc());
8317330f729Sjoerg       NewCall->setAttributes(II->getAttributes());
8327330f729Sjoerg       II->replaceAllUsesWith(NewCall);
8337330f729Sjoerg       ToErase.push_back(II);
8347330f729Sjoerg 
8357330f729Sjoerg       IRB.CreateBr(II->getNormalDest());
8367330f729Sjoerg 
8377330f729Sjoerg       // Remove any PHI node entries from the exception destination
8387330f729Sjoerg       II->getUnwindDest()->removePredecessor(&BB);
8397330f729Sjoerg     }
8407330f729Sjoerg   }
8417330f729Sjoerg 
8427330f729Sjoerg   // Process resume instructions
8437330f729Sjoerg   for (BasicBlock &BB : F) {
8447330f729Sjoerg     // Scan the body of the basic block for resumes
8457330f729Sjoerg     for (Instruction &I : BB) {
8467330f729Sjoerg       auto *RI = dyn_cast<ResumeInst>(&I);
8477330f729Sjoerg       if (!RI)
8487330f729Sjoerg         continue;
849*82d56013Sjoerg       Changed = true;
8507330f729Sjoerg 
8517330f729Sjoerg       // Split the input into legal values
8527330f729Sjoerg       Value *Input = RI->getValue();
8537330f729Sjoerg       IRB.SetInsertPoint(RI);
8547330f729Sjoerg       Value *Low = IRB.CreateExtractValue(Input, 0, "low");
8557330f729Sjoerg       // Create a call to __resumeException function
8567330f729Sjoerg       IRB.CreateCall(ResumeF, {Low});
8577330f729Sjoerg       // Add a terminator to the block
8587330f729Sjoerg       IRB.CreateUnreachable();
8597330f729Sjoerg       ToErase.push_back(RI);
8607330f729Sjoerg     }
8617330f729Sjoerg   }
8627330f729Sjoerg 
8637330f729Sjoerg   // Process llvm.eh.typeid.for intrinsics
8647330f729Sjoerg   for (BasicBlock &BB : F) {
8657330f729Sjoerg     for (Instruction &I : BB) {
8667330f729Sjoerg       auto *CI = dyn_cast<CallInst>(&I);
8677330f729Sjoerg       if (!CI)
8687330f729Sjoerg         continue;
8697330f729Sjoerg       const Function *Callee = CI->getCalledFunction();
8707330f729Sjoerg       if (!Callee)
8717330f729Sjoerg         continue;
8727330f729Sjoerg       if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
8737330f729Sjoerg         continue;
874*82d56013Sjoerg       Changed = true;
8757330f729Sjoerg 
8767330f729Sjoerg       IRB.SetInsertPoint(CI);
8777330f729Sjoerg       CallInst *NewCI =
8787330f729Sjoerg           IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
8797330f729Sjoerg       CI->replaceAllUsesWith(NewCI);
8807330f729Sjoerg       ToErase.push_back(CI);
8817330f729Sjoerg     }
8827330f729Sjoerg   }
8837330f729Sjoerg 
8847330f729Sjoerg   // Look for orphan landingpads, can occur in blocks with no predecessors
8857330f729Sjoerg   for (BasicBlock &BB : F) {
8867330f729Sjoerg     Instruction *I = BB.getFirstNonPHI();
8877330f729Sjoerg     if (auto *LPI = dyn_cast<LandingPadInst>(I))
8887330f729Sjoerg       LandingPads.insert(LPI);
8897330f729Sjoerg   }
890*82d56013Sjoerg   Changed |= !LandingPads.empty();
8917330f729Sjoerg 
8927330f729Sjoerg   // Handle all the landingpad for this function together, as multiple invokes
8937330f729Sjoerg   // may share a single lp
8947330f729Sjoerg   for (LandingPadInst *LPI : LandingPads) {
8957330f729Sjoerg     IRB.SetInsertPoint(LPI);
8967330f729Sjoerg     SmallVector<Value *, 16> FMCArgs;
8977330f729Sjoerg     for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
8987330f729Sjoerg       Constant *Clause = LPI->getClause(I);
899*82d56013Sjoerg       // TODO Handle filters (= exception specifications).
900*82d56013Sjoerg       // https://bugs.llvm.org/show_bug.cgi?id=50396
901*82d56013Sjoerg       if (LPI->isCatch(I))
9027330f729Sjoerg         FMCArgs.push_back(Clause);
9037330f729Sjoerg     }
9047330f729Sjoerg 
9057330f729Sjoerg     // Create a call to __cxa_find_matching_catch_N function
9067330f729Sjoerg     Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
9077330f729Sjoerg     CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
9087330f729Sjoerg     Value *Undef = UndefValue::get(LPI->getType());
9097330f729Sjoerg     Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
9107330f729Sjoerg     Value *TempRet0 = IRB.CreateCall(GetTempRet0Func, None, "tempret0");
9117330f729Sjoerg     Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
9127330f729Sjoerg 
9137330f729Sjoerg     LPI->replaceAllUsesWith(Pair1);
9147330f729Sjoerg     ToErase.push_back(LPI);
9157330f729Sjoerg   }
9167330f729Sjoerg 
9177330f729Sjoerg   // Erase everything we no longer need in this function
9187330f729Sjoerg   for (Instruction *I : ToErase)
9197330f729Sjoerg     I->eraseFromParent();
9207330f729Sjoerg 
9217330f729Sjoerg   return Changed;
9227330f729Sjoerg }
9237330f729Sjoerg 
924*82d56013Sjoerg // This tries to get debug info from the instruction before which a new
925*82d56013Sjoerg // instruction will be inserted, and if there's no debug info in that
926*82d56013Sjoerg // instruction, tries to get the info instead from the previous instruction (if
927*82d56013Sjoerg // any). If none of these has debug info and a DISubprogram is provided, it
928*82d56013Sjoerg // creates a dummy debug info with the first line of the function, because IR
929*82d56013Sjoerg // verifier requires all inlinable callsites should have debug info when both a
930*82d56013Sjoerg // caller and callee have DISubprogram. If none of these conditions are met,
931*82d56013Sjoerg // returns empty info.
getOrCreateDebugLoc(const Instruction * InsertBefore,DISubprogram * SP)932*82d56013Sjoerg static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore,
933*82d56013Sjoerg                                     DISubprogram *SP) {
934*82d56013Sjoerg   assert(InsertBefore);
935*82d56013Sjoerg   if (InsertBefore->getDebugLoc())
936*82d56013Sjoerg     return InsertBefore->getDebugLoc();
937*82d56013Sjoerg   const Instruction *Prev = InsertBefore->getPrevNode();
938*82d56013Sjoerg   if (Prev && Prev->getDebugLoc())
939*82d56013Sjoerg     return Prev->getDebugLoc();
940*82d56013Sjoerg   if (SP)
941*82d56013Sjoerg     return DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
942*82d56013Sjoerg   return DebugLoc();
943*82d56013Sjoerg }
944*82d56013Sjoerg 
runSjLjOnFunction(Function & F)9457330f729Sjoerg bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
9467330f729Sjoerg   Module &M = *F.getParent();
9477330f729Sjoerg   LLVMContext &C = F.getContext();
9487330f729Sjoerg   IRBuilder<> IRB(C);
9497330f729Sjoerg   SmallVector<Instruction *, 64> ToErase;
9507330f729Sjoerg   // Vector of %setjmpTable values
9517330f729Sjoerg   std::vector<Instruction *> SetjmpTableInsts;
9527330f729Sjoerg   // Vector of %setjmpTableSize values
9537330f729Sjoerg   std::vector<Instruction *> SetjmpTableSizeInsts;
9547330f729Sjoerg 
9557330f729Sjoerg   // Setjmp preparation
9567330f729Sjoerg 
9577330f729Sjoerg   // This instruction effectively means %setjmpTableSize = 4.
9587330f729Sjoerg   // We create this as an instruction intentionally, and we don't want to fold
9597330f729Sjoerg   // this instruction to a constant 4, because this value will be used in
9607330f729Sjoerg   // SSAUpdater.AddAvailableValue(...) later.
9617330f729Sjoerg   BasicBlock &EntryBB = F.getEntryBlock();
962*82d56013Sjoerg   DebugLoc FirstDL = getOrCreateDebugLoc(&*EntryBB.begin(), F.getSubprogram());
9637330f729Sjoerg   BinaryOperator *SetjmpTableSize = BinaryOperator::Create(
9647330f729Sjoerg       Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize",
9657330f729Sjoerg       &*EntryBB.getFirstInsertionPt());
966*82d56013Sjoerg   SetjmpTableSize->setDebugLoc(FirstDL);
9677330f729Sjoerg   // setjmpTable = (int *) malloc(40);
9687330f729Sjoerg   Instruction *SetjmpTable = CallInst::CreateMalloc(
9697330f729Sjoerg       SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
9707330f729Sjoerg       nullptr, nullptr, "setjmpTable");
971*82d56013Sjoerg   SetjmpTable->setDebugLoc(FirstDL);
972*82d56013Sjoerg   // CallInst::CreateMalloc may return a bitcast instruction if the result types
973*82d56013Sjoerg   // mismatch. We need to set the debug loc for the original call too.
974*82d56013Sjoerg   auto *MallocCall = SetjmpTable->stripPointerCasts();
975*82d56013Sjoerg   if (auto *MallocCallI = dyn_cast<Instruction>(MallocCall)) {
976*82d56013Sjoerg     MallocCallI->setDebugLoc(FirstDL);
977*82d56013Sjoerg   }
9787330f729Sjoerg   // setjmpTable[0] = 0;
9797330f729Sjoerg   IRB.SetInsertPoint(SetjmpTableSize);
9807330f729Sjoerg   IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
9817330f729Sjoerg   SetjmpTableInsts.push_back(SetjmpTable);
9827330f729Sjoerg   SetjmpTableSizeInsts.push_back(SetjmpTableSize);
9837330f729Sjoerg 
9847330f729Sjoerg   // Setjmp transformation
9857330f729Sjoerg   std::vector<PHINode *> SetjmpRetPHIs;
9867330f729Sjoerg   Function *SetjmpF = M.getFunction("setjmp");
9877330f729Sjoerg   for (User *U : SetjmpF->users()) {
9887330f729Sjoerg     auto *CI = dyn_cast<CallInst>(U);
9897330f729Sjoerg     if (!CI)
9907330f729Sjoerg       report_fatal_error("Does not support indirect calls to setjmp");
9917330f729Sjoerg 
9927330f729Sjoerg     BasicBlock *BB = CI->getParent();
9937330f729Sjoerg     if (BB->getParent() != &F) // in other function
9947330f729Sjoerg       continue;
9957330f729Sjoerg 
9967330f729Sjoerg     // The tail is everything right after the call, and will be reached once
9977330f729Sjoerg     // when setjmp is called, and later when longjmp returns to the setjmp
9987330f729Sjoerg     BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
9997330f729Sjoerg     // Add a phi to the tail, which will be the output of setjmp, which
10007330f729Sjoerg     // indicates if this is the first call or a longjmp back. The phi directly
10017330f729Sjoerg     // uses the right value based on where we arrive from
10027330f729Sjoerg     IRB.SetInsertPoint(Tail->getFirstNonPHI());
10037330f729Sjoerg     PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
10047330f729Sjoerg 
10057330f729Sjoerg     // setjmp initial call returns 0
10067330f729Sjoerg     SetjmpRet->addIncoming(IRB.getInt32(0), BB);
10077330f729Sjoerg     // The proper output is now this, not the setjmp call itself
10087330f729Sjoerg     CI->replaceAllUsesWith(SetjmpRet);
10097330f729Sjoerg     // longjmp returns to the setjmp will add themselves to this phi
10107330f729Sjoerg     SetjmpRetPHIs.push_back(SetjmpRet);
10117330f729Sjoerg 
10127330f729Sjoerg     // Fix call target
10137330f729Sjoerg     // Our index in the function is our place in the array + 1 to avoid index
10147330f729Sjoerg     // 0, because index 0 means the longjmp is not ours to handle.
10157330f729Sjoerg     IRB.SetInsertPoint(CI);
10167330f729Sjoerg     Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
10177330f729Sjoerg                      SetjmpTable, SetjmpTableSize};
10187330f729Sjoerg     Instruction *NewSetjmpTable =
10197330f729Sjoerg         IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
10207330f729Sjoerg     Instruction *NewSetjmpTableSize =
10217330f729Sjoerg         IRB.CreateCall(GetTempRet0Func, None, "setjmpTableSize");
10227330f729Sjoerg     SetjmpTableInsts.push_back(NewSetjmpTable);
10237330f729Sjoerg     SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
10247330f729Sjoerg     ToErase.push_back(CI);
10257330f729Sjoerg   }
10267330f729Sjoerg 
10277330f729Sjoerg   // Update each call that can longjmp so it can return to a setjmp where
10287330f729Sjoerg   // relevant.
10297330f729Sjoerg 
10307330f729Sjoerg   // Because we are creating new BBs while processing and don't want to make
10317330f729Sjoerg   // all these newly created BBs candidates again for longjmp processing, we
10327330f729Sjoerg   // first make the vector of candidate BBs.
10337330f729Sjoerg   std::vector<BasicBlock *> BBs;
10347330f729Sjoerg   for (BasicBlock &BB : F)
10357330f729Sjoerg     BBs.push_back(&BB);
10367330f729Sjoerg 
10377330f729Sjoerg   // BBs.size() will change within the loop, so we query it every time
10387330f729Sjoerg   for (unsigned I = 0; I < BBs.size(); I++) {
10397330f729Sjoerg     BasicBlock *BB = BBs[I];
10407330f729Sjoerg     for (Instruction &I : *BB) {
10417330f729Sjoerg       assert(!isa<InvokeInst>(&I));
10427330f729Sjoerg       auto *CI = dyn_cast<CallInst>(&I);
10437330f729Sjoerg       if (!CI)
10447330f729Sjoerg         continue;
10457330f729Sjoerg 
1046*82d56013Sjoerg       const Value *Callee = CI->getCalledOperand();
10477330f729Sjoerg       if (!canLongjmp(M, Callee))
10487330f729Sjoerg         continue;
10497330f729Sjoerg       if (isEmAsmCall(M, Callee))
10507330f729Sjoerg         report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
10517330f729Sjoerg                                F.getName() +
10527330f729Sjoerg                                ". Please consider using EM_JS, or move the "
10537330f729Sjoerg                                "EM_ASM into another function.",
10547330f729Sjoerg                            false);
10557330f729Sjoerg 
10567330f729Sjoerg       Value *Threw = nullptr;
10577330f729Sjoerg       BasicBlock *Tail;
10587330f729Sjoerg       if (Callee->getName().startswith("__invoke_")) {
10597330f729Sjoerg         // If invoke wrapper has already been generated for this call in
10607330f729Sjoerg         // previous EH phase, search for the load instruction
10617330f729Sjoerg         // %__THREW__.val = __THREW__;
10627330f729Sjoerg         // in postamble after the invoke wrapper call
10637330f729Sjoerg         LoadInst *ThrewLI = nullptr;
10647330f729Sjoerg         StoreInst *ThrewResetSI = nullptr;
10657330f729Sjoerg         for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
10667330f729Sjoerg              I != IE; ++I) {
10677330f729Sjoerg           if (auto *LI = dyn_cast<LoadInst>(I))
10687330f729Sjoerg             if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
10697330f729Sjoerg               if (GV == ThrewGV) {
10707330f729Sjoerg                 Threw = ThrewLI = LI;
10717330f729Sjoerg                 break;
10727330f729Sjoerg               }
10737330f729Sjoerg         }
10747330f729Sjoerg         // Search for the store instruction after the load above
10757330f729Sjoerg         // __THREW__ = 0;
10767330f729Sjoerg         for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
10777330f729Sjoerg              I != IE; ++I) {
1078*82d56013Sjoerg           if (auto *SI = dyn_cast<StoreInst>(I)) {
1079*82d56013Sjoerg             if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) {
1080*82d56013Sjoerg               if (GV == ThrewGV &&
1081*82d56013Sjoerg                   SI->getValueOperand() == getAddrSizeInt(&M, 0)) {
10827330f729Sjoerg                 ThrewResetSI = SI;
10837330f729Sjoerg                 break;
10847330f729Sjoerg               }
10857330f729Sjoerg             }
1086*82d56013Sjoerg           }
1087*82d56013Sjoerg         }
10887330f729Sjoerg         assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
10897330f729Sjoerg         assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
10907330f729Sjoerg         Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
10917330f729Sjoerg 
10927330f729Sjoerg       } else {
10937330f729Sjoerg         // Wrap call with invoke wrapper and generate preamble/postamble
10947330f729Sjoerg         Threw = wrapInvoke(CI);
10957330f729Sjoerg         ToErase.push_back(CI);
10967330f729Sjoerg         Tail = SplitBlock(BB, CI->getNextNode());
10977330f729Sjoerg       }
10987330f729Sjoerg 
10997330f729Sjoerg       // We need to replace the terminator in Tail - SplitBlock makes BB go
11007330f729Sjoerg       // straight to Tail, we need to check if a longjmp occurred, and go to the
11017330f729Sjoerg       // right setjmp-tail if so
11027330f729Sjoerg       ToErase.push_back(BB->getTerminator());
11037330f729Sjoerg 
11047330f729Sjoerg       // Generate a function call to testSetjmp function and preamble/postamble
11057330f729Sjoerg       // code to figure out (1) whether longjmp occurred (2) if longjmp
11067330f729Sjoerg       // occurred, which setjmp it corresponds to
11077330f729Sjoerg       Value *Label = nullptr;
11087330f729Sjoerg       Value *LongjmpResult = nullptr;
11097330f729Sjoerg       BasicBlock *EndBB = nullptr;
1110*82d56013Sjoerg       wrapTestSetjmp(BB, CI->getDebugLoc(), Threw, SetjmpTable, SetjmpTableSize,
1111*82d56013Sjoerg                      Label, LongjmpResult, EndBB);
11127330f729Sjoerg       assert(Label && LongjmpResult && EndBB);
11137330f729Sjoerg 
11147330f729Sjoerg       // Create switch instruction
11157330f729Sjoerg       IRB.SetInsertPoint(EndBB);
1116*82d56013Sjoerg       IRB.SetCurrentDebugLocation(EndBB->getInstList().back().getDebugLoc());
11177330f729Sjoerg       SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
11187330f729Sjoerg       // -1 means no longjmp happened, continue normally (will hit the default
11197330f729Sjoerg       // switch case). 0 means a longjmp that is not ours to handle, needs a
11207330f729Sjoerg       // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
11217330f729Sjoerg       // 0).
11227330f729Sjoerg       for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
11237330f729Sjoerg         SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
11247330f729Sjoerg         SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB);
11257330f729Sjoerg       }
11267330f729Sjoerg 
11277330f729Sjoerg       // We are splitting the block here, and must continue to find other calls
11287330f729Sjoerg       // in the block - which is now split. so continue to traverse in the Tail
11297330f729Sjoerg       BBs.push_back(Tail);
11307330f729Sjoerg     }
11317330f729Sjoerg   }
11327330f729Sjoerg 
11337330f729Sjoerg   // Erase everything we no longer need in this function
11347330f729Sjoerg   for (Instruction *I : ToErase)
11357330f729Sjoerg     I->eraseFromParent();
11367330f729Sjoerg 
11377330f729Sjoerg   // Free setjmpTable buffer before each return instruction
11387330f729Sjoerg   for (BasicBlock &BB : F) {
11397330f729Sjoerg     Instruction *TI = BB.getTerminator();
1140*82d56013Sjoerg     if (isa<ReturnInst>(TI)) {
1141*82d56013Sjoerg       DebugLoc DL = getOrCreateDebugLoc(TI, F.getSubprogram());
1142*82d56013Sjoerg       auto *Free = CallInst::CreateFree(SetjmpTable, TI);
1143*82d56013Sjoerg       Free->setDebugLoc(DL);
1144*82d56013Sjoerg       // CallInst::CreateFree may create a bitcast instruction if its argument
1145*82d56013Sjoerg       // types mismatch. We need to set the debug loc for the bitcast too.
1146*82d56013Sjoerg       if (auto *FreeCallI = dyn_cast<CallInst>(Free)) {
1147*82d56013Sjoerg         if (auto *BitCastI = dyn_cast<BitCastInst>(FreeCallI->getArgOperand(0)))
1148*82d56013Sjoerg           BitCastI->setDebugLoc(DL);
1149*82d56013Sjoerg       }
1150*82d56013Sjoerg     }
11517330f729Sjoerg   }
11527330f729Sjoerg 
11537330f729Sjoerg   // Every call to saveSetjmp can change setjmpTable and setjmpTableSize
11547330f729Sjoerg   // (when buffer reallocation occurs)
11557330f729Sjoerg   // entry:
11567330f729Sjoerg   //   setjmpTableSize = 4;
11577330f729Sjoerg   //   setjmpTable = (int *) malloc(40);
11587330f729Sjoerg   //   setjmpTable[0] = 0;
11597330f729Sjoerg   // ...
11607330f729Sjoerg   // somebb:
11617330f729Sjoerg   //   setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
11627330f729Sjoerg   //   setjmpTableSize = getTempRet0();
11637330f729Sjoerg   // So we need to make sure the SSA for these variables is valid so that every
11647330f729Sjoerg   // saveSetjmp and testSetjmp calls have the correct arguments.
11657330f729Sjoerg   SSAUpdater SetjmpTableSSA;
11667330f729Sjoerg   SSAUpdater SetjmpTableSizeSSA;
11677330f729Sjoerg   SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
11687330f729Sjoerg   SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
11697330f729Sjoerg   for (Instruction *I : SetjmpTableInsts)
11707330f729Sjoerg     SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
11717330f729Sjoerg   for (Instruction *I : SetjmpTableSizeInsts)
11727330f729Sjoerg     SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
11737330f729Sjoerg 
11747330f729Sjoerg   for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end();
11757330f729Sjoerg        UI != UE;) {
11767330f729Sjoerg     // Grab the use before incrementing the iterator.
11777330f729Sjoerg     Use &U = *UI;
11787330f729Sjoerg     // Increment the iterator before removing the use from the list.
11797330f729Sjoerg     ++UI;
11807330f729Sjoerg     if (auto *I = dyn_cast<Instruction>(U.getUser()))
11817330f729Sjoerg       if (I->getParent() != &EntryBB)
11827330f729Sjoerg         SetjmpTableSSA.RewriteUse(U);
11837330f729Sjoerg   }
11847330f729Sjoerg   for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end();
11857330f729Sjoerg        UI != UE;) {
11867330f729Sjoerg     Use &U = *UI;
11877330f729Sjoerg     ++UI;
11887330f729Sjoerg     if (auto *I = dyn_cast<Instruction>(U.getUser()))
11897330f729Sjoerg       if (I->getParent() != &EntryBB)
11907330f729Sjoerg         SetjmpTableSizeSSA.RewriteUse(U);
11917330f729Sjoerg   }
11927330f729Sjoerg 
11937330f729Sjoerg   // Finally, our modifications to the cfg can break dominance of SSA variables.
11947330f729Sjoerg   // For example, in this code,
11957330f729Sjoerg   // if (x()) { .. setjmp() .. }
11967330f729Sjoerg   // if (y()) { .. longjmp() .. }
11977330f729Sjoerg   // We must split the longjmp block, and it can jump into the block splitted
11987330f729Sjoerg   // from setjmp one. But that means that when we split the setjmp block, it's
11997330f729Sjoerg   // first part no longer dominates its second part - there is a theoretically
12007330f729Sjoerg   // possible control flow path where x() is false, then y() is true and we
12017330f729Sjoerg   // reach the second part of the setjmp block, without ever reaching the first
12027330f729Sjoerg   // part. So, we rebuild SSA form here.
12037330f729Sjoerg   rebuildSSA(F);
12047330f729Sjoerg   return true;
12057330f729Sjoerg }
1206