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