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