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