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