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/Support/CommandLine.h" 215 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 216 #include "llvm/Transforms/Utils/SSAUpdater.h" 217 218 using namespace llvm; 219 220 #define DEBUG_TYPE "wasm-lower-em-ehsjlj" 221 222 static cl::list<std::string> 223 EHWhitelist("emscripten-cxx-exceptions-whitelist", 224 cl::desc("The list of function names in which Emscripten-style " 225 "exception handling is enabled (see emscripten " 226 "EMSCRIPTEN_CATCHING_WHITELIST options)"), 227 cl::CommaSeparated); 228 229 namespace { 230 class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass { 231 bool EnableEH; // Enable exception handling 232 bool EnableSjLj; // Enable setjmp/longjmp handling 233 234 GlobalVariable *ThrewGV = nullptr; 235 GlobalVariable *ThrewValueGV = nullptr; 236 Function *GetTempRet0Func = nullptr; 237 Function *SetTempRet0Func = nullptr; 238 Function *ResumeF = nullptr; 239 Function *EHTypeIDF = nullptr; 240 Function *EmLongjmpF = nullptr; 241 Function *EmLongjmpJmpbufF = nullptr; 242 Function *SaveSetjmpF = nullptr; 243 Function *TestSetjmpF = nullptr; 244 245 // __cxa_find_matching_catch_N functions. 246 // Indexed by the number of clauses in an original landingpad instruction. 247 DenseMap<int, Function *> FindMatchingCatches; 248 // Map of <function signature string, invoke_ wrappers> 249 StringMap<Function *> InvokeWrappers; 250 // Set of whitelisted function names for exception handling 251 std::set<std::string> EHWhitelistSet; 252 253 StringRef getPassName() const override { 254 return "WebAssembly Lower Emscripten Exceptions"; 255 } 256 257 bool runEHOnFunction(Function &F); 258 bool runSjLjOnFunction(Function &F); 259 Function *getFindMatchingCatch(Module &M, unsigned NumClauses); 260 261 template <typename CallOrInvoke> Value *wrapInvoke(CallOrInvoke *CI); 262 void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw, 263 Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label, 264 Value *&LongjmpResult, BasicBlock *&EndBB); 265 template <typename CallOrInvoke> Function *getInvokeWrapper(CallOrInvoke *CI); 266 267 bool areAllExceptionsAllowed() const { return EHWhitelistSet.empty(); } 268 bool canLongjmp(Module &M, const Value *Callee) const; 269 bool isEmAsmCall(Module &M, const Value *Callee) const; 270 271 void rebuildSSA(Function &F); 272 273 public: 274 static char ID; 275 276 WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH = true, bool EnableSjLj = true) 277 : ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj) { 278 EHWhitelistSet.insert(EHWhitelist.begin(), EHWhitelist.end()); 279 } 280 bool runOnModule(Module &M) override; 281 282 void getAnalysisUsage(AnalysisUsage &AU) const override { 283 AU.addRequired<DominatorTreeWrapperPass>(); 284 } 285 }; 286 } // End anonymous namespace 287 288 char WebAssemblyLowerEmscriptenEHSjLj::ID = 0; 289 INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE, 290 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp", 291 false, false) 292 293 ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH, 294 bool EnableSjLj) { 295 return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj); 296 } 297 298 static bool canThrow(const Value *V) { 299 if (const auto *F = dyn_cast<const Function>(V)) { 300 // Intrinsics cannot throw 301 if (F->isIntrinsic()) 302 return false; 303 StringRef Name = F->getName(); 304 // leave setjmp and longjmp (mostly) alone, we process them properly later 305 if (Name == "setjmp" || Name == "longjmp") 306 return false; 307 return !F->doesNotThrow(); 308 } 309 // not a function, so an indirect call - can throw, we can't tell 310 return true; 311 } 312 313 // Get a global variable with the given name. If it doesn't exist declare it, 314 // which will generate an import and asssumes that it will exist at link time. 315 static GlobalVariable *getGlobalVariableI32(Module &M, IRBuilder<> &IRB, 316 const char *Name) { 317 318 auto *GV = 319 dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, IRB.getInt32Ty())); 320 if (!GV) 321 report_fatal_error(Twine("unable to create global: ") + Name); 322 323 return GV; 324 } 325 326 // Simple function name mangler. 327 // This function simply takes LLVM's string representation of parameter types 328 // and concatenate them with '_'. There are non-alphanumeric characters but llc 329 // is ok with it, and we need to postprocess these names after the lowering 330 // phase anyway. 331 static std::string getSignature(FunctionType *FTy) { 332 std::string Sig; 333 raw_string_ostream OS(Sig); 334 OS << *FTy->getReturnType(); 335 for (Type *ParamTy : FTy->params()) 336 OS << "_" << *ParamTy; 337 if (FTy->isVarArg()) 338 OS << "_..."; 339 Sig = OS.str(); 340 Sig.erase(remove_if(Sig, isspace), Sig.end()); 341 // When s2wasm parses .s file, a comma means the end of an argument. So a 342 // mangled function name can contain any character but a comma. 343 std::replace(Sig.begin(), Sig.end(), ',', '.'); 344 return Sig; 345 } 346 347 static void markAsImported(Function *F) { 348 // Tell the linker that this function is expected to be imported from the 349 // 'env' module. 350 if (!F->hasFnAttribute("wasm-import-module")) { 351 llvm::AttrBuilder B; 352 B.addAttribute("wasm-import-module", "env"); 353 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 354 } 355 if (!F->hasFnAttribute("wasm-import-name")) { 356 llvm::AttrBuilder B; 357 B.addAttribute("wasm-import-name", F->getName()); 358 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 359 } 360 } 361 362 // Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2. 363 // This is because a landingpad instruction contains two more arguments, a 364 // personality function and a cleanup bit, and __cxa_find_matching_catch_N 365 // functions are named after the number of arguments in the original landingpad 366 // instruction. 367 Function * 368 WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M, 369 unsigned NumClauses) { 370 if (FindMatchingCatches.count(NumClauses)) 371 return FindMatchingCatches[NumClauses]; 372 PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext()); 373 SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy); 374 FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false); 375 Function *F = Function::Create( 376 FTy, GlobalValue::ExternalLinkage, 377 "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M); 378 markAsImported(F); 379 FindMatchingCatches[NumClauses] = F; 380 return F; 381 } 382 383 // Generate invoke wrapper seqence with preamble and postamble 384 // Preamble: 385 // __THREW__ = 0; 386 // Postamble: 387 // %__THREW__.val = __THREW__; __THREW__ = 0; 388 // Returns %__THREW__.val, which indicates whether an exception is thrown (or 389 // whether longjmp occurred), for future use. 390 template <typename CallOrInvoke> 391 Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallOrInvoke *CI) { 392 LLVMContext &C = CI->getModule()->getContext(); 393 394 // If we are calling a function that is noreturn, we must remove that 395 // attribute. The code we insert here does expect it to return, after we 396 // catch the exception. 397 if (CI->doesNotReturn()) { 398 if (auto *F = dyn_cast<Function>(CI->getCalledValue())) 399 F->removeFnAttr(Attribute::NoReturn); 400 CI->removeAttribute(AttributeList::FunctionIndex, Attribute::NoReturn); 401 } 402 403 IRBuilder<> IRB(C); 404 IRB.SetInsertPoint(CI); 405 406 // Pre-invoke 407 // __THREW__ = 0; 408 IRB.CreateStore(IRB.getInt32(0), ThrewGV); 409 410 // Invoke function wrapper in JavaScript 411 SmallVector<Value *, 16> Args; 412 // Put the pointer to the callee as first argument, so it can be called 413 // within the invoke wrapper later 414 Args.push_back(CI->getCalledValue()); 415 Args.append(CI->arg_begin(), CI->arg_end()); 416 CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args); 417 NewCall->takeName(CI); 418 NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke); 419 NewCall->setDebugLoc(CI->getDebugLoc()); 420 421 // Because we added the pointer to the callee as first argument, all 422 // argument attribute indices have to be incremented by one. 423 SmallVector<AttributeSet, 8> ArgAttributes; 424 const AttributeList &InvokeAL = CI->getAttributes(); 425 426 // No attributes for the callee pointer. 427 ArgAttributes.push_back(AttributeSet()); 428 // Copy the argument attributes from the original 429 for (unsigned I = 0, E = CI->getNumArgOperands(); I < E; ++I) 430 ArgAttributes.push_back(InvokeAL.getParamAttributes(I)); 431 432 AttrBuilder FnAttrs(InvokeAL.getFnAttributes()); 433 if (FnAttrs.contains(Attribute::AllocSize)) { 434 // The allocsize attribute (if any) referes to parameters by index and needs 435 // to be adjusted. 436 unsigned SizeArg; 437 Optional<unsigned> NEltArg; 438 std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs(); 439 SizeArg += 1; 440 if (NEltArg.hasValue()) 441 NEltArg = NEltArg.getValue() + 1; 442 FnAttrs.addAllocSizeAttr(SizeArg, NEltArg); 443 } 444 445 // Reconstruct the AttributesList based on the vector we constructed. 446 AttributeList NewCallAL = 447 AttributeList::get(C, AttributeSet::get(C, FnAttrs), 448 InvokeAL.getRetAttributes(), ArgAttributes); 449 NewCall->setAttributes(NewCallAL); 450 451 CI->replaceAllUsesWith(NewCall); 452 453 // Post-invoke 454 // %__THREW__.val = __THREW__; __THREW__ = 0; 455 Value *Threw = 456 IRB.CreateLoad(IRB.getInt32Ty(), ThrewGV, ThrewGV->getName() + ".val"); 457 IRB.CreateStore(IRB.getInt32(0), ThrewGV); 458 return Threw; 459 } 460 461 // Get matching invoke wrapper based on callee signature 462 template <typename CallOrInvoke> 463 Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallOrInvoke *CI) { 464 Module *M = CI->getModule(); 465 SmallVector<Type *, 16> ArgTys; 466 Value *Callee = CI->getCalledValue(); 467 FunctionType *CalleeFTy; 468 if (auto *F = dyn_cast<Function>(Callee)) 469 CalleeFTy = F->getFunctionType(); 470 else { 471 auto *CalleeTy = cast<PointerType>(Callee->getType())->getElementType(); 472 CalleeFTy = cast<FunctionType>(CalleeTy); 473 } 474 475 std::string Sig = getSignature(CalleeFTy); 476 if (InvokeWrappers.find(Sig) != InvokeWrappers.end()) 477 return InvokeWrappers[Sig]; 478 479 // Put the pointer to the callee as first argument 480 ArgTys.push_back(PointerType::getUnqual(CalleeFTy)); 481 // Add argument types 482 ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end()); 483 484 FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys, 485 CalleeFTy->isVarArg()); 486 Function *F = 487 Function::Create(FTy, GlobalValue::ExternalLinkage, "__invoke_" + Sig, M); 488 markAsImported(F); 489 InvokeWrappers[Sig] = F; 490 return F; 491 } 492 493 bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(Module &M, 494 const Value *Callee) const { 495 if (auto *CalleeF = dyn_cast<Function>(Callee)) 496 if (CalleeF->isIntrinsic()) 497 return false; 498 499 // Attempting to transform inline assembly will result in something like: 500 // call void @__invoke_void(void ()* asm ...) 501 // which is invalid because inline assembly blocks do not have addresses 502 // and can't be passed by pointer. The result is a crash with illegal IR. 503 if (isa<InlineAsm>(Callee)) 504 return false; 505 StringRef CalleeName = Callee->getName(); 506 507 // The reason we include malloc/free here is to exclude the malloc/free 508 // calls generated in setjmp prep / cleanup routines. 509 if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free") 510 return false; 511 512 // There are functions in JS glue code 513 if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" || 514 CalleeName == "saveSetjmp" || CalleeName == "testSetjmp" || 515 CalleeName == "getTempRet0" || CalleeName == "setTempRet0") 516 return false; 517 518 // __cxa_find_matching_catch_N functions cannot longjmp 519 if (Callee->getName().startswith("__cxa_find_matching_catch_")) 520 return false; 521 522 // Exception-catching related functions 523 if (CalleeName == "__cxa_begin_catch" || CalleeName == "__cxa_end_catch" || 524 CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" || 525 CalleeName == "__clang_call_terminate") 526 return false; 527 528 // Otherwise we don't know 529 return true; 530 } 531 532 bool WebAssemblyLowerEmscriptenEHSjLj::isEmAsmCall(Module &M, 533 const Value *Callee) const { 534 StringRef CalleeName = Callee->getName(); 535 // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>. 536 return CalleeName == "emscripten_asm_const_int" || 537 CalleeName == "emscripten_asm_const_double" || 538 CalleeName == "emscripten_asm_const_int_sync_on_main_thread" || 539 CalleeName == "emscripten_asm_const_double_sync_on_main_thread" || 540 CalleeName == "emscripten_asm_const_async_on_main_thread"; 541 } 542 543 // Generate testSetjmp function call seqence with preamble and postamble. 544 // The code this generates is equivalent to the following JavaScript code: 545 // if (%__THREW__.val != 0 & threwValue != 0) { 546 // %label = _testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize); 547 // if (%label == 0) 548 // emscripten_longjmp(%__THREW__.val, threwValue); 549 // setTempRet0(threwValue); 550 // } else { 551 // %label = -1; 552 // } 553 // %longjmp_result = getTempRet0(); 554 // 555 // As output parameters. returns %label, %longjmp_result, and the BB the last 556 // instruction (%longjmp_result = ...) is in. 557 void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp( 558 BasicBlock *BB, DebugLoc DL, Value *Threw, Value *SetjmpTable, 559 Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult, 560 BasicBlock *&EndBB) { 561 Function *F = BB->getParent(); 562 LLVMContext &C = BB->getModule()->getContext(); 563 IRBuilder<> IRB(C); 564 IRB.SetCurrentDebugLocation(DL); 565 566 // if (%__THREW__.val != 0 & threwValue != 0) 567 IRB.SetInsertPoint(BB); 568 BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F); 569 BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F); 570 BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F); 571 Value *ThrewCmp = IRB.CreateICmpNE(Threw, IRB.getInt32(0)); 572 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV, 573 ThrewValueGV->getName() + ".val"); 574 Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0)); 575 Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1"); 576 IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1); 577 578 // %label = _testSetjmp(mem[%__THREW__.val], _setjmpTable, _setjmpTableSize); 579 // if (%label == 0) 580 IRB.SetInsertPoint(ThenBB1); 581 BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F); 582 BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F); 583 Value *ThrewInt = IRB.CreateIntToPtr(Threw, Type::getInt32PtrTy(C), 584 Threw->getName() + ".i32p"); 585 Value *LoadedThrew = IRB.CreateLoad(IRB.getInt32Ty(), ThrewInt, 586 ThrewInt->getName() + ".loaded"); 587 Value *ThenLabel = IRB.CreateCall( 588 TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label"); 589 Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0)); 590 IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2); 591 592 // emscripten_longjmp(%__THREW__.val, threwValue); 593 IRB.SetInsertPoint(ThenBB2); 594 IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue}); 595 IRB.CreateUnreachable(); 596 597 // setTempRet0(threwValue); 598 IRB.SetInsertPoint(EndBB2); 599 IRB.CreateCall(SetTempRet0Func, ThrewValue); 600 IRB.CreateBr(EndBB1); 601 602 IRB.SetInsertPoint(ElseBB1); 603 IRB.CreateBr(EndBB1); 604 605 // longjmp_result = getTempRet0(); 606 IRB.SetInsertPoint(EndBB1); 607 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label"); 608 LabelPHI->addIncoming(ThenLabel, EndBB2); 609 610 LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1); 611 612 // Output parameter assignment 613 Label = LabelPHI; 614 EndBB = EndBB1; 615 LongjmpResult = IRB.CreateCall(GetTempRet0Func, None, "longjmp_result"); 616 } 617 618 void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) { 619 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); 620 DT.recalculate(F); // CFG has been changed 621 SSAUpdater SSA; 622 for (BasicBlock &BB : F) { 623 for (Instruction &I : BB) { 624 SSA.Initialize(I.getType(), I.getName()); 625 SSA.AddAvailableValue(&BB, &I); 626 for (auto UI = I.use_begin(), UE = I.use_end(); UI != UE;) { 627 Use &U = *UI; 628 ++UI; 629 auto *User = cast<Instruction>(U.getUser()); 630 if (auto *UserPN = dyn_cast<PHINode>(User)) 631 if (UserPN->getIncomingBlock(U) == &BB) 632 continue; 633 634 if (DT.dominates(&I, User)) 635 continue; 636 SSA.RewriteUseAfterInsertions(U); 637 } 638 } 639 } 640 } 641 642 bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) { 643 LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n"); 644 645 LLVMContext &C = M.getContext(); 646 IRBuilder<> IRB(C); 647 648 Function *SetjmpF = M.getFunction("setjmp"); 649 Function *LongjmpF = M.getFunction("longjmp"); 650 bool SetjmpUsed = SetjmpF && !SetjmpF->use_empty(); 651 bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty(); 652 bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed); 653 654 // Declare (or get) global variables __THREW__, __threwValue, and 655 // getTempRet0/setTempRet0 function which are used in common for both 656 // exception handling and setjmp/longjmp handling 657 ThrewGV = getGlobalVariableI32(M, IRB, "__THREW__"); 658 ThrewValueGV = getGlobalVariableI32(M, IRB, "__threwValue"); 659 GetTempRet0Func = 660 Function::Create(FunctionType::get(IRB.getInt32Ty(), false), 661 GlobalValue::ExternalLinkage, "getTempRet0", &M); 662 SetTempRet0Func = Function::Create( 663 FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false), 664 GlobalValue::ExternalLinkage, "setTempRet0", &M); 665 GetTempRet0Func->setDoesNotThrow(); 666 SetTempRet0Func->setDoesNotThrow(); 667 668 bool Changed = false; 669 670 // Exception handling 671 if (EnableEH) { 672 // Register __resumeException function 673 FunctionType *ResumeFTy = 674 FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false); 675 ResumeF = Function::Create(ResumeFTy, GlobalValue::ExternalLinkage, 676 "__resumeException", &M); 677 678 // Register llvm_eh_typeid_for function 679 FunctionType *EHTypeIDTy = 680 FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false); 681 EHTypeIDF = Function::Create(EHTypeIDTy, GlobalValue::ExternalLinkage, 682 "llvm_eh_typeid_for", &M); 683 684 for (Function &F : M) { 685 if (F.isDeclaration()) 686 continue; 687 Changed |= runEHOnFunction(F); 688 } 689 } 690 691 // Setjmp/longjmp handling 692 if (DoSjLj) { 693 Changed = true; // We have setjmp or longjmp somewhere 694 695 if (LongjmpF) { 696 // Replace all uses of longjmp with emscripten_longjmp_jmpbuf, which is 697 // defined in JS code 698 EmLongjmpJmpbufF = Function::Create(LongjmpF->getFunctionType(), 699 GlobalValue::ExternalLinkage, 700 "emscripten_longjmp_jmpbuf", &M); 701 702 LongjmpF->replaceAllUsesWith(EmLongjmpJmpbufF); 703 } 704 705 if (SetjmpF) { 706 // Register saveSetjmp function 707 FunctionType *SetjmpFTy = SetjmpF->getFunctionType(); 708 FunctionType *FTy = 709 FunctionType::get(Type::getInt32PtrTy(C), 710 {SetjmpFTy->getParamType(0), IRB.getInt32Ty(), 711 Type::getInt32PtrTy(C), IRB.getInt32Ty()}, 712 false); 713 SaveSetjmpF = 714 Function::Create(FTy, GlobalValue::ExternalLinkage, "saveSetjmp", &M); 715 716 // Register testSetjmp function 717 FTy = FunctionType::get( 718 IRB.getInt32Ty(), 719 {IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()}, false); 720 TestSetjmpF = 721 Function::Create(FTy, GlobalValue::ExternalLinkage, "testSetjmp", &M); 722 723 FTy = FunctionType::get(IRB.getVoidTy(), 724 {IRB.getInt32Ty(), IRB.getInt32Ty()}, false); 725 EmLongjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage, 726 "emscripten_longjmp", &M); 727 728 // Only traverse functions that uses setjmp in order not to insert 729 // unnecessary prep / cleanup code in every function 730 SmallPtrSet<Function *, 8> SetjmpUsers; 731 for (User *U : SetjmpF->users()) { 732 auto *UI = cast<Instruction>(U); 733 SetjmpUsers.insert(UI->getFunction()); 734 } 735 for (Function *F : SetjmpUsers) 736 runSjLjOnFunction(*F); 737 } 738 } 739 740 if (!Changed) { 741 // Delete unused global variables and functions 742 if (ResumeF) 743 ResumeF->eraseFromParent(); 744 if (EHTypeIDF) 745 EHTypeIDF->eraseFromParent(); 746 if (EmLongjmpF) 747 EmLongjmpF->eraseFromParent(); 748 if (SaveSetjmpF) 749 SaveSetjmpF->eraseFromParent(); 750 if (TestSetjmpF) 751 TestSetjmpF->eraseFromParent(); 752 return false; 753 } 754 755 return true; 756 } 757 758 bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) { 759 Module &M = *F.getParent(); 760 LLVMContext &C = F.getContext(); 761 IRBuilder<> IRB(C); 762 bool Changed = false; 763 SmallVector<Instruction *, 64> ToErase; 764 SmallPtrSet<LandingPadInst *, 32> LandingPads; 765 bool AllowExceptions = areAllExceptionsAllowed() || 766 EHWhitelistSet.count(std::string(F.getName())); 767 768 for (BasicBlock &BB : F) { 769 auto *II = dyn_cast<InvokeInst>(BB.getTerminator()); 770 if (!II) 771 continue; 772 Changed = true; 773 LandingPads.insert(II->getLandingPadInst()); 774 IRB.SetInsertPoint(II); 775 776 bool NeedInvoke = AllowExceptions && canThrow(II->getCalledValue()); 777 if (NeedInvoke) { 778 // Wrap invoke with invoke wrapper and generate preamble/postamble 779 Value *Threw = wrapInvoke(II); 780 ToErase.push_back(II); 781 782 // Insert a branch based on __THREW__ variable 783 Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(1), "cmp"); 784 IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest()); 785 786 } else { 787 // This can't throw, and we don't need this invoke, just replace it with a 788 // call+branch 789 SmallVector<Value *, 16> Args(II->arg_begin(), II->arg_end()); 790 CallInst *NewCall = 791 IRB.CreateCall(II->getFunctionType(), II->getCalledValue(), Args); 792 NewCall->takeName(II); 793 NewCall->setCallingConv(II->getCallingConv()); 794 NewCall->setDebugLoc(II->getDebugLoc()); 795 NewCall->setAttributes(II->getAttributes()); 796 II->replaceAllUsesWith(NewCall); 797 ToErase.push_back(II); 798 799 IRB.CreateBr(II->getNormalDest()); 800 801 // Remove any PHI node entries from the exception destination 802 II->getUnwindDest()->removePredecessor(&BB); 803 } 804 } 805 806 // Process resume instructions 807 for (BasicBlock &BB : F) { 808 // Scan the body of the basic block for resumes 809 for (Instruction &I : BB) { 810 auto *RI = dyn_cast<ResumeInst>(&I); 811 if (!RI) 812 continue; 813 Changed = true; 814 815 // Split the input into legal values 816 Value *Input = RI->getValue(); 817 IRB.SetInsertPoint(RI); 818 Value *Low = IRB.CreateExtractValue(Input, 0, "low"); 819 // Create a call to __resumeException function 820 IRB.CreateCall(ResumeF, {Low}); 821 // Add a terminator to the block 822 IRB.CreateUnreachable(); 823 ToErase.push_back(RI); 824 } 825 } 826 827 // Process llvm.eh.typeid.for intrinsics 828 for (BasicBlock &BB : F) { 829 for (Instruction &I : BB) { 830 auto *CI = dyn_cast<CallInst>(&I); 831 if (!CI) 832 continue; 833 const Function *Callee = CI->getCalledFunction(); 834 if (!Callee) 835 continue; 836 if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for) 837 continue; 838 Changed = true; 839 840 IRB.SetInsertPoint(CI); 841 CallInst *NewCI = 842 IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid"); 843 CI->replaceAllUsesWith(NewCI); 844 ToErase.push_back(CI); 845 } 846 } 847 848 // Look for orphan landingpads, can occur in blocks with no predecessors 849 for (BasicBlock &BB : F) { 850 Instruction *I = BB.getFirstNonPHI(); 851 if (auto *LPI = dyn_cast<LandingPadInst>(I)) 852 LandingPads.insert(LPI); 853 } 854 Changed |= !LandingPads.empty(); 855 856 // Handle all the landingpad for this function together, as multiple invokes 857 // may share a single lp 858 for (LandingPadInst *LPI : LandingPads) { 859 IRB.SetInsertPoint(LPI); 860 SmallVector<Value *, 16> FMCArgs; 861 for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) { 862 Constant *Clause = LPI->getClause(I); 863 // As a temporary workaround for the lack of aggregate varargs support 864 // in the interface between JS and wasm, break out filter operands into 865 // their component elements. 866 if (LPI->isFilter(I)) { 867 auto *ATy = cast<ArrayType>(Clause->getType()); 868 for (unsigned J = 0, E = ATy->getNumElements(); J < E; ++J) { 869 Value *EV = IRB.CreateExtractValue(Clause, makeArrayRef(J), "filter"); 870 FMCArgs.push_back(EV); 871 } 872 } else 873 FMCArgs.push_back(Clause); 874 } 875 876 // Create a call to __cxa_find_matching_catch_N function 877 Function *FMCF = getFindMatchingCatch(M, FMCArgs.size()); 878 CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc"); 879 Value *Undef = UndefValue::get(LPI->getType()); 880 Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0"); 881 Value *TempRet0 = IRB.CreateCall(GetTempRet0Func, None, "tempret0"); 882 Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1"); 883 884 LPI->replaceAllUsesWith(Pair1); 885 ToErase.push_back(LPI); 886 } 887 888 // Erase everything we no longer need in this function 889 for (Instruction *I : ToErase) 890 I->eraseFromParent(); 891 892 return Changed; 893 } 894 895 bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) { 896 Module &M = *F.getParent(); 897 LLVMContext &C = F.getContext(); 898 IRBuilder<> IRB(C); 899 SmallVector<Instruction *, 64> ToErase; 900 // Vector of %setjmpTable values 901 std::vector<Instruction *> SetjmpTableInsts; 902 // Vector of %setjmpTableSize values 903 std::vector<Instruction *> SetjmpTableSizeInsts; 904 905 // Setjmp preparation 906 907 // This instruction effectively means %setjmpTableSize = 4. 908 // We create this as an instruction intentionally, and we don't want to fold 909 // this instruction to a constant 4, because this value will be used in 910 // SSAUpdater.AddAvailableValue(...) later. 911 BasicBlock &EntryBB = F.getEntryBlock(); 912 DebugLoc FirstDL = EntryBB.begin()->getDebugLoc(); 913 BinaryOperator *SetjmpTableSize = BinaryOperator::Create( 914 Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize", 915 &*EntryBB.getFirstInsertionPt()); 916 SetjmpTableSize->setDebugLoc(FirstDL); 917 // setjmpTable = (int *) malloc(40); 918 Instruction *SetjmpTable = CallInst::CreateMalloc( 919 SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40), 920 nullptr, nullptr, "setjmpTable"); 921 SetjmpTable->setDebugLoc(FirstDL); 922 // CallInst::CreateMalloc may return a bitcast instruction if the result types 923 // mismatch. We need to set the debug loc for the original call too. 924 auto *MallocCall = SetjmpTable->stripPointerCasts(); 925 if (auto *MallocCallI = dyn_cast<Instruction>(MallocCall)) { 926 MallocCallI->setDebugLoc(FirstDL); 927 } 928 // setjmpTable[0] = 0; 929 IRB.SetInsertPoint(SetjmpTableSize); 930 IRB.CreateStore(IRB.getInt32(0), SetjmpTable); 931 SetjmpTableInsts.push_back(SetjmpTable); 932 SetjmpTableSizeInsts.push_back(SetjmpTableSize); 933 934 // Setjmp transformation 935 std::vector<PHINode *> SetjmpRetPHIs; 936 Function *SetjmpF = M.getFunction("setjmp"); 937 for (User *U : SetjmpF->users()) { 938 auto *CI = dyn_cast<CallInst>(U); 939 if (!CI) 940 report_fatal_error("Does not support indirect calls to setjmp"); 941 942 BasicBlock *BB = CI->getParent(); 943 if (BB->getParent() != &F) // in other function 944 continue; 945 946 // The tail is everything right after the call, and will be reached once 947 // when setjmp is called, and later when longjmp returns to the setjmp 948 BasicBlock *Tail = SplitBlock(BB, CI->getNextNode()); 949 // Add a phi to the tail, which will be the output of setjmp, which 950 // indicates if this is the first call or a longjmp back. The phi directly 951 // uses the right value based on where we arrive from 952 IRB.SetInsertPoint(Tail->getFirstNonPHI()); 953 PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret"); 954 955 // setjmp initial call returns 0 956 SetjmpRet->addIncoming(IRB.getInt32(0), BB); 957 // The proper output is now this, not the setjmp call itself 958 CI->replaceAllUsesWith(SetjmpRet); 959 // longjmp returns to the setjmp will add themselves to this phi 960 SetjmpRetPHIs.push_back(SetjmpRet); 961 962 // Fix call target 963 // Our index in the function is our place in the array + 1 to avoid index 964 // 0, because index 0 means the longjmp is not ours to handle. 965 IRB.SetInsertPoint(CI); 966 Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()), 967 SetjmpTable, SetjmpTableSize}; 968 Instruction *NewSetjmpTable = 969 IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable"); 970 Instruction *NewSetjmpTableSize = 971 IRB.CreateCall(GetTempRet0Func, None, "setjmpTableSize"); 972 SetjmpTableInsts.push_back(NewSetjmpTable); 973 SetjmpTableSizeInsts.push_back(NewSetjmpTableSize); 974 ToErase.push_back(CI); 975 } 976 977 // Update each call that can longjmp so it can return to a setjmp where 978 // relevant. 979 980 // Because we are creating new BBs while processing and don't want to make 981 // all these newly created BBs candidates again for longjmp processing, we 982 // first make the vector of candidate BBs. 983 std::vector<BasicBlock *> BBs; 984 for (BasicBlock &BB : F) 985 BBs.push_back(&BB); 986 987 // BBs.size() will change within the loop, so we query it every time 988 for (unsigned I = 0; I < BBs.size(); I++) { 989 BasicBlock *BB = BBs[I]; 990 for (Instruction &I : *BB) { 991 assert(!isa<InvokeInst>(&I)); 992 auto *CI = dyn_cast<CallInst>(&I); 993 if (!CI) 994 continue; 995 996 const Value *Callee = CI->getCalledValue(); 997 if (!canLongjmp(M, Callee)) 998 continue; 999 if (isEmAsmCall(M, Callee)) 1000 report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " + 1001 F.getName() + 1002 ". Please consider using EM_JS, or move the " 1003 "EM_ASM into another function.", 1004 false); 1005 1006 Value *Threw = nullptr; 1007 BasicBlock *Tail; 1008 if (Callee->getName().startswith("__invoke_")) { 1009 // If invoke wrapper has already been generated for this call in 1010 // previous EH phase, search for the load instruction 1011 // %__THREW__.val = __THREW__; 1012 // in postamble after the invoke wrapper call 1013 LoadInst *ThrewLI = nullptr; 1014 StoreInst *ThrewResetSI = nullptr; 1015 for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end(); 1016 I != IE; ++I) { 1017 if (auto *LI = dyn_cast<LoadInst>(I)) 1018 if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand())) 1019 if (GV == ThrewGV) { 1020 Threw = ThrewLI = LI; 1021 break; 1022 } 1023 } 1024 // Search for the store instruction after the load above 1025 // __THREW__ = 0; 1026 for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end(); 1027 I != IE; ++I) { 1028 if (auto *SI = dyn_cast<StoreInst>(I)) 1029 if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) 1030 if (GV == ThrewGV && SI->getValueOperand() == IRB.getInt32(0)) { 1031 ThrewResetSI = SI; 1032 break; 1033 } 1034 } 1035 assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke"); 1036 assert(ThrewResetSI && "Cannot find __THREW__ store after invoke"); 1037 Tail = SplitBlock(BB, ThrewResetSI->getNextNode()); 1038 1039 } else { 1040 // Wrap call with invoke wrapper and generate preamble/postamble 1041 Threw = wrapInvoke(CI); 1042 ToErase.push_back(CI); 1043 Tail = SplitBlock(BB, CI->getNextNode()); 1044 } 1045 1046 // We need to replace the terminator in Tail - SplitBlock makes BB go 1047 // straight to Tail, we need to check if a longjmp occurred, and go to the 1048 // right setjmp-tail if so 1049 ToErase.push_back(BB->getTerminator()); 1050 1051 // Generate a function call to testSetjmp function and preamble/postamble 1052 // code to figure out (1) whether longjmp occurred (2) if longjmp 1053 // occurred, which setjmp it corresponds to 1054 Value *Label = nullptr; 1055 Value *LongjmpResult = nullptr; 1056 BasicBlock *EndBB = nullptr; 1057 wrapTestSetjmp(BB, CI->getDebugLoc(), Threw, SetjmpTable, SetjmpTableSize, 1058 Label, LongjmpResult, EndBB); 1059 assert(Label && LongjmpResult && EndBB); 1060 1061 // Create switch instruction 1062 IRB.SetInsertPoint(EndBB); 1063 IRB.SetCurrentDebugLocation(EndBB->getInstList().back().getDebugLoc()); 1064 SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size()); 1065 // -1 means no longjmp happened, continue normally (will hit the default 1066 // switch case). 0 means a longjmp that is not ours to handle, needs a 1067 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid 1068 // 0). 1069 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) { 1070 SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent()); 1071 SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB); 1072 } 1073 1074 // We are splitting the block here, and must continue to find other calls 1075 // in the block - which is now split. so continue to traverse in the Tail 1076 BBs.push_back(Tail); 1077 } 1078 } 1079 1080 // Erase everything we no longer need in this function 1081 for (Instruction *I : ToErase) 1082 I->eraseFromParent(); 1083 1084 // Free setjmpTable buffer before each return instruction 1085 for (BasicBlock &BB : F) { 1086 Instruction *TI = BB.getTerminator(); 1087 if (isa<ReturnInst>(TI)) { 1088 auto *Free = CallInst::CreateFree(SetjmpTable, TI); 1089 Free->setDebugLoc(TI->getDebugLoc()); 1090 // CallInst::CreateFree may create a bitcast instruction if its argument 1091 // types mismatch. We need to set the debug loc for the bitcast too. 1092 if (auto *FreeCallI = dyn_cast<CallInst>(Free)) { 1093 if (auto *BitCastI = dyn_cast<BitCastInst>(FreeCallI->getArgOperand(0))) 1094 BitCastI->setDebugLoc(TI->getDebugLoc()); 1095 } 1096 } 1097 } 1098 1099 // Every call to saveSetjmp can change setjmpTable and setjmpTableSize 1100 // (when buffer reallocation occurs) 1101 // entry: 1102 // setjmpTableSize = 4; 1103 // setjmpTable = (int *) malloc(40); 1104 // setjmpTable[0] = 0; 1105 // ... 1106 // somebb: 1107 // setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize); 1108 // setjmpTableSize = getTempRet0(); 1109 // So we need to make sure the SSA for these variables is valid so that every 1110 // saveSetjmp and testSetjmp calls have the correct arguments. 1111 SSAUpdater SetjmpTableSSA; 1112 SSAUpdater SetjmpTableSizeSSA; 1113 SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable"); 1114 SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize"); 1115 for (Instruction *I : SetjmpTableInsts) 1116 SetjmpTableSSA.AddAvailableValue(I->getParent(), I); 1117 for (Instruction *I : SetjmpTableSizeInsts) 1118 SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I); 1119 1120 for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end(); 1121 UI != UE;) { 1122 // Grab the use before incrementing the iterator. 1123 Use &U = *UI; 1124 // Increment the iterator before removing the use from the list. 1125 ++UI; 1126 if (auto *I = dyn_cast<Instruction>(U.getUser())) 1127 if (I->getParent() != &EntryBB) 1128 SetjmpTableSSA.RewriteUse(U); 1129 } 1130 for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end(); 1131 UI != UE;) { 1132 Use &U = *UI; 1133 ++UI; 1134 if (auto *I = dyn_cast<Instruction>(U.getUser())) 1135 if (I->getParent() != &EntryBB) 1136 SetjmpTableSizeSSA.RewriteUse(U); 1137 } 1138 1139 // Finally, our modifications to the cfg can break dominance of SSA variables. 1140 // For example, in this code, 1141 // if (x()) { .. setjmp() .. } 1142 // if (y()) { .. longjmp() .. } 1143 // We must split the longjmp block, and it can jump into the block splitted 1144 // from setjmp one. But that means that when we split the setjmp block, it's 1145 // first part no longer dominates its second part - there is a theoretically 1146 // possible control flow path where x() is false, then y() is true and we 1147 // reach the second part of the setjmp block, without ever reaching the first 1148 // part. So, we rebuild SSA form here. 1149 rebuildSSA(F); 1150 return true; 1151 } 1152