1 //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===// 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 implements a CFG stacking pass. 11 /// 12 /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes, 13 /// since scope boundaries serve as the labels for WebAssembly's control 14 /// transfers. 15 /// 16 /// This is sufficient to convert arbitrary CFGs into a form that works on 17 /// WebAssembly, provided that all loops are single-entry. 18 /// 19 /// In case we use exceptions, this pass also fixes mismatches in unwind 20 /// destinations created during transforming CFG into wasm structured format. 21 /// 22 //===----------------------------------------------------------------------===// 23 24 #include "WebAssembly.h" 25 #include "WebAssemblyExceptionInfo.h" 26 #include "WebAssemblyMachineFunctionInfo.h" 27 #include "WebAssemblySubtarget.h" 28 #include "WebAssemblyUtilities.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/CodeGen/MachineDominators.h" 31 #include "llvm/CodeGen/MachineInstrBuilder.h" 32 #include "llvm/CodeGen/MachineLoopInfo.h" 33 #include "llvm/MC/MCAsmInfo.h" 34 #include "llvm/Target/TargetMachine.h" 35 using namespace llvm; 36 37 #define DEBUG_TYPE "wasm-cfg-stackify" 38 39 STATISTIC(NumUnwindMismatches, "Number of EH pad unwind mismatches found"); 40 41 namespace { 42 class WebAssemblyCFGStackify final : public MachineFunctionPass { 43 StringRef getPassName() const override { return "WebAssembly CFG Stackify"; } 44 45 void getAnalysisUsage(AnalysisUsage &AU) const override { 46 AU.addRequired<MachineDominatorTree>(); 47 AU.addRequired<MachineLoopInfo>(); 48 AU.addRequired<WebAssemblyExceptionInfo>(); 49 MachineFunctionPass::getAnalysisUsage(AU); 50 } 51 52 bool runOnMachineFunction(MachineFunction &MF) override; 53 54 // For each block whose label represents the end of a scope, record the block 55 // which holds the beginning of the scope. This will allow us to quickly skip 56 // over scoped regions when walking blocks. 57 SmallVector<MachineBasicBlock *, 8> ScopeTops; 58 59 // Placing markers. 60 void placeMarkers(MachineFunction &MF); 61 void placeBlockMarker(MachineBasicBlock &MBB); 62 void placeLoopMarker(MachineBasicBlock &MBB); 63 void placeTryMarker(MachineBasicBlock &MBB); 64 void removeUnnecessaryInstrs(MachineFunction &MF); 65 bool fixUnwindMismatches(MachineFunction &MF); 66 void rewriteDepthImmediates(MachineFunction &MF); 67 void fixEndsAtEndOfFunction(MachineFunction &MF); 68 69 // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY). 70 DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd; 71 // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY. 72 DenseMap<const MachineInstr *, MachineInstr *> EndToBegin; 73 // <TRY marker, EH pad> map 74 DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad; 75 // <EH pad, TRY marker> map 76 DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry; 77 78 // There can be an appendix block at the end of each function, shared for: 79 // - creating a correct signature for fallthrough returns 80 // - target for rethrows that need to unwind to the caller, but are trapped 81 // inside another try/catch 82 MachineBasicBlock *AppendixBB = nullptr; 83 MachineBasicBlock *getAppendixBlock(MachineFunction &MF) { 84 if (!AppendixBB) { 85 AppendixBB = MF.CreateMachineBasicBlock(); 86 // Give it a fake predecessor so that AsmPrinter prints its label. 87 AppendixBB->addSuccessor(AppendixBB); 88 MF.push_back(AppendixBB); 89 } 90 return AppendixBB; 91 } 92 93 // Helper functions to register / unregister scope information created by 94 // marker instructions. 95 void registerScope(MachineInstr *Begin, MachineInstr *End); 96 void registerTryScope(MachineInstr *Begin, MachineInstr *End, 97 MachineBasicBlock *EHPad); 98 void unregisterScope(MachineInstr *Begin); 99 100 public: 101 static char ID; // Pass identification, replacement for typeid 102 WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 103 ~WebAssemblyCFGStackify() override { releaseMemory(); } 104 void releaseMemory() override; 105 }; 106 } // end anonymous namespace 107 108 char WebAssemblyCFGStackify::ID = 0; 109 INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE, 110 "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false, 111 false) 112 113 FunctionPass *llvm::createWebAssemblyCFGStackify() { 114 return new WebAssemblyCFGStackify(); 115 } 116 117 /// Test whether Pred has any terminators explicitly branching to MBB, as 118 /// opposed to falling through. Note that it's possible (eg. in unoptimized 119 /// code) for a branch instruction to both branch to a block and fallthrough 120 /// to it, so we check the actual branch operands to see if there are any 121 /// explicit mentions. 122 static bool explicitlyBranchesTo(MachineBasicBlock *Pred, 123 MachineBasicBlock *MBB) { 124 for (MachineInstr &MI : Pred->terminators()) 125 for (MachineOperand &MO : MI.explicit_operands()) 126 if (MO.isMBB() && MO.getMBB() == MBB) 127 return true; 128 return false; 129 } 130 131 // Returns an iterator to the earliest position possible within the MBB, 132 // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 133 // contains instructions that should go before the marker, and AfterSet contains 134 // ones that should go after the marker. In this function, AfterSet is only 135 // used for sanity checking. 136 static MachineBasicBlock::iterator 137 getEarliestInsertPos(MachineBasicBlock *MBB, 138 const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 139 const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 140 auto InsertPos = MBB->end(); 141 while (InsertPos != MBB->begin()) { 142 if (BeforeSet.count(&*std::prev(InsertPos))) { 143 #ifndef NDEBUG 144 // Sanity check 145 for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos) 146 assert(!AfterSet.count(&*std::prev(Pos))); 147 #endif 148 break; 149 } 150 --InsertPos; 151 } 152 return InsertPos; 153 } 154 155 // Returns an iterator to the latest position possible within the MBB, 156 // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 157 // contains instructions that should go before the marker, and AfterSet contains 158 // ones that should go after the marker. In this function, BeforeSet is only 159 // used for sanity checking. 160 static MachineBasicBlock::iterator 161 getLatestInsertPos(MachineBasicBlock *MBB, 162 const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 163 const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 164 auto InsertPos = MBB->begin(); 165 while (InsertPos != MBB->end()) { 166 if (AfterSet.count(&*InsertPos)) { 167 #ifndef NDEBUG 168 // Sanity check 169 for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos) 170 assert(!BeforeSet.count(&*Pos)); 171 #endif 172 break; 173 } 174 ++InsertPos; 175 } 176 return InsertPos; 177 } 178 179 void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin, 180 MachineInstr *End) { 181 BeginToEnd[Begin] = End; 182 EndToBegin[End] = Begin; 183 } 184 185 void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin, 186 MachineInstr *End, 187 MachineBasicBlock *EHPad) { 188 registerScope(Begin, End); 189 TryToEHPad[Begin] = EHPad; 190 EHPadToTry[EHPad] = Begin; 191 } 192 193 void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) { 194 assert(BeginToEnd.count(Begin)); 195 MachineInstr *End = BeginToEnd[Begin]; 196 assert(EndToBegin.count(End)); 197 BeginToEnd.erase(Begin); 198 EndToBegin.erase(End); 199 MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin); 200 if (EHPad) { 201 assert(EHPadToTry.count(EHPad)); 202 TryToEHPad.erase(Begin); 203 EHPadToTry.erase(EHPad); 204 } 205 } 206 207 /// Insert a BLOCK marker for branches to MBB (if needed). 208 // TODO Consider a more generalized way of handling block (and also loop and 209 // try) signatures when we implement the multi-value proposal later. 210 void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) { 211 assert(!MBB.isEHPad()); 212 MachineFunction &MF = *MBB.getParent(); 213 auto &MDT = getAnalysis<MachineDominatorTree>(); 214 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 215 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 216 217 // First compute the nearest common dominator of all forward non-fallthrough 218 // predecessors so that we minimize the time that the BLOCK is on the stack, 219 // which reduces overall stack height. 220 MachineBasicBlock *Header = nullptr; 221 bool IsBranchedTo = false; 222 bool IsBrOnExn = false; 223 MachineInstr *BrOnExn = nullptr; 224 int MBBNumber = MBB.getNumber(); 225 for (MachineBasicBlock *Pred : MBB.predecessors()) { 226 if (Pred->getNumber() < MBBNumber) { 227 Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 228 if (explicitlyBranchesTo(Pred, &MBB)) { 229 IsBranchedTo = true; 230 if (Pred->getFirstTerminator()->getOpcode() == WebAssembly::BR_ON_EXN) { 231 IsBrOnExn = true; 232 assert(!BrOnExn && "There should be only one br_on_exn per block"); 233 BrOnExn = &*Pred->getFirstTerminator(); 234 } 235 } 236 } 237 } 238 if (!Header) 239 return; 240 if (!IsBranchedTo) 241 return; 242 243 assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 244 MachineBasicBlock *LayoutPred = MBB.getPrevNode(); 245 246 // If the nearest common dominator is inside a more deeply nested context, 247 // walk out to the nearest scope which isn't more deeply nested. 248 for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 249 if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 250 if (ScopeTop->getNumber() > Header->getNumber()) { 251 // Skip over an intervening scope. 252 I = std::next(ScopeTop->getIterator()); 253 } else { 254 // We found a scope level at an appropriate depth. 255 Header = ScopeTop; 256 break; 257 } 258 } 259 } 260 261 // Decide where in Header to put the BLOCK. 262 263 // Instructions that should go before the BLOCK. 264 SmallPtrSet<const MachineInstr *, 4> BeforeSet; 265 // Instructions that should go after the BLOCK. 266 SmallPtrSet<const MachineInstr *, 4> AfterSet; 267 for (const auto &MI : *Header) { 268 // If there is a previously placed LOOP marker and the bottom block of the 269 // loop is above MBB, it should be after the BLOCK, because the loop is 270 // nested in this BLOCK. Otherwise it should be before the BLOCK. 271 if (MI.getOpcode() == WebAssembly::LOOP) { 272 auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 273 if (MBB.getNumber() > LoopBottom->getNumber()) 274 AfterSet.insert(&MI); 275 #ifndef NDEBUG 276 else 277 BeforeSet.insert(&MI); 278 #endif 279 } 280 281 // If there is a previously placed BLOCK/TRY marker and its corresponding 282 // END marker is before the current BLOCK's END marker, that should be 283 // placed after this BLOCK. Otherwise it should be placed before this BLOCK 284 // marker. 285 if (MI.getOpcode() == WebAssembly::BLOCK || 286 MI.getOpcode() == WebAssembly::TRY) { 287 if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber()) 288 AfterSet.insert(&MI); 289 #ifndef NDEBUG 290 else 291 BeforeSet.insert(&MI); 292 #endif 293 } 294 295 #ifndef NDEBUG 296 // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK. 297 if (MI.getOpcode() == WebAssembly::END_BLOCK || 298 MI.getOpcode() == WebAssembly::END_LOOP || 299 MI.getOpcode() == WebAssembly::END_TRY) 300 BeforeSet.insert(&MI); 301 #endif 302 303 // Terminators should go after the BLOCK. 304 if (MI.isTerminator()) 305 AfterSet.insert(&MI); 306 } 307 308 // Local expression tree should go after the BLOCK. 309 for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 310 --I) { 311 if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 312 continue; 313 if (WebAssembly::isChild(*std::prev(I), MFI)) 314 AfterSet.insert(&*std::prev(I)); 315 else 316 break; 317 } 318 319 // Add the BLOCK. 320 321 // 'br_on_exn' extracts exnref object and pushes variable number of values 322 // depending on its tag. For C++ exception, its a single i32 value, and the 323 // generated code will be in the form of: 324 // block i32 325 // br_on_exn 0, $__cpp_exception 326 // rethrow 327 // end_block 328 WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void; 329 if (IsBrOnExn) { 330 const char *TagName = BrOnExn->getOperand(1).getSymbolName(); 331 if (std::strcmp(TagName, "__cpp_exception") != 0) 332 llvm_unreachable("Only C++ exception is supported"); 333 ReturnType = WebAssembly::BlockType::I32; 334 } 335 336 auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 337 MachineInstr *Begin = 338 BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 339 TII.get(WebAssembly::BLOCK)) 340 .addImm(int64_t(ReturnType)); 341 342 // Decide where in Header to put the END_BLOCK. 343 BeforeSet.clear(); 344 AfterSet.clear(); 345 for (auto &MI : MBB) { 346 #ifndef NDEBUG 347 // END_BLOCK should precede existing LOOP and TRY markers. 348 if (MI.getOpcode() == WebAssembly::LOOP || 349 MI.getOpcode() == WebAssembly::TRY) 350 AfterSet.insert(&MI); 351 #endif 352 353 // If there is a previously placed END_LOOP marker and the header of the 354 // loop is above this block's header, the END_LOOP should be placed after 355 // the BLOCK, because the loop contains this block. Otherwise the END_LOOP 356 // should be placed before the BLOCK. The same for END_TRY. 357 if (MI.getOpcode() == WebAssembly::END_LOOP || 358 MI.getOpcode() == WebAssembly::END_TRY) { 359 if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 360 BeforeSet.insert(&MI); 361 #ifndef NDEBUG 362 else 363 AfterSet.insert(&MI); 364 #endif 365 } 366 } 367 368 // Mark the end of the block. 369 InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 370 MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos), 371 TII.get(WebAssembly::END_BLOCK)); 372 registerScope(Begin, End); 373 374 // Track the farthest-spanning scope that ends at this point. 375 int Number = MBB.getNumber(); 376 if (!ScopeTops[Number] || 377 ScopeTops[Number]->getNumber() > Header->getNumber()) 378 ScopeTops[Number] = Header; 379 } 380 381 /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 382 void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) { 383 MachineFunction &MF = *MBB.getParent(); 384 const auto &MLI = getAnalysis<MachineLoopInfo>(); 385 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 386 387 MachineLoop *Loop = MLI.getLoopFor(&MBB); 388 if (!Loop || Loop->getHeader() != &MBB) 389 return; 390 391 // The operand of a LOOP is the first block after the loop. If the loop is the 392 // bottom of the function, insert a dummy block at the end. 393 MachineBasicBlock *Bottom = WebAssembly::getBottom(Loop); 394 auto Iter = std::next(Bottom->getIterator()); 395 if (Iter == MF.end()) { 396 getAppendixBlock(MF); 397 Iter = std::next(Bottom->getIterator()); 398 } 399 MachineBasicBlock *AfterLoop = &*Iter; 400 401 // Decide where in Header to put the LOOP. 402 SmallPtrSet<const MachineInstr *, 4> BeforeSet; 403 SmallPtrSet<const MachineInstr *, 4> AfterSet; 404 for (const auto &MI : MBB) { 405 // LOOP marker should be after any existing loop that ends here. Otherwise 406 // we assume the instruction belongs to the loop. 407 if (MI.getOpcode() == WebAssembly::END_LOOP) 408 BeforeSet.insert(&MI); 409 #ifndef NDEBUG 410 else 411 AfterSet.insert(&MI); 412 #endif 413 } 414 415 // Mark the beginning of the loop. 416 auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 417 MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos), 418 TII.get(WebAssembly::LOOP)) 419 .addImm(int64_t(WebAssembly::BlockType::Void)); 420 421 // Decide where in Header to put the END_LOOP. 422 BeforeSet.clear(); 423 AfterSet.clear(); 424 #ifndef NDEBUG 425 for (const auto &MI : MBB) 426 // Existing END_LOOP markers belong to parent loops of this loop 427 if (MI.getOpcode() == WebAssembly::END_LOOP) 428 AfterSet.insert(&MI); 429 #endif 430 431 // Mark the end of the loop (using arbitrary debug location that branched to 432 // the loop end as its location). 433 InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet); 434 DebugLoc EndDL = AfterLoop->pred_empty() 435 ? DebugLoc() 436 : (*AfterLoop->pred_rbegin())->findBranchDebugLoc(); 437 MachineInstr *End = 438 BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP)); 439 registerScope(Begin, End); 440 441 assert((!ScopeTops[AfterLoop->getNumber()] || 442 ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 443 "With block sorting the outermost loop for a block should be first."); 444 if (!ScopeTops[AfterLoop->getNumber()]) 445 ScopeTops[AfterLoop->getNumber()] = &MBB; 446 } 447 448 void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) { 449 assert(MBB.isEHPad()); 450 MachineFunction &MF = *MBB.getParent(); 451 auto &MDT = getAnalysis<MachineDominatorTree>(); 452 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 453 const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 454 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 455 456 // Compute the nearest common dominator of all unwind predecessors 457 MachineBasicBlock *Header = nullptr; 458 int MBBNumber = MBB.getNumber(); 459 for (auto *Pred : MBB.predecessors()) { 460 if (Pred->getNumber() < MBBNumber) { 461 Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 462 assert(!explicitlyBranchesTo(Pred, &MBB) && 463 "Explicit branch to an EH pad!"); 464 } 465 } 466 if (!Header) 467 return; 468 469 // If this try is at the bottom of the function, insert a dummy block at the 470 // end. 471 WebAssemblyException *WE = WEI.getExceptionFor(&MBB); 472 assert(WE); 473 MachineBasicBlock *Bottom = WebAssembly::getBottom(WE); 474 475 auto Iter = std::next(Bottom->getIterator()); 476 if (Iter == MF.end()) { 477 getAppendixBlock(MF); 478 Iter = std::next(Bottom->getIterator()); 479 } 480 MachineBasicBlock *Cont = &*Iter; 481 482 assert(Cont != &MF.front()); 483 MachineBasicBlock *LayoutPred = Cont->getPrevNode(); 484 485 // If the nearest common dominator is inside a more deeply nested context, 486 // walk out to the nearest scope which isn't more deeply nested. 487 for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 488 if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 489 if (ScopeTop->getNumber() > Header->getNumber()) { 490 // Skip over an intervening scope. 491 I = std::next(ScopeTop->getIterator()); 492 } else { 493 // We found a scope level at an appropriate depth. 494 Header = ScopeTop; 495 break; 496 } 497 } 498 } 499 500 // Decide where in Header to put the TRY. 501 502 // Instructions that should go before the TRY. 503 SmallPtrSet<const MachineInstr *, 4> BeforeSet; 504 // Instructions that should go after the TRY. 505 SmallPtrSet<const MachineInstr *, 4> AfterSet; 506 for (const auto &MI : *Header) { 507 // If there is a previously placed LOOP marker and the bottom block of the 508 // loop is above MBB, it should be after the TRY, because the loop is nested 509 // in this TRY. Otherwise it should be before the TRY. 510 if (MI.getOpcode() == WebAssembly::LOOP) { 511 auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 512 if (MBB.getNumber() > LoopBottom->getNumber()) 513 AfterSet.insert(&MI); 514 #ifndef NDEBUG 515 else 516 BeforeSet.insert(&MI); 517 #endif 518 } 519 520 // All previously inserted BLOCK/TRY markers should be after the TRY because 521 // they are all nested trys. 522 if (MI.getOpcode() == WebAssembly::BLOCK || 523 MI.getOpcode() == WebAssembly::TRY) 524 AfterSet.insert(&MI); 525 526 #ifndef NDEBUG 527 // All END_(BLOCK/LOOP/TRY) markers should be before the TRY. 528 if (MI.getOpcode() == WebAssembly::END_BLOCK || 529 MI.getOpcode() == WebAssembly::END_LOOP || 530 MI.getOpcode() == WebAssembly::END_TRY) 531 BeforeSet.insert(&MI); 532 #endif 533 534 // Terminators should go after the TRY. 535 if (MI.isTerminator()) 536 AfterSet.insert(&MI); 537 } 538 539 // If Header unwinds to MBB (= Header contains 'invoke'), the try block should 540 // contain the call within it. So the call should go after the TRY. The 541 // exception is when the header's terminator is a rethrow instruction, in 542 // which case that instruction, not a call instruction before it, is gonna 543 // throw. 544 MachineInstr *ThrowingCall = nullptr; 545 if (MBB.isPredecessor(Header)) { 546 auto TermPos = Header->getFirstTerminator(); 547 if (TermPos == Header->end() || 548 TermPos->getOpcode() != WebAssembly::RETHROW) { 549 for (auto &MI : reverse(*Header)) { 550 if (MI.isCall()) { 551 AfterSet.insert(&MI); 552 ThrowingCall = &MI; 553 // Possibly throwing calls are usually wrapped by EH_LABEL 554 // instructions. We don't want to split them and the call. 555 if (MI.getIterator() != Header->begin() && 556 std::prev(MI.getIterator())->isEHLabel()) { 557 AfterSet.insert(&*std::prev(MI.getIterator())); 558 ThrowingCall = &*std::prev(MI.getIterator()); 559 } 560 break; 561 } 562 } 563 } 564 } 565 566 // Local expression tree should go after the TRY. 567 // For BLOCK placement, we start the search from the previous instruction of a 568 // BB's terminator, but in TRY's case, we should start from the previous 569 // instruction of a call that can throw, or a EH_LABEL that precedes the call, 570 // because the return values of the call's previous instructions can be 571 // stackified and consumed by the throwing call. 572 auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall) 573 : Header->getFirstTerminator(); 574 for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) { 575 if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 576 continue; 577 if (WebAssembly::isChild(*std::prev(I), MFI)) 578 AfterSet.insert(&*std::prev(I)); 579 else 580 break; 581 } 582 583 // Add the TRY. 584 auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 585 MachineInstr *Begin = 586 BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 587 TII.get(WebAssembly::TRY)) 588 .addImm(int64_t(WebAssembly::BlockType::Void)); 589 590 // Decide where in Header to put the END_TRY. 591 BeforeSet.clear(); 592 AfterSet.clear(); 593 for (const auto &MI : *Cont) { 594 #ifndef NDEBUG 595 // END_TRY should precede existing LOOP and BLOCK markers. 596 if (MI.getOpcode() == WebAssembly::LOOP || 597 MI.getOpcode() == WebAssembly::BLOCK) 598 AfterSet.insert(&MI); 599 600 // All END_TRY markers placed earlier belong to exceptions that contains 601 // this one. 602 if (MI.getOpcode() == WebAssembly::END_TRY) 603 AfterSet.insert(&MI); 604 #endif 605 606 // If there is a previously placed END_LOOP marker and its header is after 607 // where TRY marker is, this loop is contained within the 'catch' part, so 608 // the END_TRY marker should go after that. Otherwise, the whole try-catch 609 // is contained within this loop, so the END_TRY should go before that. 610 if (MI.getOpcode() == WebAssembly::END_LOOP) { 611 // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they 612 // are in the same BB, LOOP is always before TRY. 613 if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber()) 614 BeforeSet.insert(&MI); 615 #ifndef NDEBUG 616 else 617 AfterSet.insert(&MI); 618 #endif 619 } 620 621 // It is not possible for an END_BLOCK to be already in this block. 622 } 623 624 // Mark the end of the TRY. 625 InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet); 626 MachineInstr *End = 627 BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(), 628 TII.get(WebAssembly::END_TRY)); 629 registerTryScope(Begin, End, &MBB); 630 631 // Track the farthest-spanning scope that ends at this point. We create two 632 // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB 633 // with 'try'). We need to create 'catch' -> 'try' mapping here too because 634 // markers should not span across 'catch'. For example, this should not 635 // happen: 636 // 637 // try 638 // block --| (X) 639 // catch | 640 // end_block --| 641 // end_try 642 for (int Number : {Cont->getNumber(), MBB.getNumber()}) { 643 if (!ScopeTops[Number] || 644 ScopeTops[Number]->getNumber() > Header->getNumber()) 645 ScopeTops[Number] = Header; 646 } 647 } 648 649 void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) { 650 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 651 652 // When there is an unconditional branch right before a catch instruction and 653 // it branches to the end of end_try marker, we don't need the branch, because 654 // it there is no exception, the control flow transfers to that point anyway. 655 // bb0: 656 // try 657 // ... 658 // br bb2 <- Not necessary 659 // bb1: 660 // catch 661 // ... 662 // bb2: 663 // end 664 for (auto &MBB : MF) { 665 if (!MBB.isEHPad()) 666 continue; 667 668 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 669 SmallVector<MachineOperand, 4> Cond; 670 MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode(); 671 MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent(); 672 bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond); 673 if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) || 674 (!Cond.empty() && FBB && FBB == Cont))) 675 TII.removeBranch(*EHPadLayoutPred); 676 } 677 678 // When there are block / end_block markers that overlap with try / end_try 679 // markers, and the block and try markers' return types are the same, the 680 // block /end_block markers are not necessary, because try / end_try markers 681 // also can serve as boundaries for branches. 682 // block <- Not necessary 683 // try 684 // ... 685 // catch 686 // ... 687 // end 688 // end <- Not necessary 689 SmallVector<MachineInstr *, 32> ToDelete; 690 for (auto &MBB : MF) { 691 for (auto &MI : MBB) { 692 if (MI.getOpcode() != WebAssembly::TRY) 693 continue; 694 695 MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try]; 696 MachineBasicBlock *TryBB = Try->getParent(); 697 MachineBasicBlock *Cont = EndTry->getParent(); 698 int64_t RetType = Try->getOperand(0).getImm(); 699 for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator()); 700 B != TryBB->begin() && E != Cont->end() && 701 std::prev(B)->getOpcode() == WebAssembly::BLOCK && 702 E->getOpcode() == WebAssembly::END_BLOCK && 703 std::prev(B)->getOperand(0).getImm() == RetType; 704 --B, ++E) { 705 ToDelete.push_back(&*std::prev(B)); 706 ToDelete.push_back(&*E); 707 } 708 } 709 } 710 for (auto *MI : ToDelete) { 711 if (MI->getOpcode() == WebAssembly::BLOCK) 712 unregisterScope(MI); 713 MI->eraseFromParent(); 714 } 715 } 716 717 // When MBB is split into MBB and Split, we should unstackify defs in MBB that 718 // have their uses in Split. 719 static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, 720 MachineBasicBlock &Split, 721 WebAssemblyFunctionInfo &MFI, 722 MachineRegisterInfo &MRI) { 723 for (auto &MI : Split) { 724 for (auto &MO : MI.explicit_uses()) { 725 if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg())) 726 continue; 727 if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg())) 728 if (Def->getParent() == &MBB) 729 MFI.unstackifyVReg(MO.getReg()); 730 } 731 } 732 } 733 734 bool WebAssemblyCFGStackify::fixUnwindMismatches(MachineFunction &MF) { 735 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 736 auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 737 MachineRegisterInfo &MRI = MF.getRegInfo(); 738 739 // Linearizing the control flow by placing TRY / END_TRY markers can create 740 // mismatches in unwind destinations. There are two kinds of mismatches we 741 // try to solve here. 742 743 // 1. When an instruction may throw, but the EH pad it will unwind to can be 744 // different from the original CFG. 745 // 746 // Example: we have the following CFG: 747 // bb0: 748 // call @foo (if it throws, unwind to bb2) 749 // bb1: 750 // call @bar (if it throws, unwind to bb3) 751 // bb2 (ehpad): 752 // catch 753 // ... 754 // bb3 (ehpad) 755 // catch 756 // handler body 757 // 758 // And the CFG is sorted in this order. Then after placing TRY markers, it 759 // will look like: (BB markers are omitted) 760 // try $label1 761 // try 762 // call @foo 763 // call @bar (if it throws, unwind to bb3) 764 // catch <- ehpad (bb2) 765 // ... 766 // end_try 767 // catch <- ehpad (bb3) 768 // handler body 769 // end_try 770 // 771 // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it 772 // is supposed to end up. We solve this problem by 773 // a. Split the target unwind EH pad (here bb3) so that the handler body is 774 // right after 'end_try', which means we extract the handler body out of 775 // the catch block. We do this because this handler body should be 776 // somewhere branch-eable from the inner scope. 777 // b. Wrap the call that has an incorrect unwind destination ('call @bar' 778 // here) with a nested try/catch/end_try scope, and within the new catch 779 // block, branches to the handler body. 780 // c. Place a branch after the newly inserted nested end_try so it can bypass 781 // the handler body, which is now outside of a catch block. 782 // 783 // The result will like as follows. (new: a) means this instruction is newly 784 // created in the process of doing 'a' above. 785 // 786 // block $label0 (new: placeBlockMarker) 787 // try $label1 788 // try 789 // call @foo 790 // try (new: b) 791 // call @bar 792 // catch (new: b) 793 // local.set n / drop (new: b) 794 // br $label1 (new: b) 795 // end_try (new: b) 796 // catch <- ehpad (bb2) 797 // end_try 798 // br $label0 (new: c) 799 // catch <- ehpad (bb3) 800 // end_try (hoisted: a) 801 // handler body 802 // end_block (new: placeBlockMarker) 803 // 804 // Note that the new wrapping block/end_block will be generated later in 805 // placeBlockMarker. 806 // 807 // TODO Currently local.set and local.gets are generated to move exnref value 808 // created by catches. That's because we don't support yielding values from a 809 // block in LLVM machine IR yet, even though it is supported by wasm. Delete 810 // unnecessary local.get/local.sets once yielding values from a block is 811 // supported. The full EH spec requires multi-value support to do this, but 812 // for C++ we don't yet need it because we only throw a single i32. 813 // 814 // --- 815 // 2. The same as 1, but in this case an instruction unwinds to a caller 816 // function and not another EH pad. 817 // 818 // Example: we have the following CFG: 819 // bb0: 820 // call @foo (if it throws, unwind to bb2) 821 // bb1: 822 // call @bar (if it throws, unwind to caller) 823 // bb2 (ehpad): 824 // catch 825 // ... 826 // 827 // And the CFG is sorted in this order. Then after placing TRY markers, it 828 // will look like: 829 // try 830 // call @foo 831 // call @bar (if it throws, unwind to caller) 832 // catch <- ehpad (bb2) 833 // ... 834 // end_try 835 // 836 // Now if bar() throws, it is going to end up ip in bb2, when it is supposed 837 // throw up to the caller. 838 // We solve this problem by 839 // a. Create a new 'appendix' BB at the end of the function and put a single 840 // 'rethrow' instruction (+ local.get) in there. 841 // b. Wrap the call that has an incorrect unwind destination ('call @bar' 842 // here) with a nested try/catch/end_try scope, and within the new catch 843 // block, branches to the new appendix block. 844 // 845 // block $label0 (new: placeBlockMarker) 846 // try 847 // call @foo 848 // try (new: b) 849 // call @bar 850 // catch (new: b) 851 // local.set n (new: b) 852 // br $label0 (new: b) 853 // end_try (new: b) 854 // catch <- ehpad (bb2) 855 // ... 856 // end_try 857 // ... 858 // end_block (new: placeBlockMarker) 859 // local.get n (new: a) <- appendix block 860 // rethrow (new: a) 861 // 862 // In case there are multiple calls in a BB that may throw to the caller, they 863 // can be wrapped together in one nested try scope. (In 1, this couldn't 864 // happen, because may-throwing instruction there had an unwind destination, 865 // i.e., it was an invoke before, and there could be only one invoke within a 866 // BB.) 867 868 SmallVector<const MachineBasicBlock *, 8> EHPadStack; 869 // Range of intructions to be wrapped in a new nested try/catch 870 using TryRange = std::pair<MachineInstr *, MachineInstr *>; 871 // In original CFG, <unwind destination BB, a vector of try ranges> 872 DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges; 873 // In new CFG, <destination to branch to, a vector of try ranges> 874 DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> BrDestToTryRanges; 875 // In new CFG, <destination to branch to, register containing exnref> 876 DenseMap<MachineBasicBlock *, unsigned> BrDestToExnReg; 877 878 // Destinations for branches that will be newly added, for which a new 879 // BLOCK/END_BLOCK markers are necessary. 880 SmallVector<MachineBasicBlock *, 8> BrDests; 881 882 // Gather possibly throwing calls (i.e., previously invokes) whose current 883 // unwind destination is not the same as the original CFG. 884 for (auto &MBB : reverse(MF)) { 885 bool SeenThrowableInstInBB = false; 886 for (auto &MI : reverse(MBB)) { 887 if (MI.getOpcode() == WebAssembly::TRY) 888 EHPadStack.pop_back(); 889 else if (MI.getOpcode() == WebAssembly::CATCH) 890 EHPadStack.push_back(MI.getParent()); 891 892 // In this loop we only gather calls that have an EH pad to unwind. So 893 // there will be at most 1 such call (= invoke) in a BB, so after we've 894 // seen one, we can skip the rest of BB. Also if MBB has no EH pad 895 // successor or MI does not throw, this is not an invoke. 896 if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() || 897 !WebAssembly::mayThrow(MI)) 898 continue; 899 SeenThrowableInstInBB = true; 900 901 // If the EH pad on the stack top is where this instruction should unwind 902 // next, we're good. 903 MachineBasicBlock *UnwindDest = nullptr; 904 for (auto *Succ : MBB.successors()) { 905 if (Succ->isEHPad()) { 906 UnwindDest = Succ; 907 break; 908 } 909 } 910 if (EHPadStack.back() == UnwindDest) 911 continue; 912 913 // If not, record the range. 914 UnwindDestToTryRanges[UnwindDest].push_back(TryRange(&MI, &MI)); 915 } 916 } 917 918 assert(EHPadStack.empty()); 919 920 // Gather possibly throwing calls that are supposed to unwind up to the caller 921 // if they throw, but currently unwind to an incorrect destination. Unlike the 922 // loop above, there can be multiple calls within a BB that unwind to the 923 // caller, which we should group together in a range. 924 bool NeedAppendixBlock = false; 925 for (auto &MBB : reverse(MF)) { 926 MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive 927 for (auto &MI : reverse(MBB)) { 928 if (MI.getOpcode() == WebAssembly::TRY) 929 EHPadStack.pop_back(); 930 else if (MI.getOpcode() == WebAssembly::CATCH) 931 EHPadStack.push_back(MI.getParent()); 932 933 // If MBB has an EH pad successor, this inst does not unwind to caller. 934 if (MBB.hasEHPadSuccessor()) 935 continue; 936 937 // We wrap up the current range when we see a marker even if we haven't 938 // finished a BB. 939 if (RangeEnd && WebAssembly::isMarker(MI.getOpcode())) { 940 NeedAppendixBlock = true; 941 // Record the range. nullptr here means the unwind destination is the 942 // caller. 943 UnwindDestToTryRanges[nullptr].push_back( 944 TryRange(RangeBegin, RangeEnd)); 945 RangeBegin = RangeEnd = nullptr; // Reset range pointers 946 } 947 948 // If EHPadStack is empty, that means it is correctly unwind to caller if 949 // it throws, so we're good. If MI does not throw, we're good too. 950 if (EHPadStack.empty() || !WebAssembly::mayThrow(MI)) 951 continue; 952 953 // We found an instruction that unwinds to the caller but currently has an 954 // incorrect unwind destination. Create a new range or increment the 955 // currently existing range. 956 if (!RangeEnd) 957 RangeBegin = RangeEnd = &MI; 958 else 959 RangeBegin = &MI; 960 } 961 962 if (RangeEnd) { 963 NeedAppendixBlock = true; 964 // Record the range. nullptr here means the unwind destination is the 965 // caller. 966 UnwindDestToTryRanges[nullptr].push_back(TryRange(RangeBegin, RangeEnd)); 967 RangeBegin = RangeEnd = nullptr; // Reset range pointers 968 } 969 } 970 971 assert(EHPadStack.empty()); 972 // We don't have any unwind destination mismatches to resolve. 973 if (UnwindDestToTryRanges.empty()) 974 return false; 975 976 // If we found instructions that should unwind to the caller but currently 977 // have incorrect unwind destination, we create an appendix block at the end 978 // of the function with a local.get and a rethrow instruction. 979 if (NeedAppendixBlock) { 980 auto *AppendixBB = getAppendixBlock(MF); 981 Register ExnReg = MRI.createVirtualRegister(&WebAssembly::EXNREFRegClass); 982 BuildMI(AppendixBB, DebugLoc(), TII.get(WebAssembly::RETHROW)) 983 .addReg(ExnReg); 984 // These instruction ranges should branch to this appendix BB. 985 for (auto Range : UnwindDestToTryRanges[nullptr]) 986 BrDestToTryRanges[AppendixBB].push_back(Range); 987 BrDestToExnReg[AppendixBB] = ExnReg; 988 } 989 990 // We loop through unwind destination EH pads that are targeted from some 991 // inner scopes. Because these EH pads are destination of more than one scope 992 // now, we split them so that the handler body is after 'end_try'. 993 // - Before 994 // ehpad: 995 // catch 996 // local.set n / drop 997 // handler body 998 // ... 999 // cont: 1000 // end_try 1001 // 1002 // - After 1003 // ehpad: 1004 // catch 1005 // local.set n / drop 1006 // brdest: (new) 1007 // end_try (hoisted from 'cont' BB) 1008 // handler body (taken from 'ehpad') 1009 // ... 1010 // cont: 1011 for (auto &P : UnwindDestToTryRanges) { 1012 NumUnwindMismatches += P.second.size(); 1013 1014 // This means the destination is the appendix BB, which was separately 1015 // handled above. 1016 if (!P.first) 1017 continue; 1018 1019 MachineBasicBlock *EHPad = P.first; 1020 1021 // Find 'catch' and 'local.set' or 'drop' instruction that follows the 1022 // 'catch'. If -wasm-disable-explicit-locals is not set, 'catch' should be 1023 // always followed by either 'local.set' or a 'drop', because 'br_on_exn' is 1024 // generated after 'catch' in LateEHPrepare and we don't support blocks 1025 // taking values yet. 1026 MachineInstr *Catch = nullptr; 1027 unsigned ExnReg = 0; 1028 for (auto &MI : *EHPad) { 1029 switch (MI.getOpcode()) { 1030 case WebAssembly::CATCH: 1031 Catch = &MI; 1032 ExnReg = Catch->getOperand(0).getReg(); 1033 break; 1034 } 1035 } 1036 assert(Catch && "EH pad does not have a catch"); 1037 assert(ExnReg != 0 && "Invalid register"); 1038 1039 auto SplitPos = std::next(Catch->getIterator()); 1040 1041 // Create a new BB that's gonna be the destination for branches from the 1042 // inner mismatched scope. 1043 MachineInstr *BeginTry = EHPadToTry[EHPad]; 1044 MachineInstr *EndTry = BeginToEnd[BeginTry]; 1045 MachineBasicBlock *Cont = EndTry->getParent(); 1046 auto *BrDest = MF.CreateMachineBasicBlock(); 1047 MF.insert(std::next(EHPad->getIterator()), BrDest); 1048 // Hoist up the existing 'end_try'. 1049 BrDest->insert(BrDest->end(), EndTry->removeFromParent()); 1050 // Take out the handler body from EH pad to the new branch destination BB. 1051 BrDest->splice(BrDest->end(), EHPad, SplitPos, EHPad->end()); 1052 unstackifyVRegsUsedInSplitBB(*EHPad, *BrDest, MFI, MRI); 1053 // Fix predecessor-successor relationship. 1054 BrDest->transferSuccessors(EHPad); 1055 EHPad->addSuccessor(BrDest); 1056 1057 // All try ranges that were supposed to unwind to this EH pad now have to 1058 // branch to this new branch dest BB. 1059 for (auto Range : UnwindDestToTryRanges[EHPad]) 1060 BrDestToTryRanges[BrDest].push_back(Range); 1061 BrDestToExnReg[BrDest] = ExnReg; 1062 1063 // In case we fall through to the continuation BB after the catch block, we 1064 // now have to add a branch to it. 1065 // - Before 1066 // try 1067 // ... 1068 // (falls through to 'cont') 1069 // catch 1070 // handler body 1071 // end 1072 // <-- cont 1073 // 1074 // - After 1075 // try 1076 // ... 1077 // br %cont (new) 1078 // catch 1079 // end 1080 // handler body 1081 // <-- cont 1082 MachineBasicBlock *EHPadLayoutPred = &*std::prev(EHPad->getIterator()); 1083 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1084 SmallVector<MachineOperand, 4> Cond; 1085 bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond); 1086 if (Analyzable && !TBB && !FBB) { 1087 DebugLoc DL = EHPadLayoutPred->empty() 1088 ? DebugLoc() 1089 : EHPadLayoutPred->rbegin()->getDebugLoc(); 1090 BuildMI(EHPadLayoutPred, DL, TII.get(WebAssembly::BR)).addMBB(Cont); 1091 BrDests.push_back(Cont); 1092 } 1093 } 1094 1095 // For possibly throwing calls whose unwind destinations are currently 1096 // incorrect because of CFG linearization, we wrap them with a nested 1097 // try/catch/end_try, and within the new catch block, we branch to the correct 1098 // handler. 1099 // - Before 1100 // mbb: 1101 // call @foo <- Unwind destination mismatch! 1102 // ehpad: 1103 // ... 1104 // 1105 // - After 1106 // mbb: 1107 // try (new) 1108 // call @foo 1109 // nested-ehpad: (new) 1110 // catch (new) 1111 // local.set n / drop (new) 1112 // br %brdest (new) 1113 // nested-end: (new) 1114 // end_try (new) 1115 // ehpad: 1116 // ... 1117 for (auto &P : BrDestToTryRanges) { 1118 MachineBasicBlock *BrDest = P.first; 1119 auto &TryRanges = P.second; 1120 unsigned ExnReg = BrDestToExnReg[BrDest]; 1121 1122 for (auto Range : TryRanges) { 1123 MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; 1124 std::tie(RangeBegin, RangeEnd) = Range; 1125 auto *MBB = RangeBegin->getParent(); 1126 // Store the first function call from this range, because RangeBegin can 1127 // be moved to point EH_LABEL before the call 1128 MachineInstr *RangeBeginCall = RangeBegin; 1129 1130 // Include possible EH_LABELs in the range 1131 if (RangeBegin->getIterator() != MBB->begin() && 1132 std::prev(RangeBegin->getIterator())->isEHLabel()) 1133 RangeBegin = &*std::prev(RangeBegin->getIterator()); 1134 if (std::next(RangeEnd->getIterator()) != MBB->end() && 1135 std::next(RangeEnd->getIterator())->isEHLabel()) 1136 RangeEnd = &*std::next(RangeEnd->getIterator()); 1137 1138 MachineBasicBlock *EHPad = nullptr; 1139 for (auto *Succ : MBB->successors()) { 1140 if (Succ->isEHPad()) { 1141 EHPad = Succ; 1142 break; 1143 } 1144 } 1145 1146 // Local expression tree before the first call of this range should go 1147 // after the nested TRY. 1148 SmallPtrSet<const MachineInstr *, 4> AfterSet; 1149 AfterSet.insert(RangeBegin); 1150 AfterSet.insert(RangeBeginCall); 1151 for (auto I = MachineBasicBlock::iterator(RangeBeginCall), 1152 E = MBB->begin(); 1153 I != E; --I) { 1154 if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 1155 continue; 1156 if (WebAssembly::isChild(*std::prev(I), MFI)) 1157 AfterSet.insert(&*std::prev(I)); 1158 else 1159 break; 1160 } 1161 1162 // Create the nested try instruction. 1163 auto InsertPos = getLatestInsertPos( 1164 MBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet); 1165 MachineInstr *NestedTry = 1166 BuildMI(*MBB, InsertPos, RangeBegin->getDebugLoc(), 1167 TII.get(WebAssembly::TRY)) 1168 .addImm(int64_t(WebAssembly::BlockType::Void)); 1169 1170 // Create the nested EH pad and fill instructions in. 1171 MachineBasicBlock *NestedEHPad = MF.CreateMachineBasicBlock(); 1172 MF.insert(std::next(MBB->getIterator()), NestedEHPad); 1173 NestedEHPad->setIsEHPad(); 1174 NestedEHPad->setIsEHScopeEntry(); 1175 BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::CATCH), 1176 ExnReg); 1177 BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::BR)) 1178 .addMBB(BrDest); 1179 1180 // Create the nested continuation BB and end_try instruction. 1181 MachineBasicBlock *NestedCont = MF.CreateMachineBasicBlock(); 1182 MF.insert(std::next(NestedEHPad->getIterator()), NestedCont); 1183 MachineInstr *NestedEndTry = 1184 BuildMI(*NestedCont, NestedCont->begin(), RangeEnd->getDebugLoc(), 1185 TII.get(WebAssembly::END_TRY)); 1186 // In case MBB has more instructions after the try range, move them to the 1187 // new nested continuation BB. 1188 NestedCont->splice(NestedCont->end(), MBB, 1189 std::next(RangeEnd->getIterator()), MBB->end()); 1190 unstackifyVRegsUsedInSplitBB(*MBB, *NestedCont, MFI, MRI); 1191 registerTryScope(NestedTry, NestedEndTry, NestedEHPad); 1192 1193 // Fix predecessor-successor relationship. 1194 NestedCont->transferSuccessors(MBB); 1195 if (EHPad) { 1196 NestedCont->removeSuccessor(EHPad); 1197 // If EHPad does not have any predecessors left after removing 1198 // NextedCont predecessor, remove its successor too, because this EHPad 1199 // is not reachable from the entry BB anyway. We can't remove EHPad BB 1200 // itself because it can contain 'catch' or 'end', which are necessary 1201 // for keeping try-catch-end structure. 1202 if (EHPad->pred_empty()) 1203 EHPad->removeSuccessor(BrDest); 1204 } 1205 MBB->addSuccessor(NestedEHPad); 1206 MBB->addSuccessor(NestedCont); 1207 NestedEHPad->addSuccessor(BrDest); 1208 } 1209 } 1210 1211 // Renumber BBs and recalculate ScopeTop info because new BBs might have been 1212 // created and inserted above. 1213 MF.RenumberBlocks(); 1214 ScopeTops.clear(); 1215 ScopeTops.resize(MF.getNumBlockIDs()); 1216 for (auto &MBB : reverse(MF)) { 1217 for (auto &MI : reverse(MBB)) { 1218 if (ScopeTops[MBB.getNumber()]) 1219 break; 1220 switch (MI.getOpcode()) { 1221 case WebAssembly::END_BLOCK: 1222 case WebAssembly::END_LOOP: 1223 case WebAssembly::END_TRY: 1224 ScopeTops[MBB.getNumber()] = EndToBegin[&MI]->getParent(); 1225 break; 1226 case WebAssembly::CATCH: 1227 ScopeTops[MBB.getNumber()] = EHPadToTry[&MBB]->getParent(); 1228 break; 1229 } 1230 } 1231 } 1232 1233 // Recompute the dominator tree. 1234 getAnalysis<MachineDominatorTree>().runOnMachineFunction(MF); 1235 1236 // Place block markers for newly added branches, if necessary. 1237 1238 // If we've created an appendix BB and a branch to it, place a block/end_block 1239 // marker for that. For some new branches, those branch destination BBs start 1240 // with a hoisted end_try marker, so we don't need a new marker there. 1241 if (AppendixBB) 1242 BrDests.push_back(AppendixBB); 1243 1244 llvm::sort(BrDests, 1245 [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { 1246 auto ANum = A->getNumber(); 1247 auto BNum = B->getNumber(); 1248 return ANum < BNum; 1249 }); 1250 for (auto *Dest : BrDests) 1251 placeBlockMarker(*Dest); 1252 1253 return true; 1254 } 1255 1256 static unsigned 1257 getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 1258 const MachineBasicBlock *MBB) { 1259 unsigned Depth = 0; 1260 for (auto X : reverse(Stack)) { 1261 if (X == MBB) 1262 break; 1263 ++Depth; 1264 } 1265 assert(Depth < Stack.size() && "Branch destination should be in scope"); 1266 return Depth; 1267 } 1268 1269 /// In normal assembly languages, when the end of a function is unreachable, 1270 /// because the function ends in an infinite loop or a noreturn call or similar, 1271 /// it isn't necessary to worry about the function return type at the end of 1272 /// the function, because it's never reached. However, in WebAssembly, blocks 1273 /// that end at the function end need to have a return type signature that 1274 /// matches the function signature, even though it's unreachable. This function 1275 /// checks for such cases and fixes up the signatures. 1276 void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) { 1277 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 1278 1279 if (MFI.getResults().empty()) 1280 return; 1281 1282 // MCInstLower will add the proper types to multivalue signatures based on the 1283 // function return type 1284 WebAssembly::BlockType RetType = 1285 MFI.getResults().size() > 1 1286 ? WebAssembly::BlockType::Multivalue 1287 : WebAssembly::BlockType( 1288 WebAssembly::toValType(MFI.getResults().front())); 1289 1290 for (MachineBasicBlock &MBB : reverse(MF)) { 1291 for (MachineInstr &MI : reverse(MBB)) { 1292 if (MI.isPosition() || MI.isDebugInstr()) 1293 continue; 1294 switch (MI.getOpcode()) { 1295 case WebAssembly::END_BLOCK: 1296 case WebAssembly::END_LOOP: 1297 case WebAssembly::END_TRY: 1298 EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType)); 1299 continue; 1300 default: 1301 // Something other than an `end`. We're done. 1302 return; 1303 } 1304 } 1305 } 1306 } 1307 1308 // WebAssembly functions end with an end instruction, as if the function body 1309 // were a block. 1310 static void appendEndToFunction(MachineFunction &MF, 1311 const WebAssemblyInstrInfo &TII) { 1312 BuildMI(MF.back(), MF.back().end(), 1313 MF.back().findPrevDebugLoc(MF.back().end()), 1314 TII.get(WebAssembly::END_FUNCTION)); 1315 } 1316 1317 /// Insert LOOP/TRY/BLOCK markers at appropriate places. 1318 void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) { 1319 // We allocate one more than the number of blocks in the function to 1320 // accommodate for the possible fake block we may insert at the end. 1321 ScopeTops.resize(MF.getNumBlockIDs() + 1); 1322 // Place the LOOP for MBB if MBB is the header of a loop. 1323 for (auto &MBB : MF) 1324 placeLoopMarker(MBB); 1325 1326 const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 1327 for (auto &MBB : MF) { 1328 if (MBB.isEHPad()) { 1329 // Place the TRY for MBB if MBB is the EH pad of an exception. 1330 if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1331 MF.getFunction().hasPersonalityFn()) 1332 placeTryMarker(MBB); 1333 } else { 1334 // Place the BLOCK for MBB if MBB is branched to from above. 1335 placeBlockMarker(MBB); 1336 } 1337 } 1338 // Fix mismatches in unwind destinations induced by linearizing the code. 1339 if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1340 MF.getFunction().hasPersonalityFn()) 1341 fixUnwindMismatches(MF); 1342 } 1343 1344 void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) { 1345 // Now rewrite references to basic blocks to be depth immediates. 1346 SmallVector<const MachineBasicBlock *, 8> Stack; 1347 for (auto &MBB : reverse(MF)) { 1348 for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) { 1349 MachineInstr &MI = *I; 1350 switch (MI.getOpcode()) { 1351 case WebAssembly::BLOCK: 1352 case WebAssembly::TRY: 1353 assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= 1354 MBB.getNumber() && 1355 "Block/try marker should be balanced"); 1356 Stack.pop_back(); 1357 break; 1358 1359 case WebAssembly::LOOP: 1360 assert(Stack.back() == &MBB && "Loop top should be balanced"); 1361 Stack.pop_back(); 1362 break; 1363 1364 case WebAssembly::END_BLOCK: 1365 case WebAssembly::END_TRY: 1366 Stack.push_back(&MBB); 1367 break; 1368 1369 case WebAssembly::END_LOOP: 1370 Stack.push_back(EndToBegin[&MI]->getParent()); 1371 break; 1372 1373 default: 1374 if (MI.isTerminator()) { 1375 // Rewrite MBB operands to be depth immediates. 1376 SmallVector<MachineOperand, 4> Ops(MI.operands()); 1377 while (MI.getNumOperands() > 0) 1378 MI.RemoveOperand(MI.getNumOperands() - 1); 1379 for (auto MO : Ops) { 1380 if (MO.isMBB()) 1381 MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB())); 1382 MI.addOperand(MF, MO); 1383 } 1384 } 1385 break; 1386 } 1387 } 1388 } 1389 assert(Stack.empty() && "Control flow should be balanced"); 1390 } 1391 1392 void WebAssemblyCFGStackify::releaseMemory() { 1393 ScopeTops.clear(); 1394 BeginToEnd.clear(); 1395 EndToBegin.clear(); 1396 TryToEHPad.clear(); 1397 EHPadToTry.clear(); 1398 AppendixBB = nullptr; 1399 } 1400 1401 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 1402 LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n" 1403 "********** Function: " 1404 << MF.getName() << '\n'); 1405 const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 1406 1407 releaseMemory(); 1408 1409 // Liveness is not tracked for VALUE_STACK physreg. 1410 MF.getRegInfo().invalidateLiveness(); 1411 1412 // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes. 1413 placeMarkers(MF); 1414 1415 // Remove unnecessary instructions possibly introduced by try/end_trys. 1416 if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1417 MF.getFunction().hasPersonalityFn()) 1418 removeUnnecessaryInstrs(MF); 1419 1420 // Convert MBB operands in terminators to relative depth immediates. 1421 rewriteDepthImmediates(MF); 1422 1423 // Fix up block/loop/try signatures at the end of the function to conform to 1424 // WebAssembly's rules. 1425 fixEndsAtEndOfFunction(MF); 1426 1427 // Add an end instruction at the end of the function body. 1428 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 1429 if (!MF.getSubtarget<WebAssemblySubtarget>() 1430 .getTargetTriple() 1431 .isOSBinFormatELF()) 1432 appendEndToFunction(MF, TII); 1433 1434 MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified(); 1435 return true; 1436 } 1437