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