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 function 11 /// calls to use Emscripten's library functions. The pass uses JavaScript's try 12 /// and catch mechanism in case of Emscripten EH/SjLj and Wasm EH intrinsics in 13 /// case of Emscripten SjLJ. 14 /// 15 /// * Emscripten exception handling 16 /// This pass lowers invokes and landingpads into library functions in JS glue 17 /// code. Invokes are lowered into function wrappers called invoke wrappers that 18 /// exist in JS side, which wraps the original function call with JS try-catch. 19 /// If an exception occurred, cxa_throw() function in JS side sets some 20 /// variables (see below) so we can check whether an exception occurred from 21 /// wasm code and handle it appropriately. 22 /// 23 /// * Emscripten setjmp-longjmp handling 24 /// This pass lowers setjmp to a reasonably-performant approach for emscripten. 25 /// The idea is that each block with a setjmp is broken up into two parts: the 26 /// part containing setjmp and the part right after the setjmp. The latter part 27 /// is either reached from the setjmp, or later from a longjmp. To handle the 28 /// longjmp, all calls that might longjmp are also called using invoke wrappers 29 /// and thus JS / try-catch. JS longjmp() function also sets some variables so 30 /// we can check / whether a longjmp occurred from wasm code. Each block with a 31 /// function call that might longjmp is also split up after the longjmp call. 32 /// After the longjmp call, we check whether a longjmp occurred, and if it did, 33 /// which setjmp it corresponds to, and jump to the right post-setjmp block. 34 /// We assume setjmp-longjmp handling always run after EH handling, which means 35 /// we don't expect any exception-related instructions when SjLj runs. 36 /// FIXME Currently this scheme does not support indirect call of setjmp, 37 /// because of the limitation of the scheme itself. fastcomp does not support it 38 /// either. 39 /// 40 /// In detail, this pass does following things: 41 /// 42 /// 1) Assumes the existence of global variables: __THREW__, __threwValue 43 /// __THREW__ and __threwValue are defined in compiler-rt in Emscripten. 44 /// These variables are used for both exceptions and setjmp/longjmps. 45 /// __THREW__ indicates whether an exception or a longjmp occurred or not. 0 46 /// means nothing occurred, 1 means an exception occurred, and other numbers 47 /// mean a longjmp occurred. In the case of longjmp, __THREW__ variable 48 /// indicates the corresponding setjmp buffer the longjmp corresponds to. 49 /// __threwValue is 0 for exceptions, and the argument to longjmp in case of 50 /// longjmp. 51 /// 52 /// * Emscripten exception handling 53 /// 54 /// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions 55 /// at link time. setThrew exists in Emscripten's compiler-rt: 56 /// 57 /// void setThrew(uintptr_t threw, int value) { 58 /// if (__THREW__ == 0) { 59 /// __THREW__ = threw; 60 /// __threwValue = value; 61 /// } 62 /// } 63 // 64 /// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code. 65 /// In exception handling, getTempRet0 indicates the type of an exception 66 /// caught, and in setjmp/longjmp, it means the second argument to longjmp 67 /// function. 68 /// 69 /// 3) Lower 70 /// invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad 71 /// into 72 /// __THREW__ = 0; 73 /// call @__invoke_SIG(func, arg1, arg2) 74 /// %__THREW__.val = __THREW__; 75 /// __THREW__ = 0; 76 /// if (%__THREW__.val == 1) 77 /// goto %lpad 78 /// else 79 /// goto %invoke.cont 80 /// SIG is a mangled string generated based on the LLVM IR-level function 81 /// signature. After LLVM IR types are lowered to the target wasm types, 82 /// the names for these wrappers will change based on wasm types as well, 83 /// as in invoke_vi (function takes an int and returns void). The bodies of 84 /// these wrappers will be generated in JS glue code, and inside those 85 /// wrappers we use JS try-catch to generate actual exception effects. It 86 /// also calls the original callee function. An example wrapper in JS code 87 /// would look like this: 88 /// function invoke_vi(index,a1) { 89 /// try { 90 /// Module["dynCall_vi"](index,a1); // This calls original callee 91 /// } catch(e) { 92 /// if (typeof e !== 'number' && e !== 'longjmp') throw e; 93 /// _setThrew(1, 0); // setThrew is called here 94 /// } 95 /// } 96 /// If an exception is thrown, __THREW__ will be set to true in a wrapper, 97 /// so we can jump to the right BB based on this value. 98 /// 99 /// 4) Lower 100 /// %val = landingpad catch c1 catch c2 catch c3 ... 101 /// ... use %val ... 102 /// into 103 /// %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...) 104 /// %val = {%fmc, getTempRet0()} 105 /// ... use %val ... 106 /// Here N is a number calculated based on the number of clauses. 107 /// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code. 108 /// 109 /// 5) Lower 110 /// resume {%a, %b} 111 /// into 112 /// call @__resumeException(%a) 113 /// where __resumeException() is a function in JS glue code. 114 /// 115 /// 6) Lower 116 /// call @llvm.eh.typeid.for(type) (intrinsic) 117 /// into 118 /// call @llvm_eh_typeid_for(type) 119 /// llvm_eh_typeid_for function will be generated in JS glue code. 120 /// 121 /// * Emscripten setjmp / longjmp handling 122 /// 123 /// If there are calls to longjmp() 124 /// 125 /// 1) Lower 126 /// longjmp(env, val) 127 /// into 128 /// emscripten_longjmp(env, val) 129 /// 130 /// If there are calls to setjmp() 131 /// 132 /// 2) In the function entry that calls setjmp, initialize setjmpTable and 133 /// sejmpTableSize as follows: 134 /// setjmpTableSize = 4; 135 /// setjmpTable = (int *) malloc(40); 136 /// setjmpTable[0] = 0; 137 /// setjmpTable and setjmpTableSize are used to call saveSetjmp() function in 138 /// Emscripten compiler-rt. 139 /// 140 /// 3) Lower 141 /// setjmp(env) 142 /// into 143 /// setjmpTable = saveSetjmp(env, label, setjmpTable, setjmpTableSize); 144 /// setjmpTableSize = getTempRet0(); 145 /// For each dynamic setjmp call, setjmpTable stores its ID (a number which 146 /// is incrementally assigned from 0) and its label (a unique number that 147 /// represents each callsite of setjmp). When we need more entries in 148 /// setjmpTable, it is reallocated in saveSetjmp() in Emscripten's 149 /// compiler-rt and it will return the new table address, and assign the new 150 /// table size in setTempRet0(). saveSetjmp also stores the setjmp's ID into 151 /// the buffer 'env'. A BB with setjmp is split into two after setjmp call in 152 /// order to make the post-setjmp BB the possible destination of longjmp BB. 153 /// 154 /// 4) Lower every call that might longjmp into 155 /// __THREW__ = 0; 156 /// call @__invoke_SIG(func, arg1, arg2) 157 /// %__THREW__.val = __THREW__; 158 /// __THREW__ = 0; 159 /// %__threwValue.val = __threwValue; 160 /// if (%__THREW__.val != 0 & %__threwValue.val != 0) { 161 /// %label = testSetjmp(mem[%__THREW__.val], setjmpTable, 162 /// setjmpTableSize); 163 /// if (%label == 0) 164 /// emscripten_longjmp(%__THREW__.val, %__threwValue.val); 165 /// setTempRet0(%__threwValue.val); 166 /// } else { 167 /// %label = -1; 168 /// } 169 /// longjmp_result = getTempRet0(); 170 /// switch %label { 171 /// label 1: goto post-setjmp BB 1 172 /// label 2: goto post-setjmp BB 2 173 /// ... 174 /// default: goto splitted next BB 175 /// } 176 /// testSetjmp examines setjmpTable to see if there is a matching setjmp 177 /// call. After calling an invoke wrapper, if a longjmp occurred, __THREW__ 178 /// will be the address of matching jmp_buf buffer and __threwValue be the 179 /// second argument to longjmp. mem[%__THREW__.val] is a setjmp ID that is 180 /// stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to 181 /// each setjmp callsite. Label 0 means this longjmp buffer does not 182 /// correspond to one of the setjmp callsites in this function, so in this 183 /// case we just chain the longjmp to the caller. Label -1 means no longjmp 184 /// occurred. Otherwise we jump to the right post-setjmp BB based on the 185 /// label. 186 /// 187 /// * Wasm setjmp / longjmp handling 188 /// This mode still uses some Emscripten library functions but not JavaScript's 189 /// try-catch mechanism. It instead uses Wasm exception handling intrinsics, 190 /// which will be lowered to exception handling instructions. 191 /// 192 /// If there are calls to longjmp() 193 /// 194 /// 1) Lower 195 /// longjmp(env, val) 196 /// into 197 /// __wasm_longjmp(env, val) 198 /// 199 /// If there are calls to setjmp() 200 /// 201 /// 2) and 3): The same as 2) and 3) in Emscripten SjLj. 202 /// (setjmpTable/setjmpTableSize initialization + setjmp callsite 203 /// transformation) 204 /// 205 /// 4) Create a catchpad with a wasm.catch() intrinsic, which returns the value 206 /// thrown by __wasm_longjmp function. In Emscripten library, we have this 207 /// struct: 208 /// 209 /// struct __WasmLongjmpArgs { 210 /// void *env; 211 /// int val; 212 /// }; 213 /// struct __WasmLongjmpArgs __wasm_longjmp_args; 214 /// 215 /// The thrown value here is a pointer to __wasm_longjmp_args struct object. We 216 /// use this struct to transfer two values by throwing a single value. Wasm 217 /// throw and catch instructions are capable of throwing and catching multiple 218 /// values, but it also requires multivalue support that is currently not very 219 /// reliable. 220 /// TODO Switch to throwing and catching two values without using the struct 221 /// 222 /// All longjmpable function calls will be converted to an invoke that will 223 /// unwind to this catchpad in case a longjmp occurs. Within the catchpad, we 224 /// test the thrown values using testSetjmp function as we do for Emscripten 225 /// SjLj. The main difference is, in Emscripten SjLj, we need to transform every 226 /// longjmpable callsite into a sequence of code including testSetjmp() call; in 227 /// Wasm SjLj we do the testing in only one place, in this catchpad. 228 /// 229 /// After testing calling testSetjmp(), if the longjmp does not correspond to 230 /// one of the setjmps within the current function, it rethrows the longjmp 231 /// by calling __wasm_longjmp(). If it corresponds to one of setjmps in the 232 /// function, we jump to the beginning of the function, which contains a switch 233 /// to each post-setjmp BB. Again, in Emscripten SjLj, this switch is added for 234 /// every longjmpable callsite; in Wasm SjLj we do this only once at the top of 235 /// the function. (after setjmpTable/setjmpTableSize initialization) 236 /// 237 /// The below is the pseudocode for what we have described 238 /// 239 /// entry: 240 /// Initialize setjmpTable and setjmpTableSize 241 /// 242 /// setjmp.dispatch: 243 /// switch %label { 244 /// label 1: goto post-setjmp BB 1 245 /// label 2: goto post-setjmp BB 2 246 /// ... 247 /// default: goto splitted next BB 248 /// } 249 /// ... 250 /// 251 /// bb: 252 /// invoke void @foo() ;; foo is a longjmpable function 253 /// to label %next unwind label %catch.dispatch.longjmp 254 /// ... 255 /// 256 /// catch.dispatch.longjmp: 257 /// %0 = catchswitch within none [label %catch.longjmp] unwind to caller 258 /// 259 /// catch.longjmp: 260 /// %longjmp.args = wasm.catch() ;; struct __WasmLongjmpArgs 261 /// %env = load 'env' field from __WasmLongjmpArgs 262 /// %val = load 'val' field from __WasmLongjmpArgs 263 /// %label = testSetjmp(mem[%env], setjmpTable, setjmpTableSize); 264 /// if (%label == 0) 265 /// __wasm_longjmp(%env, %val) 266 /// catchret to %setjmp.dispatch 267 /// 268 ///===----------------------------------------------------------------------===// 269 270 #include "Utils/WebAssemblyUtilities.h" 271 #include "WebAssembly.h" 272 #include "WebAssemblyTargetMachine.h" 273 #include "llvm/ADT/StringExtras.h" 274 #include "llvm/CodeGen/TargetPassConfig.h" 275 #include "llvm/CodeGen/WasmEHFuncInfo.h" 276 #include "llvm/IR/DebugInfoMetadata.h" 277 #include "llvm/IR/Dominators.h" 278 #include "llvm/IR/IRBuilder.h" 279 #include "llvm/IR/IntrinsicsWebAssembly.h" 280 #include "llvm/Support/CommandLine.h" 281 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 282 #include "llvm/Transforms/Utils/Local.h" 283 #include "llvm/Transforms/Utils/SSAUpdater.h" 284 #include "llvm/Transforms/Utils/SSAUpdaterBulk.h" 285 286 using namespace llvm; 287 288 #define DEBUG_TYPE "wasm-lower-em-ehsjlj" 289 290 static cl::list<std::string> 291 EHAllowlist("emscripten-cxx-exceptions-allowed", 292 cl::desc("The list of function names in which Emscripten-style " 293 "exception handling is enabled (see emscripten " 294 "EMSCRIPTEN_CATCHING_ALLOWED options)"), 295 cl::CommaSeparated); 296 297 namespace { 298 class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass { 299 bool EnableEmEH; // Enable Emscripten exception handling 300 bool EnableEmSjLj; // Enable Emscripten setjmp/longjmp handling 301 bool EnableWasmSjLj; // Enable Wasm setjmp/longjmp handling 302 bool DoSjLj; // Whether we actually perform setjmp/longjmp handling 303 304 GlobalVariable *ThrewGV = nullptr; // __THREW__ (Emscripten) 305 GlobalVariable *ThrewValueGV = nullptr; // __threwValue (Emscripten) 306 Function *GetTempRet0F = nullptr; // getTempRet0() (Emscripten) 307 Function *SetTempRet0F = nullptr; // setTempRet0() (Emscripten) 308 Function *ResumeF = nullptr; // __resumeException() (Emscripten) 309 Function *EHTypeIDF = nullptr; // llvm.eh.typeid.for() (intrinsic) 310 Function *EmLongjmpF = nullptr; // emscripten_longjmp() (Emscripten) 311 Function *SaveSetjmpF = nullptr; // saveSetjmp() (Emscripten) 312 Function *TestSetjmpF = nullptr; // testSetjmp() (Emscripten) 313 Function *WasmLongjmpF = nullptr; // __wasm_longjmp() (Emscripten) 314 Function *CatchF = nullptr; // wasm.catch() (intrinsic) 315 316 // type of 'struct __WasmLongjmpArgs' defined in emscripten 317 Type *LongjmpArgsTy = nullptr; 318 319 // __cxa_find_matching_catch_N functions. 320 // Indexed by the number of clauses in an original landingpad instruction. 321 DenseMap<int, Function *> FindMatchingCatches; 322 // Map of <function signature string, invoke_ wrappers> 323 StringMap<Function *> InvokeWrappers; 324 // Set of allowed function names for exception handling 325 std::set<std::string> EHAllowlistSet; 326 // Functions that contains calls to setjmp 327 SmallPtrSet<Function *, 8> SetjmpUsers; 328 329 StringRef getPassName() const override { 330 return "WebAssembly Lower Emscripten Exceptions"; 331 } 332 333 using InstVector = SmallVectorImpl<Instruction *>; 334 bool runEHOnFunction(Function &F); 335 bool runSjLjOnFunction(Function &F); 336 void handleLongjmpableCallsForEmscriptenSjLj( 337 Function &F, InstVector &SetjmpTableInsts, 338 InstVector &SetjmpTableSizeInsts, 339 SmallVectorImpl<PHINode *> &SetjmpRetPHIs); 340 void 341 handleLongjmpableCallsForWasmSjLj(Function &F, InstVector &SetjmpTableInsts, 342 InstVector &SetjmpTableSizeInsts, 343 SmallVectorImpl<PHINode *> &SetjmpRetPHIs); 344 Function *getFindMatchingCatch(Module &M, unsigned NumClauses); 345 346 Value *wrapInvoke(CallBase *CI); 347 void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw, 348 Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label, 349 Value *&LongjmpResult, BasicBlock *&CallEmLongjmpBB, 350 PHINode *&CallEmLongjmpBBThrewPHI, 351 PHINode *&CallEmLongjmpBBThrewValuePHI, 352 BasicBlock *&EndBB); 353 Function *getInvokeWrapper(CallBase *CI); 354 355 bool areAllExceptionsAllowed() const { return EHAllowlistSet.empty(); } 356 bool supportsException(const Function *F) const { 357 return EnableEmEH && (areAllExceptionsAllowed() || 358 EHAllowlistSet.count(std::string(F->getName()))); 359 } 360 void replaceLongjmpWith(Function *LongjmpF, Function *NewF); 361 362 void rebuildSSA(Function &F); 363 364 public: 365 static char ID; 366 367 WebAssemblyLowerEmscriptenEHSjLj() 368 : ModulePass(ID), EnableEmEH(WebAssembly::WasmEnableEmEH), 369 EnableEmSjLj(WebAssembly::WasmEnableEmSjLj), 370 EnableWasmSjLj(WebAssembly::WasmEnableSjLj) { 371 assert(!(EnableEmSjLj && EnableWasmSjLj) && 372 "Two SjLj modes cannot be turned on at the same time"); 373 assert(!(EnableEmEH && EnableWasmSjLj) && 374 "Wasm SjLj should be only used with Wasm EH"); 375 EHAllowlistSet.insert(EHAllowlist.begin(), EHAllowlist.end()); 376 } 377 bool runOnModule(Module &M) override; 378 379 void getAnalysisUsage(AnalysisUsage &AU) const override { 380 AU.addRequired<DominatorTreeWrapperPass>(); 381 } 382 }; 383 } // End anonymous namespace 384 385 char WebAssemblyLowerEmscriptenEHSjLj::ID = 0; 386 INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE, 387 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp", 388 false, false) 389 390 ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj() { 391 return new WebAssemblyLowerEmscriptenEHSjLj(); 392 } 393 394 static bool canThrow(const Value *V) { 395 if (const auto *F = dyn_cast<const Function>(V)) { 396 // Intrinsics cannot throw 397 if (F->isIntrinsic()) 398 return false; 399 StringRef Name = F->getName(); 400 // leave setjmp and longjmp (mostly) alone, we process them properly later 401 if (Name == "setjmp" || Name == "longjmp" || Name == "emscripten_longjmp") 402 return false; 403 return !F->doesNotThrow(); 404 } 405 // not a function, so an indirect call - can throw, we can't tell 406 return true; 407 } 408 409 // Get a global variable with the given name. If it doesn't exist declare it, 410 // which will generate an import and assume that it will exist at link time. 411 static GlobalVariable *getGlobalVariable(Module &M, Type *Ty, 412 WebAssemblyTargetMachine &TM, 413 const char *Name) { 414 auto *GV = dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, Ty)); 415 if (!GV) 416 report_fatal_error(Twine("unable to create global: ") + Name); 417 418 // If the target supports TLS, make this variable thread-local. We can't just 419 // unconditionally make it thread-local and depend on 420 // CoalesceFeaturesAndStripAtomics to downgrade it, because stripping TLS has 421 // the side effect of disallowing the object from being linked into a 422 // shared-memory module, which we don't want to be responsible for. 423 auto *Subtarget = TM.getSubtargetImpl(); 424 auto TLS = Subtarget->hasAtomics() && Subtarget->hasBulkMemory() 425 ? GlobalValue::LocalExecTLSModel 426 : GlobalValue::NotThreadLocal; 427 GV->setThreadLocalMode(TLS); 428 return GV; 429 } 430 431 // Simple function name mangler. 432 // This function simply takes LLVM's string representation of parameter types 433 // and concatenate them with '_'. There are non-alphanumeric characters but llc 434 // is ok with it, and we need to postprocess these names after the lowering 435 // phase anyway. 436 static std::string getSignature(FunctionType *FTy) { 437 std::string Sig; 438 raw_string_ostream OS(Sig); 439 OS << *FTy->getReturnType(); 440 for (Type *ParamTy : FTy->params()) 441 OS << "_" << *ParamTy; 442 if (FTy->isVarArg()) 443 OS << "_..."; 444 Sig = OS.str(); 445 erase_if(Sig, isSpace); 446 // When s2wasm parses .s file, a comma means the end of an argument. So a 447 // mangled function name can contain any character but a comma. 448 std::replace(Sig.begin(), Sig.end(), ',', '.'); 449 return Sig; 450 } 451 452 static Function *getEmscriptenFunction(FunctionType *Ty, const Twine &Name, 453 Module *M) { 454 Function* F = Function::Create(Ty, GlobalValue::ExternalLinkage, Name, M); 455 // Tell the linker that this function is expected to be imported from the 456 // 'env' module. 457 if (!F->hasFnAttribute("wasm-import-module")) { 458 llvm::AttrBuilder B; 459 B.addAttribute("wasm-import-module", "env"); 460 F->addFnAttrs(B); 461 } 462 if (!F->hasFnAttribute("wasm-import-name")) { 463 llvm::AttrBuilder B; 464 B.addAttribute("wasm-import-name", F->getName()); 465 F->addFnAttrs(B); 466 } 467 return F; 468 } 469 470 // Returns an integer type for the target architecture's address space. 471 // i32 for wasm32 and i64 for wasm64. 472 static Type *getAddrIntType(Module *M) { 473 IRBuilder<> IRB(M->getContext()); 474 return IRB.getIntNTy(M->getDataLayout().getPointerSizeInBits()); 475 } 476 477 // Returns an integer pointer type for the target architecture's address space. 478 // i32* for wasm32 and i64* for wasm64. 479 static Type *getAddrPtrType(Module *M) { 480 return Type::getIntNPtrTy(M->getContext(), 481 M->getDataLayout().getPointerSizeInBits()); 482 } 483 484 // Returns an integer whose type is the integer type for the target's address 485 // space. Returns (i32 C) for wasm32 and (i64 C) for wasm64, when C is the 486 // integer. 487 static Value *getAddrSizeInt(Module *M, uint64_t C) { 488 IRBuilder<> IRB(M->getContext()); 489 return IRB.getIntN(M->getDataLayout().getPointerSizeInBits(), C); 490 } 491 492 // Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2. 493 // This is because a landingpad instruction contains two more arguments, a 494 // personality function and a cleanup bit, and __cxa_find_matching_catch_N 495 // functions are named after the number of arguments in the original landingpad 496 // instruction. 497 Function * 498 WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M, 499 unsigned NumClauses) { 500 if (FindMatchingCatches.count(NumClauses)) 501 return FindMatchingCatches[NumClauses]; 502 PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext()); 503 SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy); 504 FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false); 505 Function *F = getEmscriptenFunction( 506 FTy, "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M); 507 FindMatchingCatches[NumClauses] = F; 508 return F; 509 } 510 511 // Generate invoke wrapper seqence with preamble and postamble 512 // Preamble: 513 // __THREW__ = 0; 514 // Postamble: 515 // %__THREW__.val = __THREW__; __THREW__ = 0; 516 // Returns %__THREW__.val, which indicates whether an exception is thrown (or 517 // whether longjmp occurred), for future use. 518 Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) { 519 Module *M = CI->getModule(); 520 LLVMContext &C = M->getContext(); 521 522 IRBuilder<> IRB(C); 523 IRB.SetInsertPoint(CI); 524 525 // Pre-invoke 526 // __THREW__ = 0; 527 IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV); 528 529 // Invoke function wrapper in JavaScript 530 SmallVector<Value *, 16> Args; 531 // Put the pointer to the callee as first argument, so it can be called 532 // within the invoke wrapper later 533 Args.push_back(CI->getCalledOperand()); 534 Args.append(CI->arg_begin(), CI->arg_end()); 535 CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args); 536 NewCall->takeName(CI); 537 NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke); 538 NewCall->setDebugLoc(CI->getDebugLoc()); 539 540 // Because we added the pointer to the callee as first argument, all 541 // argument attribute indices have to be incremented by one. 542 SmallVector<AttributeSet, 8> ArgAttributes; 543 const AttributeList &InvokeAL = CI->getAttributes(); 544 545 // No attributes for the callee pointer. 546 ArgAttributes.push_back(AttributeSet()); 547 // Copy the argument attributes from the original 548 for (unsigned I = 0, E = CI->arg_size(); I < E; ++I) 549 ArgAttributes.push_back(InvokeAL.getParamAttrs(I)); 550 551 AttrBuilder FnAttrs(InvokeAL.getFnAttrs()); 552 if (FnAttrs.contains(Attribute::AllocSize)) { 553 // The allocsize attribute (if any) referes to parameters by index and needs 554 // to be adjusted. 555 unsigned SizeArg; 556 Optional<unsigned> NEltArg; 557 std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs(); 558 SizeArg += 1; 559 if (NEltArg.hasValue()) 560 NEltArg = NEltArg.getValue() + 1; 561 FnAttrs.addAllocSizeAttr(SizeArg, NEltArg); 562 } 563 564 // Reconstruct the AttributesList based on the vector we constructed. 565 AttributeList NewCallAL = AttributeList::get( 566 C, AttributeSet::get(C, FnAttrs), InvokeAL.getRetAttrs(), ArgAttributes); 567 NewCall->setAttributes(NewCallAL); 568 569 CI->replaceAllUsesWith(NewCall); 570 571 // Post-invoke 572 // %__THREW__.val = __THREW__; __THREW__ = 0; 573 Value *Threw = 574 IRB.CreateLoad(getAddrIntType(M), ThrewGV, ThrewGV->getName() + ".val"); 575 IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV); 576 return Threw; 577 } 578 579 // Get matching invoke wrapper based on callee signature 580 Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallBase *CI) { 581 Module *M = CI->getModule(); 582 SmallVector<Type *, 16> ArgTys; 583 FunctionType *CalleeFTy = CI->getFunctionType(); 584 585 std::string Sig = getSignature(CalleeFTy); 586 if (InvokeWrappers.find(Sig) != InvokeWrappers.end()) 587 return InvokeWrappers[Sig]; 588 589 // Put the pointer to the callee as first argument 590 ArgTys.push_back(PointerType::getUnqual(CalleeFTy)); 591 // Add argument types 592 ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end()); 593 594 FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys, 595 CalleeFTy->isVarArg()); 596 Function *F = getEmscriptenFunction(FTy, "__invoke_" + Sig, M); 597 InvokeWrappers[Sig] = F; 598 return F; 599 } 600 601 static bool canLongjmp(const Value *Callee) { 602 if (auto *CalleeF = dyn_cast<Function>(Callee)) 603 if (CalleeF->isIntrinsic()) 604 return false; 605 606 // Attempting to transform inline assembly will result in something like: 607 // call void @__invoke_void(void ()* asm ...) 608 // which is invalid because inline assembly blocks do not have addresses 609 // and can't be passed by pointer. The result is a crash with illegal IR. 610 if (isa<InlineAsm>(Callee)) 611 return false; 612 StringRef CalleeName = Callee->getName(); 613 614 // The reason we include malloc/free here is to exclude the malloc/free 615 // calls generated in setjmp prep / cleanup routines. 616 if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free") 617 return false; 618 619 // There are functions in Emscripten's JS glue code or compiler-rt 620 if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" || 621 CalleeName == "saveSetjmp" || CalleeName == "testSetjmp" || 622 CalleeName == "getTempRet0" || CalleeName == "setTempRet0") 623 return false; 624 625 // __cxa_find_matching_catch_N functions cannot longjmp 626 if (Callee->getName().startswith("__cxa_find_matching_catch_")) 627 return false; 628 629 // Exception-catching related functions 630 if (CalleeName == "__cxa_begin_catch" || CalleeName == "__cxa_end_catch" || 631 CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" || 632 CalleeName == "__clang_call_terminate") 633 return false; 634 635 // Otherwise we don't know 636 return true; 637 } 638 639 static bool isEmAsmCall(const Value *Callee) { 640 StringRef CalleeName = Callee->getName(); 641 // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>. 642 return CalleeName == "emscripten_asm_const_int" || 643 CalleeName == "emscripten_asm_const_double" || 644 CalleeName == "emscripten_asm_const_int_sync_on_main_thread" || 645 CalleeName == "emscripten_asm_const_double_sync_on_main_thread" || 646 CalleeName == "emscripten_asm_const_async_on_main_thread"; 647 } 648 649 // Generate testSetjmp function call seqence with preamble and postamble. 650 // The code this generates is equivalent to the following JavaScript code: 651 // %__threwValue.val = __threwValue; 652 // if (%__THREW__.val != 0 & %__threwValue.val != 0) { 653 // %label = testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize); 654 // if (%label == 0) 655 // emscripten_longjmp(%__THREW__.val, %__threwValue.val); 656 // setTempRet0(%__threwValue.val); 657 // } else { 658 // %label = -1; 659 // } 660 // %longjmp_result = getTempRet0(); 661 // 662 // As output parameters. returns %label, %longjmp_result, and the BB the last 663 // instruction (%longjmp_result = ...) is in. 664 void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp( 665 BasicBlock *BB, DebugLoc DL, Value *Threw, Value *SetjmpTable, 666 Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult, 667 BasicBlock *&CallEmLongjmpBB, PHINode *&CallEmLongjmpBBThrewPHI, 668 PHINode *&CallEmLongjmpBBThrewValuePHI, BasicBlock *&EndBB) { 669 Function *F = BB->getParent(); 670 Module *M = F->getParent(); 671 LLVMContext &C = M->getContext(); 672 IRBuilder<> IRB(C); 673 IRB.SetCurrentDebugLocation(DL); 674 675 // if (%__THREW__.val != 0 & %__threwValue.val != 0) 676 IRB.SetInsertPoint(BB); 677 BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F); 678 BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F); 679 BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F); 680 Value *ThrewCmp = IRB.CreateICmpNE(Threw, getAddrSizeInt(M, 0)); 681 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV, 682 ThrewValueGV->getName() + ".val"); 683 Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0)); 684 Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1"); 685 IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1); 686 687 // Generate call.em.longjmp BB once and share it within the function 688 if (!CallEmLongjmpBB) { 689 // emscripten_longjmp(%__THREW__.val, %__threwValue.val); 690 CallEmLongjmpBB = BasicBlock::Create(C, "call.em.longjmp", F); 691 IRB.SetInsertPoint(CallEmLongjmpBB); 692 CallEmLongjmpBBThrewPHI = IRB.CreatePHI(getAddrIntType(M), 4, "threw.phi"); 693 CallEmLongjmpBBThrewValuePHI = 694 IRB.CreatePHI(IRB.getInt32Ty(), 4, "threwvalue.phi"); 695 CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1); 696 CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1); 697 IRB.CreateCall(EmLongjmpF, 698 {CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI}); 699 IRB.CreateUnreachable(); 700 } else { 701 CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1); 702 CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1); 703 } 704 705 // %label = testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize); 706 // if (%label == 0) 707 IRB.SetInsertPoint(ThenBB1); 708 BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F); 709 Value *ThrewPtr = 710 IRB.CreateIntToPtr(Threw, getAddrPtrType(M), Threw->getName() + ".p"); 711 Value *LoadedThrew = IRB.CreateLoad(getAddrIntType(M), ThrewPtr, 712 ThrewPtr->getName() + ".loaded"); 713 Value *ThenLabel = IRB.CreateCall( 714 TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label"); 715 Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0)); 716 IRB.CreateCondBr(Cmp2, CallEmLongjmpBB, EndBB2); 717 718 // setTempRet0(%__threwValue.val); 719 IRB.SetInsertPoint(EndBB2); 720 IRB.CreateCall(SetTempRet0F, ThrewValue); 721 IRB.CreateBr(EndBB1); 722 723 IRB.SetInsertPoint(ElseBB1); 724 IRB.CreateBr(EndBB1); 725 726 // longjmp_result = getTempRet0(); 727 IRB.SetInsertPoint(EndBB1); 728 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label"); 729 LabelPHI->addIncoming(ThenLabel, EndBB2); 730 731 LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1); 732 733 // Output parameter assignment 734 Label = LabelPHI; 735 EndBB = EndBB1; 736 LongjmpResult = IRB.CreateCall(GetTempRet0F, None, "longjmp_result"); 737 } 738 739 void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) { 740 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); 741 DT.recalculate(F); // CFG has been changed 742 743 SSAUpdaterBulk SSA; 744 for (BasicBlock &BB : F) { 745 for (Instruction &I : BB) { 746 unsigned VarID = SSA.AddVariable(I.getName(), I.getType()); 747 // If a value is defined by an invoke instruction, it is only available in 748 // its normal destination and not in its unwind destination. 749 if (auto *II = dyn_cast<InvokeInst>(&I)) 750 SSA.AddAvailableValue(VarID, II->getNormalDest(), II); 751 else 752 SSA.AddAvailableValue(VarID, &BB, &I); 753 for (auto &U : I.uses()) { 754 auto *User = cast<Instruction>(U.getUser()); 755 if (auto *UserPN = dyn_cast<PHINode>(User)) 756 if (UserPN->getIncomingBlock(U) == &BB) 757 continue; 758 if (DT.dominates(&I, User)) 759 continue; 760 SSA.AddUse(VarID, &U); 761 } 762 } 763 } 764 SSA.RewriteAllUses(&DT); 765 } 766 767 // Replace uses of longjmp with a new longjmp function in Emscripten library. 768 // In Emscripten SjLj, the new function is 769 // void emscripten_longjmp(uintptr_t, i32) 770 // In Wasm SjLj, the new function is 771 // void __wasm_longjmp(i8*, i32) 772 // Because the original libc longjmp function takes (jmp_buf*, i32), we need a 773 // ptrtoint/bitcast instruction here to make the type match. jmp_buf* will 774 // eventually be lowered to i32/i64 in the wasm backend. 775 void WebAssemblyLowerEmscriptenEHSjLj::replaceLongjmpWith(Function *LongjmpF, 776 Function *NewF) { 777 assert(NewF == EmLongjmpF || NewF == WasmLongjmpF); 778 Module *M = LongjmpF->getParent(); 779 SmallVector<CallInst *, 8> ToErase; 780 LLVMContext &C = LongjmpF->getParent()->getContext(); 781 IRBuilder<> IRB(C); 782 783 // For calls to longjmp, replace it with emscripten_longjmp/__wasm_longjmp and 784 // cast its first argument (jmp_buf*) appropriately 785 for (User *U : LongjmpF->users()) { 786 auto *CI = dyn_cast<CallInst>(U); 787 if (CI && CI->getCalledFunction() == LongjmpF) { 788 IRB.SetInsertPoint(CI); 789 Value *Env = nullptr; 790 if (NewF == EmLongjmpF) 791 Env = 792 IRB.CreatePtrToInt(CI->getArgOperand(0), getAddrIntType(M), "env"); 793 else // WasmLongjmpF 794 Env = 795 IRB.CreateBitCast(CI->getArgOperand(0), IRB.getInt8PtrTy(), "env"); 796 IRB.CreateCall(NewF, {Env, CI->getArgOperand(1)}); 797 ToErase.push_back(CI); 798 } 799 } 800 for (auto *I : ToErase) 801 I->eraseFromParent(); 802 803 // If we have any remaining uses of longjmp's function pointer, replace it 804 // with (void(*)(jmp_buf*, int))emscripten_longjmp / __wasm_longjmp. 805 if (!LongjmpF->uses().empty()) { 806 Value *NewLongjmp = 807 IRB.CreateBitCast(NewF, LongjmpF->getType(), "longjmp.cast"); 808 LongjmpF->replaceAllUsesWith(NewLongjmp); 809 } 810 } 811 812 static bool containsLongjmpableCalls(const Function *F) { 813 for (const auto &BB : *F) 814 for (const auto &I : BB) 815 if (const auto *CB = dyn_cast<CallBase>(&I)) 816 if (canLongjmp(CB->getCalledOperand())) 817 return true; 818 return false; 819 } 820 821 // When a function contains a setjmp call but not other calls that can longjmp, 822 // we don't do setjmp transformation for that setjmp. But we need to convert the 823 // setjmp calls into "i32 0" so they don't cause link time errors. setjmp always 824 // returns 0 when called directly. 825 static void nullifySetjmp(Function *F) { 826 Module &M = *F->getParent(); 827 IRBuilder<> IRB(M.getContext()); 828 Function *SetjmpF = M.getFunction("setjmp"); 829 SmallVector<Instruction *, 1> ToErase; 830 831 for (User *U : SetjmpF->users()) { 832 auto *CI = dyn_cast<CallInst>(U); 833 // FIXME 'invoke' to setjmp can happen when we use Wasm EH + Wasm SjLj, but 834 // we don't support two being used together yet. 835 if (!CI) 836 report_fatal_error("Wasm EH + Wasm SjLj is not fully supported yet"); 837 BasicBlock *BB = CI->getParent(); 838 if (BB->getParent() != F) // in other function 839 continue; 840 ToErase.push_back(CI); 841 CI->replaceAllUsesWith(IRB.getInt32(0)); 842 } 843 for (auto *I : ToErase) 844 I->eraseFromParent(); 845 } 846 847 bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) { 848 LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n"); 849 850 LLVMContext &C = M.getContext(); 851 IRBuilder<> IRB(C); 852 853 Function *SetjmpF = M.getFunction("setjmp"); 854 Function *LongjmpF = M.getFunction("longjmp"); 855 856 // In some platforms _setjmp and _longjmp are used instead. Change these to 857 // use setjmp/longjmp instead, because we later detect these functions by 858 // their names. 859 Function *SetjmpF2 = M.getFunction("_setjmp"); 860 Function *LongjmpF2 = M.getFunction("_longjmp"); 861 if (SetjmpF2) { 862 if (SetjmpF) { 863 if (SetjmpF->getFunctionType() != SetjmpF2->getFunctionType()) 864 report_fatal_error("setjmp and _setjmp have different function types"); 865 } else { 866 SetjmpF = Function::Create(SetjmpF2->getFunctionType(), 867 GlobalValue::ExternalLinkage, "setjmp", M); 868 } 869 SetjmpF2->replaceAllUsesWith(SetjmpF); 870 } 871 if (LongjmpF2) { 872 if (LongjmpF) { 873 if (LongjmpF->getFunctionType() != LongjmpF2->getFunctionType()) 874 report_fatal_error( 875 "longjmp and _longjmp have different function types"); 876 } else { 877 LongjmpF = Function::Create(LongjmpF2->getFunctionType(), 878 GlobalValue::ExternalLinkage, "setjmp", M); 879 } 880 LongjmpF2->replaceAllUsesWith(LongjmpF); 881 } 882 883 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>(); 884 assert(TPC && "Expected a TargetPassConfig"); 885 auto &TM = TPC->getTM<WebAssemblyTargetMachine>(); 886 887 // Declare (or get) global variables __THREW__, __threwValue, and 888 // getTempRet0/setTempRet0 function which are used in common for both 889 // exception handling and setjmp/longjmp handling 890 ThrewGV = getGlobalVariable(M, getAddrIntType(&M), TM, "__THREW__"); 891 ThrewValueGV = getGlobalVariable(M, IRB.getInt32Ty(), TM, "__threwValue"); 892 GetTempRet0F = getEmscriptenFunction( 893 FunctionType::get(IRB.getInt32Ty(), false), "getTempRet0", &M); 894 SetTempRet0F = getEmscriptenFunction( 895 FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false), 896 "setTempRet0", &M); 897 GetTempRet0F->setDoesNotThrow(); 898 SetTempRet0F->setDoesNotThrow(); 899 900 bool Changed = false; 901 902 // Function registration for exception handling 903 if (EnableEmEH) { 904 // Register __resumeException function 905 FunctionType *ResumeFTy = 906 FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false); 907 ResumeF = getEmscriptenFunction(ResumeFTy, "__resumeException", &M); 908 ResumeF->addFnAttr(Attribute::NoReturn); 909 910 // Register llvm_eh_typeid_for function 911 FunctionType *EHTypeIDTy = 912 FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false); 913 EHTypeIDF = getEmscriptenFunction(EHTypeIDTy, "llvm_eh_typeid_for", &M); 914 } 915 916 // Functions that contains calls to setjmp but don't have other longjmpable 917 // calls within them. 918 SmallPtrSet<Function *, 4> SetjmpUsersToNullify; 919 920 if ((EnableEmSjLj || EnableWasmSjLj) && SetjmpF) { 921 // Precompute setjmp users 922 for (User *U : SetjmpF->users()) { 923 if (auto *CB = dyn_cast<CallBase>(U)) { 924 auto *UserF = CB->getFunction(); 925 // If a function that calls setjmp does not contain any other calls that 926 // can longjmp, we don't need to do any transformation on that function, 927 // so can ignore it 928 if (containsLongjmpableCalls(UserF)) 929 SetjmpUsers.insert(UserF); 930 else 931 SetjmpUsersToNullify.insert(UserF); 932 } else { 933 std::string S; 934 raw_string_ostream SS(S); 935 SS << *U; 936 report_fatal_error(Twine("Indirect use of setjmp is not supported: ") + 937 SS.str()); 938 } 939 } 940 } 941 942 bool SetjmpUsed = SetjmpF && !SetjmpUsers.empty(); 943 bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty(); 944 DoSjLj = (EnableEmSjLj | EnableWasmSjLj) && (SetjmpUsed || LongjmpUsed); 945 946 // Function registration and data pre-gathering for setjmp/longjmp handling 947 if (DoSjLj) { 948 assert(EnableEmSjLj || EnableWasmSjLj); 949 if (EnableEmSjLj) { 950 // Register emscripten_longjmp function 951 FunctionType *FTy = FunctionType::get( 952 IRB.getVoidTy(), {getAddrIntType(&M), IRB.getInt32Ty()}, false); 953 EmLongjmpF = getEmscriptenFunction(FTy, "emscripten_longjmp", &M); 954 EmLongjmpF->addFnAttr(Attribute::NoReturn); 955 } else { // EnableWasmSjLj 956 // Register __wasm_longjmp function, which calls __builtin_wasm_longjmp. 957 FunctionType *FTy = FunctionType::get( 958 IRB.getVoidTy(), {IRB.getInt8PtrTy(), IRB.getInt32Ty()}, false); 959 WasmLongjmpF = getEmscriptenFunction(FTy, "__wasm_longjmp", &M); 960 WasmLongjmpF->addFnAttr(Attribute::NoReturn); 961 } 962 963 if (SetjmpF) { 964 // Register saveSetjmp function 965 FunctionType *SetjmpFTy = SetjmpF->getFunctionType(); 966 FunctionType *FTy = 967 FunctionType::get(Type::getInt32PtrTy(C), 968 {SetjmpFTy->getParamType(0), IRB.getInt32Ty(), 969 Type::getInt32PtrTy(C), IRB.getInt32Ty()}, 970 false); 971 SaveSetjmpF = getEmscriptenFunction(FTy, "saveSetjmp", &M); 972 973 // Register testSetjmp function 974 FTy = FunctionType::get( 975 IRB.getInt32Ty(), 976 {getAddrIntType(&M), Type::getInt32PtrTy(C), IRB.getInt32Ty()}, 977 false); 978 TestSetjmpF = getEmscriptenFunction(FTy, "testSetjmp", &M); 979 980 // wasm.catch() will be lowered down to wasm 'catch' instruction in 981 // instruction selection. 982 CatchF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_catch); 983 // Type for struct __WasmLongjmpArgs 984 LongjmpArgsTy = StructType::get(IRB.getInt8PtrTy(), // env 985 IRB.getInt32Ty() // val 986 ); 987 } 988 } 989 990 // Exception handling transformation 991 if (EnableEmEH) { 992 for (Function &F : M) { 993 if (F.isDeclaration()) 994 continue; 995 Changed |= runEHOnFunction(F); 996 } 997 } 998 999 // Setjmp/longjmp handling transformation 1000 if (DoSjLj) { 1001 Changed = true; // We have setjmp or longjmp somewhere 1002 if (LongjmpF) 1003 replaceLongjmpWith(LongjmpF, EnableEmSjLj ? EmLongjmpF : WasmLongjmpF); 1004 // Only traverse functions that uses setjmp in order not to insert 1005 // unnecessary prep / cleanup code in every function 1006 if (SetjmpF) 1007 for (Function *F : SetjmpUsers) 1008 runSjLjOnFunction(*F); 1009 } 1010 1011 // Replace unnecessary setjmp calls with 0 1012 if ((EnableEmSjLj || EnableWasmSjLj) && !SetjmpUsersToNullify.empty()) { 1013 Changed = true; 1014 assert(SetjmpF); 1015 for (Function *F : SetjmpUsersToNullify) 1016 nullifySetjmp(F); 1017 } 1018 1019 if (!Changed) { 1020 // Delete unused global variables and functions 1021 if (ResumeF) 1022 ResumeF->eraseFromParent(); 1023 if (EHTypeIDF) 1024 EHTypeIDF->eraseFromParent(); 1025 if (EmLongjmpF) 1026 EmLongjmpF->eraseFromParent(); 1027 if (SaveSetjmpF) 1028 SaveSetjmpF->eraseFromParent(); 1029 if (TestSetjmpF) 1030 TestSetjmpF->eraseFromParent(); 1031 return false; 1032 } 1033 1034 return true; 1035 } 1036 1037 bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) { 1038 Module &M = *F.getParent(); 1039 LLVMContext &C = F.getContext(); 1040 IRBuilder<> IRB(C); 1041 bool Changed = false; 1042 SmallVector<Instruction *, 64> ToErase; 1043 SmallPtrSet<LandingPadInst *, 32> LandingPads; 1044 1045 // rethrow.longjmp BB that will be shared within the function. 1046 BasicBlock *RethrowLongjmpBB = nullptr; 1047 // PHI node for the loaded value of __THREW__ global variable in 1048 // rethrow.longjmp BB 1049 PHINode *RethrowLongjmpBBThrewPHI = nullptr; 1050 1051 for (BasicBlock &BB : F) { 1052 auto *II = dyn_cast<InvokeInst>(BB.getTerminator()); 1053 if (!II) 1054 continue; 1055 Changed = true; 1056 LandingPads.insert(II->getLandingPadInst()); 1057 IRB.SetInsertPoint(II); 1058 1059 const Value *Callee = II->getCalledOperand(); 1060 bool NeedInvoke = supportsException(&F) && canThrow(Callee); 1061 if (NeedInvoke) { 1062 // Wrap invoke with invoke wrapper and generate preamble/postamble 1063 Value *Threw = wrapInvoke(II); 1064 ToErase.push_back(II); 1065 1066 // If setjmp/longjmp handling is enabled, the thrown value can be not an 1067 // exception but a longjmp. If the current function contains calls to 1068 // setjmp, it will be appropriately handled in runSjLjOnFunction. But even 1069 // if the function does not contain setjmp calls, we shouldn't silently 1070 // ignore longjmps; we should rethrow them so they can be correctly 1071 // handled in somewhere up the call chain where setjmp is. __THREW__'s 1072 // value is 0 when nothing happened, 1 when an exception is thrown, and 1073 // other values when longjmp is thrown. 1074 // 1075 // if (%__THREW__.val == 0 || %__THREW__.val == 1) 1076 // goto %tail 1077 // else 1078 // goto %longjmp.rethrow 1079 // 1080 // rethrow.longjmp: ;; This is longjmp. Rethrow it 1081 // %__threwValue.val = __threwValue 1082 // emscripten_longjmp(%__THREW__.val, %__threwValue.val); 1083 // 1084 // tail: ;; Nothing happened or an exception is thrown 1085 // ... Continue exception handling ... 1086 if (DoSjLj && EnableEmSjLj && !SetjmpUsers.count(&F) && 1087 canLongjmp(Callee)) { 1088 // Create longjmp.rethrow BB once and share it within the function 1089 if (!RethrowLongjmpBB) { 1090 RethrowLongjmpBB = BasicBlock::Create(C, "rethrow.longjmp", &F); 1091 IRB.SetInsertPoint(RethrowLongjmpBB); 1092 RethrowLongjmpBBThrewPHI = 1093 IRB.CreatePHI(getAddrIntType(&M), 4, "threw.phi"); 1094 RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB); 1095 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV, 1096 ThrewValueGV->getName() + ".val"); 1097 IRB.CreateCall(EmLongjmpF, {RethrowLongjmpBBThrewPHI, ThrewValue}); 1098 IRB.CreateUnreachable(); 1099 } else { 1100 RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB); 1101 } 1102 1103 IRB.SetInsertPoint(II); // Restore the insert point back 1104 BasicBlock *Tail = BasicBlock::Create(C, "tail", &F); 1105 Value *CmpEqOne = 1106 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one"); 1107 Value *CmpEqZero = 1108 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 0), "cmp.eq.zero"); 1109 Value *Or = IRB.CreateOr(CmpEqZero, CmpEqOne, "or"); 1110 IRB.CreateCondBr(Or, Tail, RethrowLongjmpBB); 1111 IRB.SetInsertPoint(Tail); 1112 BB.replaceSuccessorsPhiUsesWith(&BB, Tail); 1113 } 1114 1115 // Insert a branch based on __THREW__ variable 1116 Value *Cmp = IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp"); 1117 IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest()); 1118 1119 } else { 1120 // This can't throw, and we don't need this invoke, just replace it with a 1121 // call+branch 1122 changeToCall(II); 1123 } 1124 } 1125 1126 // Process resume instructions 1127 for (BasicBlock &BB : F) { 1128 // Scan the body of the basic block for resumes 1129 for (Instruction &I : BB) { 1130 auto *RI = dyn_cast<ResumeInst>(&I); 1131 if (!RI) 1132 continue; 1133 Changed = true; 1134 1135 // Split the input into legal values 1136 Value *Input = RI->getValue(); 1137 IRB.SetInsertPoint(RI); 1138 Value *Low = IRB.CreateExtractValue(Input, 0, "low"); 1139 // Create a call to __resumeException function 1140 IRB.CreateCall(ResumeF, {Low}); 1141 // Add a terminator to the block 1142 IRB.CreateUnreachable(); 1143 ToErase.push_back(RI); 1144 } 1145 } 1146 1147 // Process llvm.eh.typeid.for intrinsics 1148 for (BasicBlock &BB : F) { 1149 for (Instruction &I : BB) { 1150 auto *CI = dyn_cast<CallInst>(&I); 1151 if (!CI) 1152 continue; 1153 const Function *Callee = CI->getCalledFunction(); 1154 if (!Callee) 1155 continue; 1156 if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for) 1157 continue; 1158 Changed = true; 1159 1160 IRB.SetInsertPoint(CI); 1161 CallInst *NewCI = 1162 IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid"); 1163 CI->replaceAllUsesWith(NewCI); 1164 ToErase.push_back(CI); 1165 } 1166 } 1167 1168 // Look for orphan landingpads, can occur in blocks with no predecessors 1169 for (BasicBlock &BB : F) { 1170 Instruction *I = BB.getFirstNonPHI(); 1171 if (auto *LPI = dyn_cast<LandingPadInst>(I)) 1172 LandingPads.insert(LPI); 1173 } 1174 Changed |= !LandingPads.empty(); 1175 1176 // Handle all the landingpad for this function together, as multiple invokes 1177 // may share a single lp 1178 for (LandingPadInst *LPI : LandingPads) { 1179 IRB.SetInsertPoint(LPI); 1180 SmallVector<Value *, 16> FMCArgs; 1181 for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) { 1182 Constant *Clause = LPI->getClause(I); 1183 // TODO Handle filters (= exception specifications). 1184 // https://bugs.llvm.org/show_bug.cgi?id=50396 1185 if (LPI->isCatch(I)) 1186 FMCArgs.push_back(Clause); 1187 } 1188 1189 // Create a call to __cxa_find_matching_catch_N function 1190 Function *FMCF = getFindMatchingCatch(M, FMCArgs.size()); 1191 CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc"); 1192 Value *Undef = UndefValue::get(LPI->getType()); 1193 Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0"); 1194 Value *TempRet0 = IRB.CreateCall(GetTempRet0F, None, "tempret0"); 1195 Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1"); 1196 1197 LPI->replaceAllUsesWith(Pair1); 1198 ToErase.push_back(LPI); 1199 } 1200 1201 // Erase everything we no longer need in this function 1202 for (Instruction *I : ToErase) 1203 I->eraseFromParent(); 1204 1205 return Changed; 1206 } 1207 1208 // This tries to get debug info from the instruction before which a new 1209 // instruction will be inserted, and if there's no debug info in that 1210 // instruction, tries to get the info instead from the previous instruction (if 1211 // any). If none of these has debug info and a DISubprogram is provided, it 1212 // creates a dummy debug info with the first line of the function, because IR 1213 // verifier requires all inlinable callsites should have debug info when both a 1214 // caller and callee have DISubprogram. If none of these conditions are met, 1215 // returns empty info. 1216 static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore, 1217 DISubprogram *SP) { 1218 assert(InsertBefore); 1219 if (InsertBefore->getDebugLoc()) 1220 return InsertBefore->getDebugLoc(); 1221 const Instruction *Prev = InsertBefore->getPrevNode(); 1222 if (Prev && Prev->getDebugLoc()) 1223 return Prev->getDebugLoc(); 1224 if (SP) 1225 return DILocation::get(SP->getContext(), SP->getLine(), 1, SP); 1226 return DebugLoc(); 1227 } 1228 1229 bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) { 1230 assert(EnableEmSjLj || EnableWasmSjLj); 1231 Module &M = *F.getParent(); 1232 LLVMContext &C = F.getContext(); 1233 IRBuilder<> IRB(C); 1234 SmallVector<Instruction *, 64> ToErase; 1235 // Vector of %setjmpTable values 1236 SmallVector<Instruction *, 4> SetjmpTableInsts; 1237 // Vector of %setjmpTableSize values 1238 SmallVector<Instruction *, 4> SetjmpTableSizeInsts; 1239 1240 // Setjmp preparation 1241 1242 // This instruction effectively means %setjmpTableSize = 4. 1243 // We create this as an instruction intentionally, and we don't want to fold 1244 // this instruction to a constant 4, because this value will be used in 1245 // SSAUpdater.AddAvailableValue(...) later. 1246 BasicBlock *Entry = &F.getEntryBlock(); 1247 DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram()); 1248 SplitBlock(Entry, &*Entry->getFirstInsertionPt()); 1249 1250 BinaryOperator *SetjmpTableSize = 1251 BinaryOperator::Create(Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), 1252 "setjmpTableSize", Entry->getTerminator()); 1253 SetjmpTableSize->setDebugLoc(FirstDL); 1254 // setjmpTable = (int *) malloc(40); 1255 Instruction *SetjmpTable = CallInst::CreateMalloc( 1256 SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40), 1257 nullptr, nullptr, "setjmpTable"); 1258 SetjmpTable->setDebugLoc(FirstDL); 1259 // CallInst::CreateMalloc may return a bitcast instruction if the result types 1260 // mismatch. We need to set the debug loc for the original call too. 1261 auto *MallocCall = SetjmpTable->stripPointerCasts(); 1262 if (auto *MallocCallI = dyn_cast<Instruction>(MallocCall)) { 1263 MallocCallI->setDebugLoc(FirstDL); 1264 } 1265 // setjmpTable[0] = 0; 1266 IRB.SetInsertPoint(SetjmpTableSize); 1267 IRB.CreateStore(IRB.getInt32(0), SetjmpTable); 1268 SetjmpTableInsts.push_back(SetjmpTable); 1269 SetjmpTableSizeInsts.push_back(SetjmpTableSize); 1270 1271 // Setjmp transformation 1272 SmallVector<PHINode *, 4> SetjmpRetPHIs; 1273 Function *SetjmpF = M.getFunction("setjmp"); 1274 for (User *U : SetjmpF->users()) { 1275 auto *CI = dyn_cast<CallInst>(U); 1276 // FIXME 'invoke' to setjmp can happen when we use Wasm EH + Wasm SjLj, but 1277 // we don't support two being used together yet. 1278 if (!CI) 1279 report_fatal_error("Wasm EH + Wasm SjLj is not fully supported yet"); 1280 BasicBlock *BB = CI->getParent(); 1281 if (BB->getParent() != &F) // in other function 1282 continue; 1283 1284 // The tail is everything right after the call, and will be reached once 1285 // when setjmp is called, and later when longjmp returns to the setjmp 1286 BasicBlock *Tail = SplitBlock(BB, CI->getNextNode()); 1287 // Add a phi to the tail, which will be the output of setjmp, which 1288 // indicates if this is the first call or a longjmp back. The phi directly 1289 // uses the right value based on where we arrive from 1290 IRB.SetInsertPoint(Tail->getFirstNonPHI()); 1291 PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret"); 1292 1293 // setjmp initial call returns 0 1294 SetjmpRet->addIncoming(IRB.getInt32(0), BB); 1295 // The proper output is now this, not the setjmp call itself 1296 CI->replaceAllUsesWith(SetjmpRet); 1297 // longjmp returns to the setjmp will add themselves to this phi 1298 SetjmpRetPHIs.push_back(SetjmpRet); 1299 1300 // Fix call target 1301 // Our index in the function is our place in the array + 1 to avoid index 1302 // 0, because index 0 means the longjmp is not ours to handle. 1303 IRB.SetInsertPoint(CI); 1304 Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()), 1305 SetjmpTable, SetjmpTableSize}; 1306 Instruction *NewSetjmpTable = 1307 IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable"); 1308 Instruction *NewSetjmpTableSize = 1309 IRB.CreateCall(GetTempRet0F, None, "setjmpTableSize"); 1310 SetjmpTableInsts.push_back(NewSetjmpTable); 1311 SetjmpTableSizeInsts.push_back(NewSetjmpTableSize); 1312 ToErase.push_back(CI); 1313 } 1314 1315 // Handle longjmpable calls. 1316 if (EnableEmSjLj) 1317 handleLongjmpableCallsForEmscriptenSjLj( 1318 F, SetjmpTableInsts, SetjmpTableSizeInsts, SetjmpRetPHIs); 1319 else // EnableWasmSjLj 1320 handleLongjmpableCallsForWasmSjLj(F, SetjmpTableInsts, SetjmpTableSizeInsts, 1321 SetjmpRetPHIs); 1322 1323 // Erase everything we no longer need in this function 1324 for (Instruction *I : ToErase) 1325 I->eraseFromParent(); 1326 1327 // Free setjmpTable buffer before each return instruction + function-exiting 1328 // call 1329 SmallVector<Instruction *, 16> ExitingInsts; 1330 for (BasicBlock &BB : F) { 1331 Instruction *TI = BB.getTerminator(); 1332 if (isa<ReturnInst>(TI)) 1333 ExitingInsts.push_back(TI); 1334 // Any 'call' instruction with 'noreturn' attribute exits the function at 1335 // this point. If this throws but unwinds to another EH pad within this 1336 // function instead of exiting, this would have been an 'invoke', which 1337 // happens if we use Wasm EH or Wasm SjLJ. 1338 for (auto &I : BB) { 1339 if (auto *CI = dyn_cast<CallInst>(&I)) { 1340 bool IsNoReturn = CI->hasFnAttr(Attribute::NoReturn); 1341 if (Function *CalleeF = CI->getCalledFunction()) 1342 IsNoReturn |= CalleeF->hasFnAttribute(Attribute::NoReturn); 1343 if (IsNoReturn) 1344 ExitingInsts.push_back(&I); 1345 } 1346 } 1347 } 1348 for (auto *I : ExitingInsts) { 1349 DebugLoc DL = getOrCreateDebugLoc(I, F.getSubprogram()); 1350 // If this existing instruction is a call within a catchpad, we should add 1351 // it as "funclet" to the operand bundle of 'free' call 1352 SmallVector<OperandBundleDef, 1> Bundles; 1353 if (auto *CB = dyn_cast<CallBase>(I)) 1354 if (auto Bundle = CB->getOperandBundle(LLVMContext::OB_funclet)) 1355 Bundles.push_back(OperandBundleDef(*Bundle)); 1356 auto *Free = CallInst::CreateFree(SetjmpTable, Bundles, I); 1357 Free->setDebugLoc(DL); 1358 // CallInst::CreateFree may create a bitcast instruction if its argument 1359 // types mismatch. We need to set the debug loc for the bitcast too. 1360 if (auto *FreeCallI = dyn_cast<CallInst>(Free)) { 1361 if (auto *BitCastI = dyn_cast<BitCastInst>(FreeCallI->getArgOperand(0))) 1362 BitCastI->setDebugLoc(DL); 1363 } 1364 } 1365 1366 // Every call to saveSetjmp can change setjmpTable and setjmpTableSize 1367 // (when buffer reallocation occurs) 1368 // entry: 1369 // setjmpTableSize = 4; 1370 // setjmpTable = (int *) malloc(40); 1371 // setjmpTable[0] = 0; 1372 // ... 1373 // somebb: 1374 // setjmpTable = saveSetjmp(env, label, setjmpTable, setjmpTableSize); 1375 // setjmpTableSize = getTempRet0(); 1376 // So we need to make sure the SSA for these variables is valid so that every 1377 // saveSetjmp and testSetjmp calls have the correct arguments. 1378 SSAUpdater SetjmpTableSSA; 1379 SSAUpdater SetjmpTableSizeSSA; 1380 SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable"); 1381 SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize"); 1382 for (Instruction *I : SetjmpTableInsts) 1383 SetjmpTableSSA.AddAvailableValue(I->getParent(), I); 1384 for (Instruction *I : SetjmpTableSizeInsts) 1385 SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I); 1386 1387 for (auto &U : make_early_inc_range(SetjmpTable->uses())) 1388 if (auto *I = dyn_cast<Instruction>(U.getUser())) 1389 if (I->getParent() != Entry) 1390 SetjmpTableSSA.RewriteUse(U); 1391 for (auto &U : make_early_inc_range(SetjmpTableSize->uses())) 1392 if (auto *I = dyn_cast<Instruction>(U.getUser())) 1393 if (I->getParent() != Entry) 1394 SetjmpTableSizeSSA.RewriteUse(U); 1395 1396 // Finally, our modifications to the cfg can break dominance of SSA variables. 1397 // For example, in this code, 1398 // if (x()) { .. setjmp() .. } 1399 // if (y()) { .. longjmp() .. } 1400 // We must split the longjmp block, and it can jump into the block splitted 1401 // from setjmp one. But that means that when we split the setjmp block, it's 1402 // first part no longer dominates its second part - there is a theoretically 1403 // possible control flow path where x() is false, then y() is true and we 1404 // reach the second part of the setjmp block, without ever reaching the first 1405 // part. So, we rebuild SSA form here. 1406 rebuildSSA(F); 1407 return true; 1408 } 1409 1410 // Update each call that can longjmp so it can return to the corresponding 1411 // setjmp. Refer to 4) of "Emscripten setjmp/longjmp handling" section in the 1412 // comments at top of the file for details. 1413 void WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForEmscriptenSjLj( 1414 Function &F, InstVector &SetjmpTableInsts, InstVector &SetjmpTableSizeInsts, 1415 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) { 1416 Module &M = *F.getParent(); 1417 LLVMContext &C = F.getContext(); 1418 IRBuilder<> IRB(C); 1419 SmallVector<Instruction *, 64> ToErase; 1420 1421 // We need to pass setjmpTable and setjmpTableSize to testSetjmp function. 1422 // These values are defined in the beginning of the function and also in each 1423 // setjmp callsite, but we don't know which values we should use at this 1424 // point. So here we arbitraily use the ones defined in the beginning of the 1425 // function, and SSAUpdater will later update them to the correct values. 1426 Instruction *SetjmpTable = *SetjmpTableInsts.begin(); 1427 Instruction *SetjmpTableSize = *SetjmpTableSizeInsts.begin(); 1428 1429 // call.em.longjmp BB that will be shared within the function. 1430 BasicBlock *CallEmLongjmpBB = nullptr; 1431 // PHI node for the loaded value of __THREW__ global variable in 1432 // call.em.longjmp BB 1433 PHINode *CallEmLongjmpBBThrewPHI = nullptr; 1434 // PHI node for the loaded value of __threwValue global variable in 1435 // call.em.longjmp BB 1436 PHINode *CallEmLongjmpBBThrewValuePHI = nullptr; 1437 // rethrow.exn BB that will be shared within the function. 1438 BasicBlock *RethrowExnBB = nullptr; 1439 1440 // Because we are creating new BBs while processing and don't want to make 1441 // all these newly created BBs candidates again for longjmp processing, we 1442 // first make the vector of candidate BBs. 1443 std::vector<BasicBlock *> BBs; 1444 for (BasicBlock &BB : F) 1445 BBs.push_back(&BB); 1446 1447 // BBs.size() will change within the loop, so we query it every time 1448 for (unsigned I = 0; I < BBs.size(); I++) { 1449 BasicBlock *BB = BBs[I]; 1450 for (Instruction &I : *BB) { 1451 if (isa<InvokeInst>(&I)) 1452 report_fatal_error("When using Wasm EH with Emscripten SjLj, there is " 1453 "a restriction that `setjmp` function call and " 1454 "exception cannot be used within the same function"); 1455 auto *CI = dyn_cast<CallInst>(&I); 1456 if (!CI) 1457 continue; 1458 1459 const Value *Callee = CI->getCalledOperand(); 1460 if (!canLongjmp(Callee)) 1461 continue; 1462 if (isEmAsmCall(Callee)) 1463 report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " + 1464 F.getName() + 1465 ". Please consider using EM_JS, or move the " 1466 "EM_ASM into another function.", 1467 false); 1468 1469 Value *Threw = nullptr; 1470 BasicBlock *Tail; 1471 if (Callee->getName().startswith("__invoke_")) { 1472 // If invoke wrapper has already been generated for this call in 1473 // previous EH phase, search for the load instruction 1474 // %__THREW__.val = __THREW__; 1475 // in postamble after the invoke wrapper call 1476 LoadInst *ThrewLI = nullptr; 1477 StoreInst *ThrewResetSI = nullptr; 1478 for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end(); 1479 I != IE; ++I) { 1480 if (auto *LI = dyn_cast<LoadInst>(I)) 1481 if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand())) 1482 if (GV == ThrewGV) { 1483 Threw = ThrewLI = LI; 1484 break; 1485 } 1486 } 1487 // Search for the store instruction after the load above 1488 // __THREW__ = 0; 1489 for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end(); 1490 I != IE; ++I) { 1491 if (auto *SI = dyn_cast<StoreInst>(I)) { 1492 if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) { 1493 if (GV == ThrewGV && 1494 SI->getValueOperand() == getAddrSizeInt(&M, 0)) { 1495 ThrewResetSI = SI; 1496 break; 1497 } 1498 } 1499 } 1500 } 1501 assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke"); 1502 assert(ThrewResetSI && "Cannot find __THREW__ store after invoke"); 1503 Tail = SplitBlock(BB, ThrewResetSI->getNextNode()); 1504 1505 } else { 1506 // Wrap call with invoke wrapper and generate preamble/postamble 1507 Threw = wrapInvoke(CI); 1508 ToErase.push_back(CI); 1509 Tail = SplitBlock(BB, CI->getNextNode()); 1510 1511 // If exception handling is enabled, the thrown value can be not a 1512 // longjmp but an exception, in which case we shouldn't silently ignore 1513 // exceptions; we should rethrow them. 1514 // __THREW__'s value is 0 when nothing happened, 1 when an exception is 1515 // thrown, other values when longjmp is thrown. 1516 // 1517 // if (%__THREW__.val == 1) 1518 // goto %eh.rethrow 1519 // else 1520 // goto %normal 1521 // 1522 // eh.rethrow: ;; Rethrow exception 1523 // %exn = call @__cxa_find_matching_catch_2() ;; Retrieve thrown ptr 1524 // __resumeException(%exn) 1525 // 1526 // normal: 1527 // <-- Insertion point. Will insert sjlj handling code from here 1528 // goto %tail 1529 // 1530 // tail: 1531 // ... 1532 if (supportsException(&F) && canThrow(Callee)) { 1533 // We will add a new conditional branch. So remove the branch created 1534 // when we split the BB 1535 ToErase.push_back(BB->getTerminator()); 1536 1537 // Generate rethrow.exn BB once and share it within the function 1538 if (!RethrowExnBB) { 1539 RethrowExnBB = BasicBlock::Create(C, "rethrow.exn", &F); 1540 IRB.SetInsertPoint(RethrowExnBB); 1541 CallInst *Exn = 1542 IRB.CreateCall(getFindMatchingCatch(M, 0), {}, "exn"); 1543 IRB.CreateCall(ResumeF, {Exn}); 1544 IRB.CreateUnreachable(); 1545 } 1546 1547 IRB.SetInsertPoint(CI); 1548 BasicBlock *NormalBB = BasicBlock::Create(C, "normal", &F); 1549 Value *CmpEqOne = 1550 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one"); 1551 IRB.CreateCondBr(CmpEqOne, RethrowExnBB, NormalBB); 1552 1553 IRB.SetInsertPoint(NormalBB); 1554 IRB.CreateBr(Tail); 1555 BB = NormalBB; // New insertion point to insert testSetjmp() 1556 } 1557 } 1558 1559 // We need to replace the terminator in Tail - SplitBlock makes BB go 1560 // straight to Tail, we need to check if a longjmp occurred, and go to the 1561 // right setjmp-tail if so 1562 ToErase.push_back(BB->getTerminator()); 1563 1564 // Generate a function call to testSetjmp function and preamble/postamble 1565 // code to figure out (1) whether longjmp occurred (2) if longjmp 1566 // occurred, which setjmp it corresponds to 1567 Value *Label = nullptr; 1568 Value *LongjmpResult = nullptr; 1569 BasicBlock *EndBB = nullptr; 1570 wrapTestSetjmp(BB, CI->getDebugLoc(), Threw, SetjmpTable, SetjmpTableSize, 1571 Label, LongjmpResult, CallEmLongjmpBB, 1572 CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI, 1573 EndBB); 1574 assert(Label && LongjmpResult && EndBB); 1575 1576 // Create switch instruction 1577 IRB.SetInsertPoint(EndBB); 1578 IRB.SetCurrentDebugLocation(EndBB->getInstList().back().getDebugLoc()); 1579 SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size()); 1580 // -1 means no longjmp happened, continue normally (will hit the default 1581 // switch case). 0 means a longjmp that is not ours to handle, needs a 1582 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid 1583 // 0). 1584 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) { 1585 SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent()); 1586 SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB); 1587 } 1588 1589 // We are splitting the block here, and must continue to find other calls 1590 // in the block - which is now split. so continue to traverse in the Tail 1591 BBs.push_back(Tail); 1592 } 1593 } 1594 1595 for (Instruction *I : ToErase) 1596 I->eraseFromParent(); 1597 } 1598 1599 // Create a catchpad in which we catch a longjmp's env and val arguments, test 1600 // if the longjmp corresponds to one of setjmps in the current function, and if 1601 // so, jump to the setjmp dispatch BB from which we go to one of post-setjmp 1602 // BBs. Refer to 4) of "Wasm setjmp/longjmp handling" section in the comments at 1603 // top of the file for details. 1604 void WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForWasmSjLj( 1605 Function &F, InstVector &SetjmpTableInsts, InstVector &SetjmpTableSizeInsts, 1606 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) { 1607 Module &M = *F.getParent(); 1608 LLVMContext &C = F.getContext(); 1609 IRBuilder<> IRB(C); 1610 1611 // A function with catchswitch/catchpad instruction should have a personality 1612 // function attached to it. Search for the wasm personality function, and if 1613 // it exists, use it, and if it doesn't, create a dummy personality function. 1614 // (SjLj is not going to call it anyway.) 1615 if (!F.hasPersonalityFn()) { 1616 StringRef PersName = getEHPersonalityName(EHPersonality::Wasm_CXX); 1617 FunctionType *PersType = 1618 FunctionType::get(IRB.getInt32Ty(), /* isVarArg */ true); 1619 Value *PersF = M.getOrInsertFunction(PersName, PersType).getCallee(); 1620 F.setPersonalityFn( 1621 cast<Constant>(IRB.CreateBitCast(PersF, IRB.getInt8PtrTy()))); 1622 } 1623 1624 // Use the entry BB's debugloc as a fallback 1625 BasicBlock *Entry = &F.getEntryBlock(); 1626 DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram()); 1627 IRB.SetCurrentDebugLocation(FirstDL); 1628 1629 // Arbitrarily use the ones defined in the beginning of the function. 1630 // SSAUpdater will later update them to the correct values. 1631 Instruction *SetjmpTable = *SetjmpTableInsts.begin(); 1632 Instruction *SetjmpTableSize = *SetjmpTableSizeInsts.begin(); 1633 1634 // Add setjmp.dispatch BB right after the entry block. Because we have 1635 // initialized setjmpTable/setjmpTableSize in the entry block and split the 1636 // rest into another BB, here 'OrigEntry' is the function's original entry 1637 // block before the transformation. 1638 // 1639 // entry: 1640 // setjmpTable / setjmpTableSize initialization 1641 // setjmp.dispatch: 1642 // switch will be inserted here later 1643 // entry.split: (OrigEntry) 1644 // the original function starts here 1645 BasicBlock *OrigEntry = Entry->getNextNode(); 1646 BasicBlock *SetjmpDispatchBB = 1647 BasicBlock::Create(C, "setjmp.dispatch", &F, OrigEntry); 1648 cast<BranchInst>(Entry->getTerminator())->setSuccessor(0, SetjmpDispatchBB); 1649 1650 // Create catch.dispatch.longjmp BB and a catchswitch instruction 1651 BasicBlock *CatchDispatchLongjmpBB = 1652 BasicBlock::Create(C, "catch.dispatch.longjmp", &F); 1653 IRB.SetInsertPoint(CatchDispatchLongjmpBB); 1654 CatchSwitchInst *CatchSwitchLongjmp = 1655 IRB.CreateCatchSwitch(ConstantTokenNone::get(C), nullptr, 1); 1656 1657 // Create catch.longjmp BB and a catchpad instruction 1658 BasicBlock *CatchLongjmpBB = BasicBlock::Create(C, "catch.longjmp", &F); 1659 CatchSwitchLongjmp->addHandler(CatchLongjmpBB); 1660 IRB.SetInsertPoint(CatchLongjmpBB); 1661 CatchPadInst *CatchPad = IRB.CreateCatchPad(CatchSwitchLongjmp, {}); 1662 1663 // Wasm throw and catch instructions can throw and catch multiple values, but 1664 // that requires multivalue support in the toolchain, which is currently not 1665 // very reliable. We instead throw and catch a pointer to a struct value of 1666 // type 'struct __WasmLongjmpArgs', which is defined in Emscripten. 1667 Instruction *CatchCI = 1668 IRB.CreateCall(CatchF, {IRB.getInt32(WebAssembly::C_LONGJMP)}, "thrown"); 1669 Value *LongjmpArgs = 1670 IRB.CreateBitCast(CatchCI, LongjmpArgsTy->getPointerTo(), "longjmp.args"); 1671 Value *EnvField = 1672 IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 0, "env_gep"); 1673 Value *ValField = 1674 IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 1, "val_gep"); 1675 // void *env = __wasm_longjmp_args.env; 1676 Instruction *Env = IRB.CreateLoad(IRB.getInt8PtrTy(), EnvField, "env"); 1677 // int val = __wasm_longjmp_args.val; 1678 Instruction *Val = IRB.CreateLoad(IRB.getInt32Ty(), ValField, "val"); 1679 1680 // %label = testSetjmp(mem[%env], setjmpTable, setjmpTableSize); 1681 // if (%label == 0) 1682 // __wasm_longjmp(%env, %val) 1683 // catchret to %setjmp.dispatch 1684 BasicBlock *ThenBB = BasicBlock::Create(C, "if.then", &F); 1685 BasicBlock *EndBB = BasicBlock::Create(C, "if.end", &F); 1686 Value *EnvP = IRB.CreateBitCast(Env, getAddrPtrType(&M), "env.p"); 1687 Value *SetjmpID = IRB.CreateLoad(getAddrIntType(&M), EnvP, "setjmp.id"); 1688 Value *Label = 1689 IRB.CreateCall(TestSetjmpF, {SetjmpID, SetjmpTable, SetjmpTableSize}, 1690 OperandBundleDef("funclet", CatchPad), "label"); 1691 Value *Cmp = IRB.CreateICmpEQ(Label, IRB.getInt32(0)); 1692 IRB.CreateCondBr(Cmp, ThenBB, EndBB); 1693 1694 IRB.SetInsertPoint(ThenBB); 1695 CallInst *WasmLongjmpCI = IRB.CreateCall( 1696 WasmLongjmpF, {Env, Val}, OperandBundleDef("funclet", CatchPad)); 1697 IRB.CreateUnreachable(); 1698 1699 IRB.SetInsertPoint(EndBB); 1700 // Jump to setjmp.dispatch block 1701 IRB.CreateCatchRet(CatchPad, SetjmpDispatchBB); 1702 1703 // Go back to setjmp.dispatch BB 1704 // setjmp.dispatch: 1705 // switch %label { 1706 // label 1: goto post-setjmp BB 1 1707 // label 2: goto post-setjmp BB 2 1708 // ... 1709 // default: goto splitted next BB 1710 // } 1711 IRB.SetInsertPoint(SetjmpDispatchBB); 1712 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label.phi"); 1713 LabelPHI->addIncoming(Label, EndBB); 1714 LabelPHI->addIncoming(IRB.getInt32(-1), Entry); 1715 SwitchInst *SI = IRB.CreateSwitch(LabelPHI, OrigEntry, SetjmpRetPHIs.size()); 1716 // -1 means no longjmp happened, continue normally (will hit the default 1717 // switch case). 0 means a longjmp that is not ours to handle, needs a 1718 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid 1719 // 0). 1720 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) { 1721 SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent()); 1722 SetjmpRetPHIs[I]->addIncoming(Val, SetjmpDispatchBB); 1723 } 1724 1725 // Convert all longjmpable call instructions to invokes that unwind to the 1726 // newly created catch.dispatch.longjmp BB. 1727 SmallVector<CallInst *, 64> LongjmpableCalls; 1728 for (auto *BB = &*F.begin(); BB; BB = BB->getNextNode()) { 1729 for (auto &I : *BB) { 1730 auto *CI = dyn_cast<CallInst>(&I); 1731 if (!CI) 1732 continue; 1733 const Value *Callee = CI->getCalledOperand(); 1734 if (!canLongjmp(Callee)) 1735 continue; 1736 if (isEmAsmCall(Callee)) 1737 report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " + 1738 F.getName() + 1739 ". Please consider using EM_JS, or move the " 1740 "EM_ASM into another function.", 1741 false); 1742 // This is __wasm_longjmp() call we inserted in this function, which 1743 // rethrows the longjmp when the longjmp does not correspond to one of 1744 // setjmps in this function. We should not convert this call to an invoke. 1745 if (CI == WasmLongjmpCI) 1746 continue; 1747 LongjmpableCalls.push_back(CI); 1748 } 1749 } 1750 for (auto *CI : LongjmpableCalls) { 1751 // Even if the callee function has attribute 'nounwind', which is true for 1752 // all C functions, it can longjmp, which means it can throw a Wasm 1753 // exception now. 1754 CI->removeFnAttr(Attribute::NoUnwind); 1755 if (Function *CalleeF = CI->getCalledFunction()) 1756 CalleeF->removeFnAttr(Attribute::NoUnwind); 1757 // Change it to an invoke and make it unwind to the catch.dispatch.longjmp 1758 // BB. 1759 changeToInvokeAndSplitBasicBlock(CI, CatchDispatchLongjmpBB); 1760 } 1761 } 1762