10b57cec5SDimitry Andric //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric /// 90b57cec5SDimitry Andric /// \file 100b57cec5SDimitry Andric /// This file implements a CFG stacking pass. 110b57cec5SDimitry Andric /// 120b57cec5SDimitry Andric /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes, 130b57cec5SDimitry Andric /// since scope boundaries serve as the labels for WebAssembly's control 140b57cec5SDimitry Andric /// transfers. 150b57cec5SDimitry Andric /// 160b57cec5SDimitry Andric /// This is sufficient to convert arbitrary CFGs into a form that works on 170b57cec5SDimitry Andric /// WebAssembly, provided that all loops are single-entry. 180b57cec5SDimitry Andric /// 190b57cec5SDimitry Andric /// In case we use exceptions, this pass also fixes mismatches in unwind 200b57cec5SDimitry Andric /// destinations created during transforming CFG into wasm structured format. 210b57cec5SDimitry Andric /// 220b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 230b57cec5SDimitry Andric 240b57cec5SDimitry Andric #include "WebAssembly.h" 250b57cec5SDimitry Andric #include "WebAssemblyExceptionInfo.h" 260b57cec5SDimitry Andric #include "WebAssemblyMachineFunctionInfo.h" 270b57cec5SDimitry Andric #include "WebAssemblySubtarget.h" 280b57cec5SDimitry Andric #include "WebAssemblyUtilities.h" 290b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h" 310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h" 32*8bcb0991SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h" 330b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h" 340b57cec5SDimitry Andric using namespace llvm; 350b57cec5SDimitry Andric 360b57cec5SDimitry Andric #define DEBUG_TYPE "wasm-cfg-stackify" 370b57cec5SDimitry Andric 380b57cec5SDimitry Andric STATISTIC(NumUnwindMismatches, "Number of EH pad unwind mismatches found"); 390b57cec5SDimitry Andric 400b57cec5SDimitry Andric namespace { 410b57cec5SDimitry Andric class WebAssemblyCFGStackify final : public MachineFunctionPass { 420b57cec5SDimitry Andric StringRef getPassName() const override { return "WebAssembly CFG Stackify"; } 430b57cec5SDimitry Andric 440b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 450b57cec5SDimitry Andric AU.addRequired<MachineDominatorTree>(); 460b57cec5SDimitry Andric AU.addRequired<MachineLoopInfo>(); 470b57cec5SDimitry Andric AU.addRequired<WebAssemblyExceptionInfo>(); 480b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 490b57cec5SDimitry Andric } 500b57cec5SDimitry Andric 510b57cec5SDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override; 520b57cec5SDimitry Andric 530b57cec5SDimitry Andric // For each block whose label represents the end of a scope, record the block 540b57cec5SDimitry Andric // which holds the beginning of the scope. This will allow us to quickly skip 550b57cec5SDimitry Andric // over scoped regions when walking blocks. 560b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 8> ScopeTops; 570b57cec5SDimitry Andric 580b57cec5SDimitry Andric // Placing markers. 590b57cec5SDimitry Andric void placeMarkers(MachineFunction &MF); 600b57cec5SDimitry Andric void placeBlockMarker(MachineBasicBlock &MBB); 610b57cec5SDimitry Andric void placeLoopMarker(MachineBasicBlock &MBB); 620b57cec5SDimitry Andric void placeTryMarker(MachineBasicBlock &MBB); 630b57cec5SDimitry Andric void removeUnnecessaryInstrs(MachineFunction &MF); 640b57cec5SDimitry Andric bool fixUnwindMismatches(MachineFunction &MF); 650b57cec5SDimitry Andric void rewriteDepthImmediates(MachineFunction &MF); 660b57cec5SDimitry Andric void fixEndsAtEndOfFunction(MachineFunction &MF); 670b57cec5SDimitry Andric 680b57cec5SDimitry Andric // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY). 690b57cec5SDimitry Andric DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd; 700b57cec5SDimitry Andric // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY. 710b57cec5SDimitry Andric DenseMap<const MachineInstr *, MachineInstr *> EndToBegin; 720b57cec5SDimitry Andric // <TRY marker, EH pad> map 730b57cec5SDimitry Andric DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad; 740b57cec5SDimitry Andric // <EH pad, TRY marker> map 750b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry; 760b57cec5SDimitry Andric 770b57cec5SDimitry Andric // There can be an appendix block at the end of each function, shared for: 780b57cec5SDimitry Andric // - creating a correct signature for fallthrough returns 790b57cec5SDimitry Andric // - target for rethrows that need to unwind to the caller, but are trapped 800b57cec5SDimitry Andric // inside another try/catch 810b57cec5SDimitry Andric MachineBasicBlock *AppendixBB = nullptr; 820b57cec5SDimitry Andric MachineBasicBlock *getAppendixBlock(MachineFunction &MF) { 830b57cec5SDimitry Andric if (!AppendixBB) { 840b57cec5SDimitry Andric AppendixBB = MF.CreateMachineBasicBlock(); 850b57cec5SDimitry Andric // Give it a fake predecessor so that AsmPrinter prints its label. 860b57cec5SDimitry Andric AppendixBB->addSuccessor(AppendixBB); 870b57cec5SDimitry Andric MF.push_back(AppendixBB); 880b57cec5SDimitry Andric } 890b57cec5SDimitry Andric return AppendixBB; 900b57cec5SDimitry Andric } 910b57cec5SDimitry Andric 920b57cec5SDimitry Andric // Helper functions to register / unregister scope information created by 930b57cec5SDimitry Andric // marker instructions. 940b57cec5SDimitry Andric void registerScope(MachineInstr *Begin, MachineInstr *End); 950b57cec5SDimitry Andric void registerTryScope(MachineInstr *Begin, MachineInstr *End, 960b57cec5SDimitry Andric MachineBasicBlock *EHPad); 970b57cec5SDimitry Andric void unregisterScope(MachineInstr *Begin); 980b57cec5SDimitry Andric 990b57cec5SDimitry Andric public: 1000b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid 1010b57cec5SDimitry Andric WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 1020b57cec5SDimitry Andric ~WebAssemblyCFGStackify() override { releaseMemory(); } 1030b57cec5SDimitry Andric void releaseMemory() override; 1040b57cec5SDimitry Andric }; 1050b57cec5SDimitry Andric } // end anonymous namespace 1060b57cec5SDimitry Andric 1070b57cec5SDimitry Andric char WebAssemblyCFGStackify::ID = 0; 1080b57cec5SDimitry Andric INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE, 1090b57cec5SDimitry Andric "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false, 1100b57cec5SDimitry Andric false) 1110b57cec5SDimitry Andric 1120b57cec5SDimitry Andric FunctionPass *llvm::createWebAssemblyCFGStackify() { 1130b57cec5SDimitry Andric return new WebAssemblyCFGStackify(); 1140b57cec5SDimitry Andric } 1150b57cec5SDimitry Andric 1160b57cec5SDimitry Andric /// Test whether Pred has any terminators explicitly branching to MBB, as 1170b57cec5SDimitry Andric /// opposed to falling through. Note that it's possible (eg. in unoptimized 1180b57cec5SDimitry Andric /// code) for a branch instruction to both branch to a block and fallthrough 1190b57cec5SDimitry Andric /// to it, so we check the actual branch operands to see if there are any 1200b57cec5SDimitry Andric /// explicit mentions. 1210b57cec5SDimitry Andric static bool explicitlyBranchesTo(MachineBasicBlock *Pred, 1220b57cec5SDimitry Andric MachineBasicBlock *MBB) { 1230b57cec5SDimitry Andric for (MachineInstr &MI : Pred->terminators()) 1240b57cec5SDimitry Andric for (MachineOperand &MO : MI.explicit_operands()) 1250b57cec5SDimitry Andric if (MO.isMBB() && MO.getMBB() == MBB) 1260b57cec5SDimitry Andric return true; 1270b57cec5SDimitry Andric return false; 1280b57cec5SDimitry Andric } 1290b57cec5SDimitry Andric 1300b57cec5SDimitry Andric // Returns an iterator to the earliest position possible within the MBB, 1310b57cec5SDimitry Andric // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 1320b57cec5SDimitry Andric // contains instructions that should go before the marker, and AfterSet contains 1330b57cec5SDimitry Andric // ones that should go after the marker. In this function, AfterSet is only 1340b57cec5SDimitry Andric // used for sanity checking. 1350b57cec5SDimitry Andric static MachineBasicBlock::iterator 1360b57cec5SDimitry Andric getEarliestInsertPos(MachineBasicBlock *MBB, 1370b57cec5SDimitry Andric const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 1380b57cec5SDimitry Andric const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 1390b57cec5SDimitry Andric auto InsertPos = MBB->end(); 1400b57cec5SDimitry Andric while (InsertPos != MBB->begin()) { 1410b57cec5SDimitry Andric if (BeforeSet.count(&*std::prev(InsertPos))) { 1420b57cec5SDimitry Andric #ifndef NDEBUG 1430b57cec5SDimitry Andric // Sanity check 1440b57cec5SDimitry Andric for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos) 1450b57cec5SDimitry Andric assert(!AfterSet.count(&*std::prev(Pos))); 1460b57cec5SDimitry Andric #endif 1470b57cec5SDimitry Andric break; 1480b57cec5SDimitry Andric } 1490b57cec5SDimitry Andric --InsertPos; 1500b57cec5SDimitry Andric } 1510b57cec5SDimitry Andric return InsertPos; 1520b57cec5SDimitry Andric } 1530b57cec5SDimitry Andric 1540b57cec5SDimitry Andric // Returns an iterator to the latest position possible within the MBB, 1550b57cec5SDimitry Andric // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 1560b57cec5SDimitry Andric // contains instructions that should go before the marker, and AfterSet contains 1570b57cec5SDimitry Andric // ones that should go after the marker. In this function, BeforeSet is only 1580b57cec5SDimitry Andric // used for sanity checking. 1590b57cec5SDimitry Andric static MachineBasicBlock::iterator 1600b57cec5SDimitry Andric getLatestInsertPos(MachineBasicBlock *MBB, 1610b57cec5SDimitry Andric const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 1620b57cec5SDimitry Andric const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 1630b57cec5SDimitry Andric auto InsertPos = MBB->begin(); 1640b57cec5SDimitry Andric while (InsertPos != MBB->end()) { 1650b57cec5SDimitry Andric if (AfterSet.count(&*InsertPos)) { 1660b57cec5SDimitry Andric #ifndef NDEBUG 1670b57cec5SDimitry Andric // Sanity check 1680b57cec5SDimitry Andric for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos) 1690b57cec5SDimitry Andric assert(!BeforeSet.count(&*Pos)); 1700b57cec5SDimitry Andric #endif 1710b57cec5SDimitry Andric break; 1720b57cec5SDimitry Andric } 1730b57cec5SDimitry Andric ++InsertPos; 1740b57cec5SDimitry Andric } 1750b57cec5SDimitry Andric return InsertPos; 1760b57cec5SDimitry Andric } 1770b57cec5SDimitry Andric 1780b57cec5SDimitry Andric void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin, 1790b57cec5SDimitry Andric MachineInstr *End) { 1800b57cec5SDimitry Andric BeginToEnd[Begin] = End; 1810b57cec5SDimitry Andric EndToBegin[End] = Begin; 1820b57cec5SDimitry Andric } 1830b57cec5SDimitry Andric 1840b57cec5SDimitry Andric void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin, 1850b57cec5SDimitry Andric MachineInstr *End, 1860b57cec5SDimitry Andric MachineBasicBlock *EHPad) { 1870b57cec5SDimitry Andric registerScope(Begin, End); 1880b57cec5SDimitry Andric TryToEHPad[Begin] = EHPad; 1890b57cec5SDimitry Andric EHPadToTry[EHPad] = Begin; 1900b57cec5SDimitry Andric } 1910b57cec5SDimitry Andric 1920b57cec5SDimitry Andric void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) { 1930b57cec5SDimitry Andric assert(BeginToEnd.count(Begin)); 1940b57cec5SDimitry Andric MachineInstr *End = BeginToEnd[Begin]; 1950b57cec5SDimitry Andric assert(EndToBegin.count(End)); 1960b57cec5SDimitry Andric BeginToEnd.erase(Begin); 1970b57cec5SDimitry Andric EndToBegin.erase(End); 1980b57cec5SDimitry Andric MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin); 1990b57cec5SDimitry Andric if (EHPad) { 2000b57cec5SDimitry Andric assert(EHPadToTry.count(EHPad)); 2010b57cec5SDimitry Andric TryToEHPad.erase(Begin); 2020b57cec5SDimitry Andric EHPadToTry.erase(EHPad); 2030b57cec5SDimitry Andric } 2040b57cec5SDimitry Andric } 2050b57cec5SDimitry Andric 2060b57cec5SDimitry Andric /// Insert a BLOCK marker for branches to MBB (if needed). 2070b57cec5SDimitry Andric // TODO Consider a more generalized way of handling block (and also loop and 2080b57cec5SDimitry Andric // try) signatures when we implement the multi-value proposal later. 2090b57cec5SDimitry Andric void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) { 2100b57cec5SDimitry Andric assert(!MBB.isEHPad()); 2110b57cec5SDimitry Andric MachineFunction &MF = *MBB.getParent(); 2120b57cec5SDimitry Andric auto &MDT = getAnalysis<MachineDominatorTree>(); 2130b57cec5SDimitry Andric const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 2140b57cec5SDimitry Andric const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 2150b57cec5SDimitry Andric 2160b57cec5SDimitry Andric // First compute the nearest common dominator of all forward non-fallthrough 2170b57cec5SDimitry Andric // predecessors so that we minimize the time that the BLOCK is on the stack, 2180b57cec5SDimitry Andric // which reduces overall stack height. 2190b57cec5SDimitry Andric MachineBasicBlock *Header = nullptr; 2200b57cec5SDimitry Andric bool IsBranchedTo = false; 2210b57cec5SDimitry Andric bool IsBrOnExn = false; 2220b57cec5SDimitry Andric MachineInstr *BrOnExn = nullptr; 2230b57cec5SDimitry Andric int MBBNumber = MBB.getNumber(); 2240b57cec5SDimitry Andric for (MachineBasicBlock *Pred : MBB.predecessors()) { 2250b57cec5SDimitry Andric if (Pred->getNumber() < MBBNumber) { 2260b57cec5SDimitry Andric Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 2270b57cec5SDimitry Andric if (explicitlyBranchesTo(Pred, &MBB)) { 2280b57cec5SDimitry Andric IsBranchedTo = true; 2290b57cec5SDimitry Andric if (Pred->getFirstTerminator()->getOpcode() == WebAssembly::BR_ON_EXN) { 2300b57cec5SDimitry Andric IsBrOnExn = true; 2310b57cec5SDimitry Andric assert(!BrOnExn && "There should be only one br_on_exn per block"); 2320b57cec5SDimitry Andric BrOnExn = &*Pred->getFirstTerminator(); 2330b57cec5SDimitry Andric } 2340b57cec5SDimitry Andric } 2350b57cec5SDimitry Andric } 2360b57cec5SDimitry Andric } 2370b57cec5SDimitry Andric if (!Header) 2380b57cec5SDimitry Andric return; 2390b57cec5SDimitry Andric if (!IsBranchedTo) 2400b57cec5SDimitry Andric return; 2410b57cec5SDimitry Andric 2420b57cec5SDimitry Andric assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 2430b57cec5SDimitry Andric MachineBasicBlock *LayoutPred = MBB.getPrevNode(); 2440b57cec5SDimitry Andric 2450b57cec5SDimitry Andric // If the nearest common dominator is inside a more deeply nested context, 2460b57cec5SDimitry Andric // walk out to the nearest scope which isn't more deeply nested. 2470b57cec5SDimitry Andric for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 2480b57cec5SDimitry Andric if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 2490b57cec5SDimitry Andric if (ScopeTop->getNumber() > Header->getNumber()) { 2500b57cec5SDimitry Andric // Skip over an intervening scope. 2510b57cec5SDimitry Andric I = std::next(ScopeTop->getIterator()); 2520b57cec5SDimitry Andric } else { 2530b57cec5SDimitry Andric // We found a scope level at an appropriate depth. 2540b57cec5SDimitry Andric Header = ScopeTop; 2550b57cec5SDimitry Andric break; 2560b57cec5SDimitry Andric } 2570b57cec5SDimitry Andric } 2580b57cec5SDimitry Andric } 2590b57cec5SDimitry Andric 2600b57cec5SDimitry Andric // Decide where in Header to put the BLOCK. 2610b57cec5SDimitry Andric 2620b57cec5SDimitry Andric // Instructions that should go before the BLOCK. 2630b57cec5SDimitry Andric SmallPtrSet<const MachineInstr *, 4> BeforeSet; 2640b57cec5SDimitry Andric // Instructions that should go after the BLOCK. 2650b57cec5SDimitry Andric SmallPtrSet<const MachineInstr *, 4> AfterSet; 2660b57cec5SDimitry Andric for (const auto &MI : *Header) { 2670b57cec5SDimitry Andric // If there is a previously placed LOOP marker and the bottom block of the 2680b57cec5SDimitry Andric // loop is above MBB, it should be after the BLOCK, because the loop is 2690b57cec5SDimitry Andric // nested in this BLOCK. Otherwise it should be before the BLOCK. 2700b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::LOOP) { 2710b57cec5SDimitry Andric auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 2720b57cec5SDimitry Andric if (MBB.getNumber() > LoopBottom->getNumber()) 2730b57cec5SDimitry Andric AfterSet.insert(&MI); 2740b57cec5SDimitry Andric #ifndef NDEBUG 2750b57cec5SDimitry Andric else 2760b57cec5SDimitry Andric BeforeSet.insert(&MI); 2770b57cec5SDimitry Andric #endif 2780b57cec5SDimitry Andric } 2790b57cec5SDimitry Andric 2800b57cec5SDimitry Andric // All previously inserted BLOCK/TRY markers should be after the BLOCK 2810b57cec5SDimitry Andric // because they are all nested blocks. 2820b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::BLOCK || 2830b57cec5SDimitry Andric MI.getOpcode() == WebAssembly::TRY) 2840b57cec5SDimitry Andric AfterSet.insert(&MI); 2850b57cec5SDimitry Andric 2860b57cec5SDimitry Andric #ifndef NDEBUG 2870b57cec5SDimitry Andric // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK. 2880b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::END_BLOCK || 2890b57cec5SDimitry Andric MI.getOpcode() == WebAssembly::END_LOOP || 2900b57cec5SDimitry Andric MI.getOpcode() == WebAssembly::END_TRY) 2910b57cec5SDimitry Andric BeforeSet.insert(&MI); 2920b57cec5SDimitry Andric #endif 2930b57cec5SDimitry Andric 2940b57cec5SDimitry Andric // Terminators should go after the BLOCK. 2950b57cec5SDimitry Andric if (MI.isTerminator()) 2960b57cec5SDimitry Andric AfterSet.insert(&MI); 2970b57cec5SDimitry Andric } 2980b57cec5SDimitry Andric 2990b57cec5SDimitry Andric // Local expression tree should go after the BLOCK. 3000b57cec5SDimitry Andric for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 3010b57cec5SDimitry Andric --I) { 3020b57cec5SDimitry Andric if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 3030b57cec5SDimitry Andric continue; 3040b57cec5SDimitry Andric if (WebAssembly::isChild(*std::prev(I), MFI)) 3050b57cec5SDimitry Andric AfterSet.insert(&*std::prev(I)); 3060b57cec5SDimitry Andric else 3070b57cec5SDimitry Andric break; 3080b57cec5SDimitry Andric } 3090b57cec5SDimitry Andric 3100b57cec5SDimitry Andric // Add the BLOCK. 3110b57cec5SDimitry Andric 3120b57cec5SDimitry Andric // 'br_on_exn' extracts exnref object and pushes variable number of values 3130b57cec5SDimitry Andric // depending on its tag. For C++ exception, its a single i32 value, and the 3140b57cec5SDimitry Andric // generated code will be in the form of: 3150b57cec5SDimitry Andric // block i32 3160b57cec5SDimitry Andric // br_on_exn 0, $__cpp_exception 3170b57cec5SDimitry Andric // rethrow 3180b57cec5SDimitry Andric // end_block 319*8bcb0991SDimitry Andric WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void; 3200b57cec5SDimitry Andric if (IsBrOnExn) { 3210b57cec5SDimitry Andric const char *TagName = BrOnExn->getOperand(1).getSymbolName(); 3220b57cec5SDimitry Andric if (std::strcmp(TagName, "__cpp_exception") != 0) 3230b57cec5SDimitry Andric llvm_unreachable("Only C++ exception is supported"); 324*8bcb0991SDimitry Andric ReturnType = WebAssembly::BlockType::I32; 3250b57cec5SDimitry Andric } 3260b57cec5SDimitry Andric 3270b57cec5SDimitry Andric auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 3280b57cec5SDimitry Andric MachineInstr *Begin = 3290b57cec5SDimitry Andric BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 3300b57cec5SDimitry Andric TII.get(WebAssembly::BLOCK)) 3310b57cec5SDimitry Andric .addImm(int64_t(ReturnType)); 3320b57cec5SDimitry Andric 3330b57cec5SDimitry Andric // Decide where in Header to put the END_BLOCK. 3340b57cec5SDimitry Andric BeforeSet.clear(); 3350b57cec5SDimitry Andric AfterSet.clear(); 3360b57cec5SDimitry Andric for (auto &MI : MBB) { 3370b57cec5SDimitry Andric #ifndef NDEBUG 3380b57cec5SDimitry Andric // END_BLOCK should precede existing LOOP and TRY markers. 3390b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::LOOP || 3400b57cec5SDimitry Andric MI.getOpcode() == WebAssembly::TRY) 3410b57cec5SDimitry Andric AfterSet.insert(&MI); 3420b57cec5SDimitry Andric #endif 3430b57cec5SDimitry Andric 3440b57cec5SDimitry Andric // If there is a previously placed END_LOOP marker and the header of the 3450b57cec5SDimitry Andric // loop is above this block's header, the END_LOOP should be placed after 3460b57cec5SDimitry Andric // the BLOCK, because the loop contains this block. Otherwise the END_LOOP 3470b57cec5SDimitry Andric // should be placed before the BLOCK. The same for END_TRY. 3480b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::END_LOOP || 3490b57cec5SDimitry Andric MI.getOpcode() == WebAssembly::END_TRY) { 3500b57cec5SDimitry Andric if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 3510b57cec5SDimitry Andric BeforeSet.insert(&MI); 3520b57cec5SDimitry Andric #ifndef NDEBUG 3530b57cec5SDimitry Andric else 3540b57cec5SDimitry Andric AfterSet.insert(&MI); 3550b57cec5SDimitry Andric #endif 3560b57cec5SDimitry Andric } 3570b57cec5SDimitry Andric } 3580b57cec5SDimitry Andric 3590b57cec5SDimitry Andric // Mark the end of the block. 3600b57cec5SDimitry Andric InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 3610b57cec5SDimitry Andric MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos), 3620b57cec5SDimitry Andric TII.get(WebAssembly::END_BLOCK)); 3630b57cec5SDimitry Andric registerScope(Begin, End); 3640b57cec5SDimitry Andric 3650b57cec5SDimitry Andric // Track the farthest-spanning scope that ends at this point. 3660b57cec5SDimitry Andric int Number = MBB.getNumber(); 3670b57cec5SDimitry Andric if (!ScopeTops[Number] || 3680b57cec5SDimitry Andric ScopeTops[Number]->getNumber() > Header->getNumber()) 3690b57cec5SDimitry Andric ScopeTops[Number] = Header; 3700b57cec5SDimitry Andric } 3710b57cec5SDimitry Andric 3720b57cec5SDimitry Andric /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 3730b57cec5SDimitry Andric void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) { 3740b57cec5SDimitry Andric MachineFunction &MF = *MBB.getParent(); 3750b57cec5SDimitry Andric const auto &MLI = getAnalysis<MachineLoopInfo>(); 3760b57cec5SDimitry Andric const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 3770b57cec5SDimitry Andric 3780b57cec5SDimitry Andric MachineLoop *Loop = MLI.getLoopFor(&MBB); 3790b57cec5SDimitry Andric if (!Loop || Loop->getHeader() != &MBB) 3800b57cec5SDimitry Andric return; 3810b57cec5SDimitry Andric 3820b57cec5SDimitry Andric // The operand of a LOOP is the first block after the loop. If the loop is the 3830b57cec5SDimitry Andric // bottom of the function, insert a dummy block at the end. 3840b57cec5SDimitry Andric MachineBasicBlock *Bottom = WebAssembly::getBottom(Loop); 3850b57cec5SDimitry Andric auto Iter = std::next(Bottom->getIterator()); 3860b57cec5SDimitry Andric if (Iter == MF.end()) { 3870b57cec5SDimitry Andric getAppendixBlock(MF); 3880b57cec5SDimitry Andric Iter = std::next(Bottom->getIterator()); 3890b57cec5SDimitry Andric } 3900b57cec5SDimitry Andric MachineBasicBlock *AfterLoop = &*Iter; 3910b57cec5SDimitry Andric 3920b57cec5SDimitry Andric // Decide where in Header to put the LOOP. 3930b57cec5SDimitry Andric SmallPtrSet<const MachineInstr *, 4> BeforeSet; 3940b57cec5SDimitry Andric SmallPtrSet<const MachineInstr *, 4> AfterSet; 3950b57cec5SDimitry Andric for (const auto &MI : MBB) { 3960b57cec5SDimitry Andric // LOOP marker should be after any existing loop that ends here. Otherwise 3970b57cec5SDimitry Andric // we assume the instruction belongs to the loop. 3980b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::END_LOOP) 3990b57cec5SDimitry Andric BeforeSet.insert(&MI); 4000b57cec5SDimitry Andric #ifndef NDEBUG 4010b57cec5SDimitry Andric else 4020b57cec5SDimitry Andric AfterSet.insert(&MI); 4030b57cec5SDimitry Andric #endif 4040b57cec5SDimitry Andric } 4050b57cec5SDimitry Andric 4060b57cec5SDimitry Andric // Mark the beginning of the loop. 4070b57cec5SDimitry Andric auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 4080b57cec5SDimitry Andric MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos), 4090b57cec5SDimitry Andric TII.get(WebAssembly::LOOP)) 410*8bcb0991SDimitry Andric .addImm(int64_t(WebAssembly::BlockType::Void)); 4110b57cec5SDimitry Andric 4120b57cec5SDimitry Andric // Decide where in Header to put the END_LOOP. 4130b57cec5SDimitry Andric BeforeSet.clear(); 4140b57cec5SDimitry Andric AfterSet.clear(); 4150b57cec5SDimitry Andric #ifndef NDEBUG 4160b57cec5SDimitry Andric for (const auto &MI : MBB) 4170b57cec5SDimitry Andric // Existing END_LOOP markers belong to parent loops of this loop 4180b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::END_LOOP) 4190b57cec5SDimitry Andric AfterSet.insert(&MI); 4200b57cec5SDimitry Andric #endif 4210b57cec5SDimitry Andric 4220b57cec5SDimitry Andric // Mark the end of the loop (using arbitrary debug location that branched to 4230b57cec5SDimitry Andric // the loop end as its location). 4240b57cec5SDimitry Andric InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet); 4250b57cec5SDimitry Andric DebugLoc EndDL = AfterLoop->pred_empty() 4260b57cec5SDimitry Andric ? DebugLoc() 4270b57cec5SDimitry Andric : (*AfterLoop->pred_rbegin())->findBranchDebugLoc(); 4280b57cec5SDimitry Andric MachineInstr *End = 4290b57cec5SDimitry Andric BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP)); 4300b57cec5SDimitry Andric registerScope(Begin, End); 4310b57cec5SDimitry Andric 4320b57cec5SDimitry Andric assert((!ScopeTops[AfterLoop->getNumber()] || 4330b57cec5SDimitry Andric ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 4340b57cec5SDimitry Andric "With block sorting the outermost loop for a block should be first."); 4350b57cec5SDimitry Andric if (!ScopeTops[AfterLoop->getNumber()]) 4360b57cec5SDimitry Andric ScopeTops[AfterLoop->getNumber()] = &MBB; 4370b57cec5SDimitry Andric } 4380b57cec5SDimitry Andric 4390b57cec5SDimitry Andric void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) { 4400b57cec5SDimitry Andric assert(MBB.isEHPad()); 4410b57cec5SDimitry Andric MachineFunction &MF = *MBB.getParent(); 4420b57cec5SDimitry Andric auto &MDT = getAnalysis<MachineDominatorTree>(); 4430b57cec5SDimitry Andric const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 4440b57cec5SDimitry Andric const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 4450b57cec5SDimitry Andric const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 4460b57cec5SDimitry Andric 4470b57cec5SDimitry Andric // Compute the nearest common dominator of all unwind predecessors 4480b57cec5SDimitry Andric MachineBasicBlock *Header = nullptr; 4490b57cec5SDimitry Andric int MBBNumber = MBB.getNumber(); 4500b57cec5SDimitry Andric for (auto *Pred : MBB.predecessors()) { 4510b57cec5SDimitry Andric if (Pred->getNumber() < MBBNumber) { 4520b57cec5SDimitry Andric Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 4530b57cec5SDimitry Andric assert(!explicitlyBranchesTo(Pred, &MBB) && 4540b57cec5SDimitry Andric "Explicit branch to an EH pad!"); 4550b57cec5SDimitry Andric } 4560b57cec5SDimitry Andric } 4570b57cec5SDimitry Andric if (!Header) 4580b57cec5SDimitry Andric return; 4590b57cec5SDimitry Andric 4600b57cec5SDimitry Andric // If this try is at the bottom of the function, insert a dummy block at the 4610b57cec5SDimitry Andric // end. 4620b57cec5SDimitry Andric WebAssemblyException *WE = WEI.getExceptionFor(&MBB); 4630b57cec5SDimitry Andric assert(WE); 4640b57cec5SDimitry Andric MachineBasicBlock *Bottom = WebAssembly::getBottom(WE); 4650b57cec5SDimitry Andric 4660b57cec5SDimitry Andric auto Iter = std::next(Bottom->getIterator()); 4670b57cec5SDimitry Andric if (Iter == MF.end()) { 4680b57cec5SDimitry Andric getAppendixBlock(MF); 4690b57cec5SDimitry Andric Iter = std::next(Bottom->getIterator()); 4700b57cec5SDimitry Andric } 4710b57cec5SDimitry Andric MachineBasicBlock *Cont = &*Iter; 4720b57cec5SDimitry Andric 4730b57cec5SDimitry Andric assert(Cont != &MF.front()); 4740b57cec5SDimitry Andric MachineBasicBlock *LayoutPred = Cont->getPrevNode(); 4750b57cec5SDimitry Andric 4760b57cec5SDimitry Andric // If the nearest common dominator is inside a more deeply nested context, 4770b57cec5SDimitry Andric // walk out to the nearest scope which isn't more deeply nested. 4780b57cec5SDimitry Andric for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 4790b57cec5SDimitry Andric if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 4800b57cec5SDimitry Andric if (ScopeTop->getNumber() > Header->getNumber()) { 4810b57cec5SDimitry Andric // Skip over an intervening scope. 4820b57cec5SDimitry Andric I = std::next(ScopeTop->getIterator()); 4830b57cec5SDimitry Andric } else { 4840b57cec5SDimitry Andric // We found a scope level at an appropriate depth. 4850b57cec5SDimitry Andric Header = ScopeTop; 4860b57cec5SDimitry Andric break; 4870b57cec5SDimitry Andric } 4880b57cec5SDimitry Andric } 4890b57cec5SDimitry Andric } 4900b57cec5SDimitry Andric 4910b57cec5SDimitry Andric // Decide where in Header to put the TRY. 4920b57cec5SDimitry Andric 4930b57cec5SDimitry Andric // Instructions that should go before the TRY. 4940b57cec5SDimitry Andric SmallPtrSet<const MachineInstr *, 4> BeforeSet; 4950b57cec5SDimitry Andric // Instructions that should go after the TRY. 4960b57cec5SDimitry Andric SmallPtrSet<const MachineInstr *, 4> AfterSet; 4970b57cec5SDimitry Andric for (const auto &MI : *Header) { 4980b57cec5SDimitry Andric // If there is a previously placed LOOP marker and the bottom block of the 4990b57cec5SDimitry Andric // loop is above MBB, it should be after the TRY, because the loop is nested 5000b57cec5SDimitry Andric // in this TRY. Otherwise it should be before the TRY. 5010b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::LOOP) { 5020b57cec5SDimitry Andric auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 5030b57cec5SDimitry Andric if (MBB.getNumber() > LoopBottom->getNumber()) 5040b57cec5SDimitry Andric AfterSet.insert(&MI); 5050b57cec5SDimitry Andric #ifndef NDEBUG 5060b57cec5SDimitry Andric else 5070b57cec5SDimitry Andric BeforeSet.insert(&MI); 5080b57cec5SDimitry Andric #endif 5090b57cec5SDimitry Andric } 5100b57cec5SDimitry Andric 5110b57cec5SDimitry Andric // All previously inserted BLOCK/TRY markers should be after the TRY because 5120b57cec5SDimitry Andric // they are all nested trys. 5130b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::BLOCK || 5140b57cec5SDimitry Andric MI.getOpcode() == WebAssembly::TRY) 5150b57cec5SDimitry Andric AfterSet.insert(&MI); 5160b57cec5SDimitry Andric 5170b57cec5SDimitry Andric #ifndef NDEBUG 5180b57cec5SDimitry Andric // All END_(BLOCK/LOOP/TRY) markers should be before the TRY. 5190b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::END_BLOCK || 5200b57cec5SDimitry Andric MI.getOpcode() == WebAssembly::END_LOOP || 5210b57cec5SDimitry Andric MI.getOpcode() == WebAssembly::END_TRY) 5220b57cec5SDimitry Andric BeforeSet.insert(&MI); 5230b57cec5SDimitry Andric #endif 5240b57cec5SDimitry Andric 5250b57cec5SDimitry Andric // Terminators should go after the TRY. 5260b57cec5SDimitry Andric if (MI.isTerminator()) 5270b57cec5SDimitry Andric AfterSet.insert(&MI); 5280b57cec5SDimitry Andric } 5290b57cec5SDimitry Andric 530*8bcb0991SDimitry Andric // If Header unwinds to MBB (= Header contains 'invoke'), the try block should 531*8bcb0991SDimitry Andric // contain the call within it. So the call should go after the TRY. The 532*8bcb0991SDimitry Andric // exception is when the header's terminator is a rethrow instruction, in 533*8bcb0991SDimitry Andric // which case that instruction, not a call instruction before it, is gonna 534*8bcb0991SDimitry Andric // throw. 535*8bcb0991SDimitry Andric MachineInstr *ThrowingCall = nullptr; 536*8bcb0991SDimitry Andric if (MBB.isPredecessor(Header)) { 537*8bcb0991SDimitry Andric auto TermPos = Header->getFirstTerminator(); 538*8bcb0991SDimitry Andric if (TermPos == Header->end() || 539*8bcb0991SDimitry Andric TermPos->getOpcode() != WebAssembly::RETHROW) { 540*8bcb0991SDimitry Andric for (auto &MI : reverse(*Header)) { 541*8bcb0991SDimitry Andric if (MI.isCall()) { 542*8bcb0991SDimitry Andric AfterSet.insert(&MI); 543*8bcb0991SDimitry Andric ThrowingCall = &MI; 544*8bcb0991SDimitry Andric // Possibly throwing calls are usually wrapped by EH_LABEL 545*8bcb0991SDimitry Andric // instructions. We don't want to split them and the call. 546*8bcb0991SDimitry Andric if (MI.getIterator() != Header->begin() && 547*8bcb0991SDimitry Andric std::prev(MI.getIterator())->isEHLabel()) { 548*8bcb0991SDimitry Andric AfterSet.insert(&*std::prev(MI.getIterator())); 549*8bcb0991SDimitry Andric ThrowingCall = &*std::prev(MI.getIterator()); 550*8bcb0991SDimitry Andric } 551*8bcb0991SDimitry Andric break; 552*8bcb0991SDimitry Andric } 553*8bcb0991SDimitry Andric } 554*8bcb0991SDimitry Andric } 555*8bcb0991SDimitry Andric } 556*8bcb0991SDimitry Andric 5570b57cec5SDimitry Andric // Local expression tree should go after the TRY. 558*8bcb0991SDimitry Andric // For BLOCK placement, we start the search from the previous instruction of a 559*8bcb0991SDimitry Andric // BB's terminator, but in TRY's case, we should start from the previous 560*8bcb0991SDimitry Andric // instruction of a call that can throw, or a EH_LABEL that precedes the call, 561*8bcb0991SDimitry Andric // because the return values of the call's previous instructions can be 562*8bcb0991SDimitry Andric // stackified and consumed by the throwing call. 563*8bcb0991SDimitry Andric auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall) 564*8bcb0991SDimitry Andric : Header->getFirstTerminator(); 565*8bcb0991SDimitry Andric for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) { 5660b57cec5SDimitry Andric if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 5670b57cec5SDimitry Andric continue; 5680b57cec5SDimitry Andric if (WebAssembly::isChild(*std::prev(I), MFI)) 5690b57cec5SDimitry Andric AfterSet.insert(&*std::prev(I)); 5700b57cec5SDimitry Andric else 5710b57cec5SDimitry Andric break; 5720b57cec5SDimitry Andric } 5730b57cec5SDimitry Andric 5740b57cec5SDimitry Andric // Add the TRY. 5750b57cec5SDimitry Andric auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 5760b57cec5SDimitry Andric MachineInstr *Begin = 5770b57cec5SDimitry Andric BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 5780b57cec5SDimitry Andric TII.get(WebAssembly::TRY)) 579*8bcb0991SDimitry Andric .addImm(int64_t(WebAssembly::BlockType::Void)); 5800b57cec5SDimitry Andric 5810b57cec5SDimitry Andric // Decide where in Header to put the END_TRY. 5820b57cec5SDimitry Andric BeforeSet.clear(); 5830b57cec5SDimitry Andric AfterSet.clear(); 5840b57cec5SDimitry Andric for (const auto &MI : *Cont) { 5850b57cec5SDimitry Andric #ifndef NDEBUG 5860b57cec5SDimitry Andric // END_TRY should precede existing LOOP and BLOCK markers. 5870b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::LOOP || 5880b57cec5SDimitry Andric MI.getOpcode() == WebAssembly::BLOCK) 5890b57cec5SDimitry Andric AfterSet.insert(&MI); 5900b57cec5SDimitry Andric 5910b57cec5SDimitry Andric // All END_TRY markers placed earlier belong to exceptions that contains 5920b57cec5SDimitry Andric // this one. 5930b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::END_TRY) 5940b57cec5SDimitry Andric AfterSet.insert(&MI); 5950b57cec5SDimitry Andric #endif 5960b57cec5SDimitry Andric 5970b57cec5SDimitry Andric // If there is a previously placed END_LOOP marker and its header is after 5980b57cec5SDimitry Andric // where TRY marker is, this loop is contained within the 'catch' part, so 5990b57cec5SDimitry Andric // the END_TRY marker should go after that. Otherwise, the whole try-catch 6000b57cec5SDimitry Andric // is contained within this loop, so the END_TRY should go before that. 6010b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::END_LOOP) { 6020b57cec5SDimitry Andric // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they 6030b57cec5SDimitry Andric // are in the same BB, LOOP is always before TRY. 6040b57cec5SDimitry Andric if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber()) 6050b57cec5SDimitry Andric BeforeSet.insert(&MI); 6060b57cec5SDimitry Andric #ifndef NDEBUG 6070b57cec5SDimitry Andric else 6080b57cec5SDimitry Andric AfterSet.insert(&MI); 6090b57cec5SDimitry Andric #endif 6100b57cec5SDimitry Andric } 6110b57cec5SDimitry Andric 6120b57cec5SDimitry Andric // It is not possible for an END_BLOCK to be already in this block. 6130b57cec5SDimitry Andric } 6140b57cec5SDimitry Andric 6150b57cec5SDimitry Andric // Mark the end of the TRY. 6160b57cec5SDimitry Andric InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet); 6170b57cec5SDimitry Andric MachineInstr *End = 6180b57cec5SDimitry Andric BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(), 6190b57cec5SDimitry Andric TII.get(WebAssembly::END_TRY)); 6200b57cec5SDimitry Andric registerTryScope(Begin, End, &MBB); 6210b57cec5SDimitry Andric 6220b57cec5SDimitry Andric // Track the farthest-spanning scope that ends at this point. We create two 6230b57cec5SDimitry Andric // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB 6240b57cec5SDimitry Andric // with 'try'). We need to create 'catch' -> 'try' mapping here too because 6250b57cec5SDimitry Andric // markers should not span across 'catch'. For example, this should not 6260b57cec5SDimitry Andric // happen: 6270b57cec5SDimitry Andric // 6280b57cec5SDimitry Andric // try 6290b57cec5SDimitry Andric // block --| (X) 6300b57cec5SDimitry Andric // catch | 6310b57cec5SDimitry Andric // end_block --| 6320b57cec5SDimitry Andric // end_try 6330b57cec5SDimitry Andric for (int Number : {Cont->getNumber(), MBB.getNumber()}) { 6340b57cec5SDimitry Andric if (!ScopeTops[Number] || 6350b57cec5SDimitry Andric ScopeTops[Number]->getNumber() > Header->getNumber()) 6360b57cec5SDimitry Andric ScopeTops[Number] = Header; 6370b57cec5SDimitry Andric } 6380b57cec5SDimitry Andric } 6390b57cec5SDimitry Andric 6400b57cec5SDimitry Andric void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) { 6410b57cec5SDimitry Andric const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 6420b57cec5SDimitry Andric 6430b57cec5SDimitry Andric // When there is an unconditional branch right before a catch instruction and 6440b57cec5SDimitry Andric // it branches to the end of end_try marker, we don't need the branch, because 6450b57cec5SDimitry Andric // it there is no exception, the control flow transfers to that point anyway. 6460b57cec5SDimitry Andric // bb0: 6470b57cec5SDimitry Andric // try 6480b57cec5SDimitry Andric // ... 6490b57cec5SDimitry Andric // br bb2 <- Not necessary 6500b57cec5SDimitry Andric // bb1: 6510b57cec5SDimitry Andric // catch 6520b57cec5SDimitry Andric // ... 6530b57cec5SDimitry Andric // bb2: 6540b57cec5SDimitry Andric // end 6550b57cec5SDimitry Andric for (auto &MBB : MF) { 6560b57cec5SDimitry Andric if (!MBB.isEHPad()) 6570b57cec5SDimitry Andric continue; 6580b57cec5SDimitry Andric 6590b57cec5SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 6600b57cec5SDimitry Andric SmallVector<MachineOperand, 4> Cond; 6610b57cec5SDimitry Andric MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode(); 6620b57cec5SDimitry Andric MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent(); 6630b57cec5SDimitry Andric bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond); 6640b57cec5SDimitry Andric if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) || 6650b57cec5SDimitry Andric (!Cond.empty() && FBB && FBB == Cont))) 6660b57cec5SDimitry Andric TII.removeBranch(*EHPadLayoutPred); 6670b57cec5SDimitry Andric } 6680b57cec5SDimitry Andric 6690b57cec5SDimitry Andric // When there are block / end_block markers that overlap with try / end_try 6700b57cec5SDimitry Andric // markers, and the block and try markers' return types are the same, the 6710b57cec5SDimitry Andric // block /end_block markers are not necessary, because try / end_try markers 6720b57cec5SDimitry Andric // also can serve as boundaries for branches. 6730b57cec5SDimitry Andric // block <- Not necessary 6740b57cec5SDimitry Andric // try 6750b57cec5SDimitry Andric // ... 6760b57cec5SDimitry Andric // catch 6770b57cec5SDimitry Andric // ... 6780b57cec5SDimitry Andric // end 6790b57cec5SDimitry Andric // end <- Not necessary 6800b57cec5SDimitry Andric SmallVector<MachineInstr *, 32> ToDelete; 6810b57cec5SDimitry Andric for (auto &MBB : MF) { 6820b57cec5SDimitry Andric for (auto &MI : MBB) { 6830b57cec5SDimitry Andric if (MI.getOpcode() != WebAssembly::TRY) 6840b57cec5SDimitry Andric continue; 6850b57cec5SDimitry Andric 6860b57cec5SDimitry Andric MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try]; 6870b57cec5SDimitry Andric MachineBasicBlock *TryBB = Try->getParent(); 6880b57cec5SDimitry Andric MachineBasicBlock *Cont = EndTry->getParent(); 6890b57cec5SDimitry Andric int64_t RetType = Try->getOperand(0).getImm(); 6900b57cec5SDimitry Andric for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator()); 6910b57cec5SDimitry Andric B != TryBB->begin() && E != Cont->end() && 6920b57cec5SDimitry Andric std::prev(B)->getOpcode() == WebAssembly::BLOCK && 6930b57cec5SDimitry Andric E->getOpcode() == WebAssembly::END_BLOCK && 6940b57cec5SDimitry Andric std::prev(B)->getOperand(0).getImm() == RetType; 6950b57cec5SDimitry Andric --B, ++E) { 6960b57cec5SDimitry Andric ToDelete.push_back(&*std::prev(B)); 6970b57cec5SDimitry Andric ToDelete.push_back(&*E); 6980b57cec5SDimitry Andric } 6990b57cec5SDimitry Andric } 7000b57cec5SDimitry Andric } 7010b57cec5SDimitry Andric for (auto *MI : ToDelete) { 7020b57cec5SDimitry Andric if (MI->getOpcode() == WebAssembly::BLOCK) 7030b57cec5SDimitry Andric unregisterScope(MI); 7040b57cec5SDimitry Andric MI->eraseFromParent(); 7050b57cec5SDimitry Andric } 7060b57cec5SDimitry Andric } 7070b57cec5SDimitry Andric 708*8bcb0991SDimitry Andric // When MBB is split into MBB and Split, we should unstackify defs in MBB that 709*8bcb0991SDimitry Andric // have their uses in Split. 710*8bcb0991SDimitry Andric static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, 711*8bcb0991SDimitry Andric MachineBasicBlock &Split, 712*8bcb0991SDimitry Andric WebAssemblyFunctionInfo &MFI, 713*8bcb0991SDimitry Andric MachineRegisterInfo &MRI) { 714*8bcb0991SDimitry Andric for (auto &MI : Split) { 715*8bcb0991SDimitry Andric for (auto &MO : MI.explicit_uses()) { 716*8bcb0991SDimitry Andric if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg())) 717*8bcb0991SDimitry Andric continue; 718*8bcb0991SDimitry Andric if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg())) 719*8bcb0991SDimitry Andric if (Def->getParent() == &MBB) 720*8bcb0991SDimitry Andric MFI.unstackifyVReg(MO.getReg()); 721*8bcb0991SDimitry Andric } 722*8bcb0991SDimitry Andric } 723*8bcb0991SDimitry Andric } 724*8bcb0991SDimitry Andric 7250b57cec5SDimitry Andric bool WebAssemblyCFGStackify::fixUnwindMismatches(MachineFunction &MF) { 7260b57cec5SDimitry Andric const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 727*8bcb0991SDimitry Andric auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 7280b57cec5SDimitry Andric MachineRegisterInfo &MRI = MF.getRegInfo(); 7290b57cec5SDimitry Andric 7300b57cec5SDimitry Andric // Linearizing the control flow by placing TRY / END_TRY markers can create 7310b57cec5SDimitry Andric // mismatches in unwind destinations. There are two kinds of mismatches we 7320b57cec5SDimitry Andric // try to solve here. 7330b57cec5SDimitry Andric 7340b57cec5SDimitry Andric // 1. When an instruction may throw, but the EH pad it will unwind to can be 7350b57cec5SDimitry Andric // different from the original CFG. 7360b57cec5SDimitry Andric // 7370b57cec5SDimitry Andric // Example: we have the following CFG: 7380b57cec5SDimitry Andric // bb0: 7390b57cec5SDimitry Andric // call @foo (if it throws, unwind to bb2) 7400b57cec5SDimitry Andric // bb1: 7410b57cec5SDimitry Andric // call @bar (if it throws, unwind to bb3) 7420b57cec5SDimitry Andric // bb2 (ehpad): 7430b57cec5SDimitry Andric // catch 7440b57cec5SDimitry Andric // ... 7450b57cec5SDimitry Andric // bb3 (ehpad) 7460b57cec5SDimitry Andric // catch 7470b57cec5SDimitry Andric // handler body 7480b57cec5SDimitry Andric // 7490b57cec5SDimitry Andric // And the CFG is sorted in this order. Then after placing TRY markers, it 7500b57cec5SDimitry Andric // will look like: (BB markers are omitted) 7510b57cec5SDimitry Andric // try $label1 7520b57cec5SDimitry Andric // try 7530b57cec5SDimitry Andric // call @foo 7540b57cec5SDimitry Andric // call @bar (if it throws, unwind to bb3) 7550b57cec5SDimitry Andric // catch <- ehpad (bb2) 7560b57cec5SDimitry Andric // ... 7570b57cec5SDimitry Andric // end_try 7580b57cec5SDimitry Andric // catch <- ehpad (bb3) 7590b57cec5SDimitry Andric // handler body 7600b57cec5SDimitry Andric // end_try 7610b57cec5SDimitry Andric // 7620b57cec5SDimitry Andric // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it 7630b57cec5SDimitry Andric // is supposed to end up. We solve this problem by 7640b57cec5SDimitry Andric // a. Split the target unwind EH pad (here bb3) so that the handler body is 7650b57cec5SDimitry Andric // right after 'end_try', which means we extract the handler body out of 7660b57cec5SDimitry Andric // the catch block. We do this because this handler body should be 7670b57cec5SDimitry Andric // somewhere branch-eable from the inner scope. 7680b57cec5SDimitry Andric // b. Wrap the call that has an incorrect unwind destination ('call @bar' 7690b57cec5SDimitry Andric // here) with a nested try/catch/end_try scope, and within the new catch 7700b57cec5SDimitry Andric // block, branches to the handler body. 7710b57cec5SDimitry Andric // c. Place a branch after the newly inserted nested end_try so it can bypass 7720b57cec5SDimitry Andric // the handler body, which is now outside of a catch block. 7730b57cec5SDimitry Andric // 7740b57cec5SDimitry Andric // The result will like as follows. (new: a) means this instruction is newly 7750b57cec5SDimitry Andric // created in the process of doing 'a' above. 7760b57cec5SDimitry Andric // 7770b57cec5SDimitry Andric // block $label0 (new: placeBlockMarker) 7780b57cec5SDimitry Andric // try $label1 7790b57cec5SDimitry Andric // try 7800b57cec5SDimitry Andric // call @foo 7810b57cec5SDimitry Andric // try (new: b) 7820b57cec5SDimitry Andric // call @bar 7830b57cec5SDimitry Andric // catch (new: b) 7840b57cec5SDimitry Andric // local.set n / drop (new: b) 7850b57cec5SDimitry Andric // br $label1 (new: b) 7860b57cec5SDimitry Andric // end_try (new: b) 7870b57cec5SDimitry Andric // catch <- ehpad (bb2) 7880b57cec5SDimitry Andric // end_try 7890b57cec5SDimitry Andric // br $label0 (new: c) 7900b57cec5SDimitry Andric // catch <- ehpad (bb3) 7910b57cec5SDimitry Andric // end_try (hoisted: a) 7920b57cec5SDimitry Andric // handler body 7930b57cec5SDimitry Andric // end_block (new: placeBlockMarker) 7940b57cec5SDimitry Andric // 7950b57cec5SDimitry Andric // Note that the new wrapping block/end_block will be generated later in 7960b57cec5SDimitry Andric // placeBlockMarker. 7970b57cec5SDimitry Andric // 7980b57cec5SDimitry Andric // TODO Currently local.set and local.gets are generated to move exnref value 7990b57cec5SDimitry Andric // created by catches. That's because we don't support yielding values from a 8000b57cec5SDimitry Andric // block in LLVM machine IR yet, even though it is supported by wasm. Delete 8010b57cec5SDimitry Andric // unnecessary local.get/local.sets once yielding values from a block is 8020b57cec5SDimitry Andric // supported. The full EH spec requires multi-value support to do this, but 8030b57cec5SDimitry Andric // for C++ we don't yet need it because we only throw a single i32. 8040b57cec5SDimitry Andric // 8050b57cec5SDimitry Andric // --- 8060b57cec5SDimitry Andric // 2. The same as 1, but in this case an instruction unwinds to a caller 8070b57cec5SDimitry Andric // function and not another EH pad. 8080b57cec5SDimitry Andric // 8090b57cec5SDimitry Andric // Example: we have the following CFG: 8100b57cec5SDimitry Andric // bb0: 8110b57cec5SDimitry Andric // call @foo (if it throws, unwind to bb2) 8120b57cec5SDimitry Andric // bb1: 8130b57cec5SDimitry Andric // call @bar (if it throws, unwind to caller) 8140b57cec5SDimitry Andric // bb2 (ehpad): 8150b57cec5SDimitry Andric // catch 8160b57cec5SDimitry Andric // ... 8170b57cec5SDimitry Andric // 8180b57cec5SDimitry Andric // And the CFG is sorted in this order. Then after placing TRY markers, it 8190b57cec5SDimitry Andric // will look like: 8200b57cec5SDimitry Andric // try 8210b57cec5SDimitry Andric // call @foo 8220b57cec5SDimitry Andric // call @bar (if it throws, unwind to caller) 8230b57cec5SDimitry Andric // catch <- ehpad (bb2) 8240b57cec5SDimitry Andric // ... 8250b57cec5SDimitry Andric // end_try 8260b57cec5SDimitry Andric // 8270b57cec5SDimitry Andric // Now if bar() throws, it is going to end up ip in bb2, when it is supposed 8280b57cec5SDimitry Andric // throw up to the caller. 8290b57cec5SDimitry Andric // We solve this problem by 8300b57cec5SDimitry Andric // a. Create a new 'appendix' BB at the end of the function and put a single 8310b57cec5SDimitry Andric // 'rethrow' instruction (+ local.get) in there. 8320b57cec5SDimitry Andric // b. Wrap the call that has an incorrect unwind destination ('call @bar' 8330b57cec5SDimitry Andric // here) with a nested try/catch/end_try scope, and within the new catch 8340b57cec5SDimitry Andric // block, branches to the new appendix block. 8350b57cec5SDimitry Andric // 8360b57cec5SDimitry Andric // block $label0 (new: placeBlockMarker) 8370b57cec5SDimitry Andric // try 8380b57cec5SDimitry Andric // call @foo 8390b57cec5SDimitry Andric // try (new: b) 8400b57cec5SDimitry Andric // call @bar 8410b57cec5SDimitry Andric // catch (new: b) 8420b57cec5SDimitry Andric // local.set n (new: b) 8430b57cec5SDimitry Andric // br $label0 (new: b) 8440b57cec5SDimitry Andric // end_try (new: b) 8450b57cec5SDimitry Andric // catch <- ehpad (bb2) 8460b57cec5SDimitry Andric // ... 8470b57cec5SDimitry Andric // end_try 8480b57cec5SDimitry Andric // ... 8490b57cec5SDimitry Andric // end_block (new: placeBlockMarker) 8500b57cec5SDimitry Andric // local.get n (new: a) <- appendix block 8510b57cec5SDimitry Andric // rethrow (new: a) 8520b57cec5SDimitry Andric // 8530b57cec5SDimitry Andric // In case there are multiple calls in a BB that may throw to the caller, they 8540b57cec5SDimitry Andric // can be wrapped together in one nested try scope. (In 1, this couldn't 8550b57cec5SDimitry Andric // happen, because may-throwing instruction there had an unwind destination, 8560b57cec5SDimitry Andric // i.e., it was an invoke before, and there could be only one invoke within a 8570b57cec5SDimitry Andric // BB.) 8580b57cec5SDimitry Andric 8590b57cec5SDimitry Andric SmallVector<const MachineBasicBlock *, 8> EHPadStack; 8600b57cec5SDimitry Andric // Range of intructions to be wrapped in a new nested try/catch 8610b57cec5SDimitry Andric using TryRange = std::pair<MachineInstr *, MachineInstr *>; 862*8bcb0991SDimitry Andric // In original CFG, <unwind destination BB, a vector of try ranges> 8630b57cec5SDimitry Andric DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges; 8640b57cec5SDimitry Andric // In new CFG, <destination to branch to, a vector of try ranges> 8650b57cec5SDimitry Andric DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> BrDestToTryRanges; 8660b57cec5SDimitry Andric // In new CFG, <destination to branch to, register containing exnref> 8670b57cec5SDimitry Andric DenseMap<MachineBasicBlock *, unsigned> BrDestToExnReg; 8680b57cec5SDimitry Andric 8690b57cec5SDimitry Andric // Gather possibly throwing calls (i.e., previously invokes) whose current 8700b57cec5SDimitry Andric // unwind destination is not the same as the original CFG. 8710b57cec5SDimitry Andric for (auto &MBB : reverse(MF)) { 8720b57cec5SDimitry Andric bool SeenThrowableInstInBB = false; 8730b57cec5SDimitry Andric for (auto &MI : reverse(MBB)) { 8740b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::TRY) 8750b57cec5SDimitry Andric EHPadStack.pop_back(); 8760b57cec5SDimitry Andric else if (MI.getOpcode() == WebAssembly::CATCH) 8770b57cec5SDimitry Andric EHPadStack.push_back(MI.getParent()); 8780b57cec5SDimitry Andric 8790b57cec5SDimitry Andric // In this loop we only gather calls that have an EH pad to unwind. So 8800b57cec5SDimitry Andric // there will be at most 1 such call (= invoke) in a BB, so after we've 8810b57cec5SDimitry Andric // seen one, we can skip the rest of BB. Also if MBB has no EH pad 8820b57cec5SDimitry Andric // successor or MI does not throw, this is not an invoke. 8830b57cec5SDimitry Andric if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() || 8840b57cec5SDimitry Andric !WebAssembly::mayThrow(MI)) 8850b57cec5SDimitry Andric continue; 8860b57cec5SDimitry Andric SeenThrowableInstInBB = true; 8870b57cec5SDimitry Andric 8880b57cec5SDimitry Andric // If the EH pad on the stack top is where this instruction should unwind 8890b57cec5SDimitry Andric // next, we're good. 8900b57cec5SDimitry Andric MachineBasicBlock *UnwindDest = nullptr; 8910b57cec5SDimitry Andric for (auto *Succ : MBB.successors()) { 8920b57cec5SDimitry Andric if (Succ->isEHPad()) { 8930b57cec5SDimitry Andric UnwindDest = Succ; 8940b57cec5SDimitry Andric break; 8950b57cec5SDimitry Andric } 8960b57cec5SDimitry Andric } 8970b57cec5SDimitry Andric if (EHPadStack.back() == UnwindDest) 8980b57cec5SDimitry Andric continue; 8990b57cec5SDimitry Andric 9000b57cec5SDimitry Andric // If not, record the range. 9010b57cec5SDimitry Andric UnwindDestToTryRanges[UnwindDest].push_back(TryRange(&MI, &MI)); 9020b57cec5SDimitry Andric } 9030b57cec5SDimitry Andric } 9040b57cec5SDimitry Andric 9050b57cec5SDimitry Andric assert(EHPadStack.empty()); 9060b57cec5SDimitry Andric 9070b57cec5SDimitry Andric // Gather possibly throwing calls that are supposed to unwind up to the caller 9080b57cec5SDimitry Andric // if they throw, but currently unwind to an incorrect destination. Unlike the 9090b57cec5SDimitry Andric // loop above, there can be multiple calls within a BB that unwind to the 9100b57cec5SDimitry Andric // caller, which we should group together in a range. 9110b57cec5SDimitry Andric bool NeedAppendixBlock = false; 9120b57cec5SDimitry Andric for (auto &MBB : reverse(MF)) { 9130b57cec5SDimitry Andric MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive 9140b57cec5SDimitry Andric for (auto &MI : reverse(MBB)) { 9150b57cec5SDimitry Andric if (MI.getOpcode() == WebAssembly::TRY) 9160b57cec5SDimitry Andric EHPadStack.pop_back(); 9170b57cec5SDimitry Andric else if (MI.getOpcode() == WebAssembly::CATCH) 9180b57cec5SDimitry Andric EHPadStack.push_back(MI.getParent()); 9190b57cec5SDimitry Andric 9200b57cec5SDimitry Andric // If MBB has an EH pad successor, this inst does not unwind to caller. 9210b57cec5SDimitry Andric if (MBB.hasEHPadSuccessor()) 9220b57cec5SDimitry Andric continue; 9230b57cec5SDimitry Andric 9240b57cec5SDimitry Andric // We wrap up the current range when we see a marker even if we haven't 9250b57cec5SDimitry Andric // finished a BB. 9260b57cec5SDimitry Andric if (RangeEnd && WebAssembly::isMarker(MI.getOpcode())) { 9270b57cec5SDimitry Andric NeedAppendixBlock = true; 9280b57cec5SDimitry Andric // Record the range. nullptr here means the unwind destination is the 9290b57cec5SDimitry Andric // caller. 9300b57cec5SDimitry Andric UnwindDestToTryRanges[nullptr].push_back( 9310b57cec5SDimitry Andric TryRange(RangeBegin, RangeEnd)); 9320b57cec5SDimitry Andric RangeBegin = RangeEnd = nullptr; // Reset range pointers 9330b57cec5SDimitry Andric } 9340b57cec5SDimitry Andric 9350b57cec5SDimitry Andric // If EHPadStack is empty, that means it is correctly unwind to caller if 9360b57cec5SDimitry Andric // it throws, so we're good. If MI does not throw, we're good too. 9370b57cec5SDimitry Andric if (EHPadStack.empty() || !WebAssembly::mayThrow(MI)) 9380b57cec5SDimitry Andric continue; 9390b57cec5SDimitry Andric 9400b57cec5SDimitry Andric // We found an instruction that unwinds to the caller but currently has an 9410b57cec5SDimitry Andric // incorrect unwind destination. Create a new range or increment the 9420b57cec5SDimitry Andric // currently existing range. 9430b57cec5SDimitry Andric if (!RangeEnd) 9440b57cec5SDimitry Andric RangeBegin = RangeEnd = &MI; 9450b57cec5SDimitry Andric else 9460b57cec5SDimitry Andric RangeBegin = &MI; 9470b57cec5SDimitry Andric } 9480b57cec5SDimitry Andric 9490b57cec5SDimitry Andric if (RangeEnd) { 9500b57cec5SDimitry Andric NeedAppendixBlock = true; 9510b57cec5SDimitry Andric // Record the range. nullptr here means the unwind destination is the 9520b57cec5SDimitry Andric // caller. 9530b57cec5SDimitry Andric UnwindDestToTryRanges[nullptr].push_back(TryRange(RangeBegin, RangeEnd)); 9540b57cec5SDimitry Andric RangeBegin = RangeEnd = nullptr; // Reset range pointers 9550b57cec5SDimitry Andric } 9560b57cec5SDimitry Andric } 9570b57cec5SDimitry Andric 9580b57cec5SDimitry Andric assert(EHPadStack.empty()); 9590b57cec5SDimitry Andric // We don't have any unwind destination mismatches to resolve. 9600b57cec5SDimitry Andric if (UnwindDestToTryRanges.empty()) 9610b57cec5SDimitry Andric return false; 9620b57cec5SDimitry Andric 9630b57cec5SDimitry Andric // If we found instructions that should unwind to the caller but currently 9640b57cec5SDimitry Andric // have incorrect unwind destination, we create an appendix block at the end 9650b57cec5SDimitry Andric // of the function with a local.get and a rethrow instruction. 9660b57cec5SDimitry Andric if (NeedAppendixBlock) { 9670b57cec5SDimitry Andric auto *AppendixBB = getAppendixBlock(MF); 968*8bcb0991SDimitry Andric Register ExnReg = MRI.createVirtualRegister(&WebAssembly::EXNREFRegClass); 9690b57cec5SDimitry Andric BuildMI(AppendixBB, DebugLoc(), TII.get(WebAssembly::RETHROW)) 9700b57cec5SDimitry Andric .addReg(ExnReg); 9710b57cec5SDimitry Andric // These instruction ranges should branch to this appendix BB. 9720b57cec5SDimitry Andric for (auto Range : UnwindDestToTryRanges[nullptr]) 9730b57cec5SDimitry Andric BrDestToTryRanges[AppendixBB].push_back(Range); 9740b57cec5SDimitry Andric BrDestToExnReg[AppendixBB] = ExnReg; 9750b57cec5SDimitry Andric } 9760b57cec5SDimitry Andric 9770b57cec5SDimitry Andric // We loop through unwind destination EH pads that are targeted from some 9780b57cec5SDimitry Andric // inner scopes. Because these EH pads are destination of more than one scope 9790b57cec5SDimitry Andric // now, we split them so that the handler body is after 'end_try'. 9800b57cec5SDimitry Andric // - Before 9810b57cec5SDimitry Andric // ehpad: 9820b57cec5SDimitry Andric // catch 9830b57cec5SDimitry Andric // local.set n / drop 9840b57cec5SDimitry Andric // handler body 9850b57cec5SDimitry Andric // ... 9860b57cec5SDimitry Andric // cont: 9870b57cec5SDimitry Andric // end_try 9880b57cec5SDimitry Andric // 9890b57cec5SDimitry Andric // - After 9900b57cec5SDimitry Andric // ehpad: 9910b57cec5SDimitry Andric // catch 9920b57cec5SDimitry Andric // local.set n / drop 9930b57cec5SDimitry Andric // brdest: (new) 9940b57cec5SDimitry Andric // end_try (hoisted from 'cont' BB) 9950b57cec5SDimitry Andric // handler body (taken from 'ehpad') 9960b57cec5SDimitry Andric // ... 9970b57cec5SDimitry Andric // cont: 9980b57cec5SDimitry Andric for (auto &P : UnwindDestToTryRanges) { 999*8bcb0991SDimitry Andric NumUnwindMismatches += P.second.size(); 10000b57cec5SDimitry Andric 10010b57cec5SDimitry Andric // This means the destination is the appendix BB, which was separately 10020b57cec5SDimitry Andric // handled above. 10030b57cec5SDimitry Andric if (!P.first) 10040b57cec5SDimitry Andric continue; 10050b57cec5SDimitry Andric 10060b57cec5SDimitry Andric MachineBasicBlock *EHPad = P.first; 10070b57cec5SDimitry Andric 10080b57cec5SDimitry Andric // Find 'catch' and 'local.set' or 'drop' instruction that follows the 10090b57cec5SDimitry Andric // 'catch'. If -wasm-disable-explicit-locals is not set, 'catch' should be 10100b57cec5SDimitry Andric // always followed by either 'local.set' or a 'drop', because 'br_on_exn' is 10110b57cec5SDimitry Andric // generated after 'catch' in LateEHPrepare and we don't support blocks 10120b57cec5SDimitry Andric // taking values yet. 10130b57cec5SDimitry Andric MachineInstr *Catch = nullptr; 10140b57cec5SDimitry Andric unsigned ExnReg = 0; 10150b57cec5SDimitry Andric for (auto &MI : *EHPad) { 10160b57cec5SDimitry Andric switch (MI.getOpcode()) { 10170b57cec5SDimitry Andric case WebAssembly::CATCH: 10180b57cec5SDimitry Andric Catch = &MI; 10190b57cec5SDimitry Andric ExnReg = Catch->getOperand(0).getReg(); 10200b57cec5SDimitry Andric break; 10210b57cec5SDimitry Andric } 10220b57cec5SDimitry Andric } 10230b57cec5SDimitry Andric assert(Catch && "EH pad does not have a catch"); 10240b57cec5SDimitry Andric assert(ExnReg != 0 && "Invalid register"); 10250b57cec5SDimitry Andric 10260b57cec5SDimitry Andric auto SplitPos = std::next(Catch->getIterator()); 10270b57cec5SDimitry Andric 10280b57cec5SDimitry Andric // Create a new BB that's gonna be the destination for branches from the 10290b57cec5SDimitry Andric // inner mismatched scope. 10300b57cec5SDimitry Andric MachineInstr *BeginTry = EHPadToTry[EHPad]; 10310b57cec5SDimitry Andric MachineInstr *EndTry = BeginToEnd[BeginTry]; 10320b57cec5SDimitry Andric MachineBasicBlock *Cont = EndTry->getParent(); 10330b57cec5SDimitry Andric auto *BrDest = MF.CreateMachineBasicBlock(); 10340b57cec5SDimitry Andric MF.insert(std::next(EHPad->getIterator()), BrDest); 10350b57cec5SDimitry Andric // Hoist up the existing 'end_try'. 10360b57cec5SDimitry Andric BrDest->insert(BrDest->end(), EndTry->removeFromParent()); 10370b57cec5SDimitry Andric // Take out the handler body from EH pad to the new branch destination BB. 10380b57cec5SDimitry Andric BrDest->splice(BrDest->end(), EHPad, SplitPos, EHPad->end()); 1039*8bcb0991SDimitry Andric unstackifyVRegsUsedInSplitBB(*EHPad, *BrDest, MFI, MRI); 10400b57cec5SDimitry Andric // Fix predecessor-successor relationship. 10410b57cec5SDimitry Andric BrDest->transferSuccessors(EHPad); 10420b57cec5SDimitry Andric EHPad->addSuccessor(BrDest); 10430b57cec5SDimitry Andric 10440b57cec5SDimitry Andric // All try ranges that were supposed to unwind to this EH pad now have to 10450b57cec5SDimitry Andric // branch to this new branch dest BB. 10460b57cec5SDimitry Andric for (auto Range : UnwindDestToTryRanges[EHPad]) 10470b57cec5SDimitry Andric BrDestToTryRanges[BrDest].push_back(Range); 10480b57cec5SDimitry Andric BrDestToExnReg[BrDest] = ExnReg; 10490b57cec5SDimitry Andric 10500b57cec5SDimitry Andric // In case we fall through to the continuation BB after the catch block, we 10510b57cec5SDimitry Andric // now have to add a branch to it. 10520b57cec5SDimitry Andric // - Before 10530b57cec5SDimitry Andric // try 10540b57cec5SDimitry Andric // ... 10550b57cec5SDimitry Andric // (falls through to 'cont') 10560b57cec5SDimitry Andric // catch 10570b57cec5SDimitry Andric // handler body 10580b57cec5SDimitry Andric // end 10590b57cec5SDimitry Andric // <-- cont 10600b57cec5SDimitry Andric // 10610b57cec5SDimitry Andric // - After 10620b57cec5SDimitry Andric // try 10630b57cec5SDimitry Andric // ... 10640b57cec5SDimitry Andric // br %cont (new) 10650b57cec5SDimitry Andric // catch 10660b57cec5SDimitry Andric // end 10670b57cec5SDimitry Andric // handler body 10680b57cec5SDimitry Andric // <-- cont 10690b57cec5SDimitry Andric MachineBasicBlock *EHPadLayoutPred = &*std::prev(EHPad->getIterator()); 10700b57cec5SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 10710b57cec5SDimitry Andric SmallVector<MachineOperand, 4> Cond; 10720b57cec5SDimitry Andric bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond); 10730b57cec5SDimitry Andric if (Analyzable && !TBB && !FBB) { 10740b57cec5SDimitry Andric DebugLoc DL = EHPadLayoutPred->empty() 10750b57cec5SDimitry Andric ? DebugLoc() 10760b57cec5SDimitry Andric : EHPadLayoutPred->rbegin()->getDebugLoc(); 10770b57cec5SDimitry Andric BuildMI(EHPadLayoutPred, DL, TII.get(WebAssembly::BR)).addMBB(Cont); 10780b57cec5SDimitry Andric } 10790b57cec5SDimitry Andric } 10800b57cec5SDimitry Andric 10810b57cec5SDimitry Andric // For possibly throwing calls whose unwind destinations are currently 10820b57cec5SDimitry Andric // incorrect because of CFG linearization, we wrap them with a nested 10830b57cec5SDimitry Andric // try/catch/end_try, and within the new catch block, we branch to the correct 10840b57cec5SDimitry Andric // handler. 10850b57cec5SDimitry Andric // - Before 10860b57cec5SDimitry Andric // mbb: 10870b57cec5SDimitry Andric // call @foo <- Unwind destination mismatch! 10880b57cec5SDimitry Andric // ehpad: 10890b57cec5SDimitry Andric // ... 10900b57cec5SDimitry Andric // 10910b57cec5SDimitry Andric // - After 10920b57cec5SDimitry Andric // mbb: 10930b57cec5SDimitry Andric // try (new) 10940b57cec5SDimitry Andric // call @foo 10950b57cec5SDimitry Andric // nested-ehpad: (new) 10960b57cec5SDimitry Andric // catch (new) 10970b57cec5SDimitry Andric // local.set n / drop (new) 10980b57cec5SDimitry Andric // br %brdest (new) 10990b57cec5SDimitry Andric // nested-end: (new) 11000b57cec5SDimitry Andric // end_try (new) 11010b57cec5SDimitry Andric // ehpad: 11020b57cec5SDimitry Andric // ... 11030b57cec5SDimitry Andric for (auto &P : BrDestToTryRanges) { 11040b57cec5SDimitry Andric MachineBasicBlock *BrDest = P.first; 11050b57cec5SDimitry Andric auto &TryRanges = P.second; 11060b57cec5SDimitry Andric unsigned ExnReg = BrDestToExnReg[BrDest]; 11070b57cec5SDimitry Andric 11080b57cec5SDimitry Andric for (auto Range : TryRanges) { 11090b57cec5SDimitry Andric MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; 11100b57cec5SDimitry Andric std::tie(RangeBegin, RangeEnd) = Range; 11110b57cec5SDimitry Andric auto *MBB = RangeBegin->getParent(); 11120b57cec5SDimitry Andric 11130b57cec5SDimitry Andric // Include possible EH_LABELs in the range 11140b57cec5SDimitry Andric if (RangeBegin->getIterator() != MBB->begin() && 11150b57cec5SDimitry Andric std::prev(RangeBegin->getIterator())->isEHLabel()) 11160b57cec5SDimitry Andric RangeBegin = &*std::prev(RangeBegin->getIterator()); 11170b57cec5SDimitry Andric if (std::next(RangeEnd->getIterator()) != MBB->end() && 11180b57cec5SDimitry Andric std::next(RangeEnd->getIterator())->isEHLabel()) 11190b57cec5SDimitry Andric RangeEnd = &*std::next(RangeEnd->getIterator()); 11200b57cec5SDimitry Andric 11210b57cec5SDimitry Andric MachineBasicBlock *EHPad = nullptr; 11220b57cec5SDimitry Andric for (auto *Succ : MBB->successors()) { 11230b57cec5SDimitry Andric if (Succ->isEHPad()) { 11240b57cec5SDimitry Andric EHPad = Succ; 11250b57cec5SDimitry Andric break; 11260b57cec5SDimitry Andric } 11270b57cec5SDimitry Andric } 11280b57cec5SDimitry Andric 11290b57cec5SDimitry Andric // Create the nested try instruction. 11300b57cec5SDimitry Andric MachineInstr *NestedTry = 11310b57cec5SDimitry Andric BuildMI(*MBB, *RangeBegin, RangeBegin->getDebugLoc(), 11320b57cec5SDimitry Andric TII.get(WebAssembly::TRY)) 1133*8bcb0991SDimitry Andric .addImm(int64_t(WebAssembly::BlockType::Void)); 11340b57cec5SDimitry Andric 11350b57cec5SDimitry Andric // Create the nested EH pad and fill instructions in. 11360b57cec5SDimitry Andric MachineBasicBlock *NestedEHPad = MF.CreateMachineBasicBlock(); 11370b57cec5SDimitry Andric MF.insert(std::next(MBB->getIterator()), NestedEHPad); 11380b57cec5SDimitry Andric NestedEHPad->setIsEHPad(); 11390b57cec5SDimitry Andric NestedEHPad->setIsEHScopeEntry(); 11400b57cec5SDimitry Andric BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::CATCH), 11410b57cec5SDimitry Andric ExnReg); 11420b57cec5SDimitry Andric BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::BR)) 11430b57cec5SDimitry Andric .addMBB(BrDest); 11440b57cec5SDimitry Andric 11450b57cec5SDimitry Andric // Create the nested continuation BB and end_try instruction. 11460b57cec5SDimitry Andric MachineBasicBlock *NestedCont = MF.CreateMachineBasicBlock(); 11470b57cec5SDimitry Andric MF.insert(std::next(NestedEHPad->getIterator()), NestedCont); 11480b57cec5SDimitry Andric MachineInstr *NestedEndTry = 11490b57cec5SDimitry Andric BuildMI(*NestedCont, NestedCont->begin(), RangeEnd->getDebugLoc(), 11500b57cec5SDimitry Andric TII.get(WebAssembly::END_TRY)); 11510b57cec5SDimitry Andric // In case MBB has more instructions after the try range, move them to the 11520b57cec5SDimitry Andric // new nested continuation BB. 11530b57cec5SDimitry Andric NestedCont->splice(NestedCont->end(), MBB, 11540b57cec5SDimitry Andric std::next(RangeEnd->getIterator()), MBB->end()); 1155*8bcb0991SDimitry Andric unstackifyVRegsUsedInSplitBB(*MBB, *NestedCont, MFI, MRI); 11560b57cec5SDimitry Andric registerTryScope(NestedTry, NestedEndTry, NestedEHPad); 11570b57cec5SDimitry Andric 11580b57cec5SDimitry Andric // Fix predecessor-successor relationship. 11590b57cec5SDimitry Andric NestedCont->transferSuccessors(MBB); 11600b57cec5SDimitry Andric if (EHPad) 11610b57cec5SDimitry Andric NestedCont->removeSuccessor(EHPad); 11620b57cec5SDimitry Andric MBB->addSuccessor(NestedEHPad); 11630b57cec5SDimitry Andric MBB->addSuccessor(NestedCont); 11640b57cec5SDimitry Andric NestedEHPad->addSuccessor(BrDest); 11650b57cec5SDimitry Andric } 11660b57cec5SDimitry Andric } 11670b57cec5SDimitry Andric 11680b57cec5SDimitry Andric // Renumber BBs and recalculate ScopeTop info because new BBs might have been 11690b57cec5SDimitry Andric // created and inserted above. 11700b57cec5SDimitry Andric MF.RenumberBlocks(); 11710b57cec5SDimitry Andric ScopeTops.clear(); 11720b57cec5SDimitry Andric ScopeTops.resize(MF.getNumBlockIDs()); 11730b57cec5SDimitry Andric for (auto &MBB : reverse(MF)) { 11740b57cec5SDimitry Andric for (auto &MI : reverse(MBB)) { 11750b57cec5SDimitry Andric if (ScopeTops[MBB.getNumber()]) 11760b57cec5SDimitry Andric break; 11770b57cec5SDimitry Andric switch (MI.getOpcode()) { 11780b57cec5SDimitry Andric case WebAssembly::END_BLOCK: 11790b57cec5SDimitry Andric case WebAssembly::END_LOOP: 11800b57cec5SDimitry Andric case WebAssembly::END_TRY: 11810b57cec5SDimitry Andric ScopeTops[MBB.getNumber()] = EndToBegin[&MI]->getParent(); 11820b57cec5SDimitry Andric break; 11830b57cec5SDimitry Andric case WebAssembly::CATCH: 11840b57cec5SDimitry Andric ScopeTops[MBB.getNumber()] = EHPadToTry[&MBB]->getParent(); 11850b57cec5SDimitry Andric break; 11860b57cec5SDimitry Andric } 11870b57cec5SDimitry Andric } 11880b57cec5SDimitry Andric } 11890b57cec5SDimitry Andric 11900b57cec5SDimitry Andric // Recompute the dominator tree. 11910b57cec5SDimitry Andric getAnalysis<MachineDominatorTree>().runOnMachineFunction(MF); 11920b57cec5SDimitry Andric 11930b57cec5SDimitry Andric // Place block markers for newly added branches. 11940b57cec5SDimitry Andric SmallVector <MachineBasicBlock *, 8> BrDests; 11950b57cec5SDimitry Andric for (auto &P : BrDestToTryRanges) 11960b57cec5SDimitry Andric BrDests.push_back(P.first); 11970b57cec5SDimitry Andric llvm::sort(BrDests, 11980b57cec5SDimitry Andric [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { 11990b57cec5SDimitry Andric auto ANum = A->getNumber(); 12000b57cec5SDimitry Andric auto BNum = B->getNumber(); 12010b57cec5SDimitry Andric return ANum < BNum; 12020b57cec5SDimitry Andric }); 12030b57cec5SDimitry Andric for (auto *Dest : BrDests) 12040b57cec5SDimitry Andric placeBlockMarker(*Dest); 12050b57cec5SDimitry Andric 12060b57cec5SDimitry Andric return true; 12070b57cec5SDimitry Andric } 12080b57cec5SDimitry Andric 12090b57cec5SDimitry Andric static unsigned 12100b57cec5SDimitry Andric getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 12110b57cec5SDimitry Andric const MachineBasicBlock *MBB) { 12120b57cec5SDimitry Andric unsigned Depth = 0; 12130b57cec5SDimitry Andric for (auto X : reverse(Stack)) { 12140b57cec5SDimitry Andric if (X == MBB) 12150b57cec5SDimitry Andric break; 12160b57cec5SDimitry Andric ++Depth; 12170b57cec5SDimitry Andric } 12180b57cec5SDimitry Andric assert(Depth < Stack.size() && "Branch destination should be in scope"); 12190b57cec5SDimitry Andric return Depth; 12200b57cec5SDimitry Andric } 12210b57cec5SDimitry Andric 12220b57cec5SDimitry Andric /// In normal assembly languages, when the end of a function is unreachable, 12230b57cec5SDimitry Andric /// because the function ends in an infinite loop or a noreturn call or similar, 12240b57cec5SDimitry Andric /// it isn't necessary to worry about the function return type at the end of 12250b57cec5SDimitry Andric /// the function, because it's never reached. However, in WebAssembly, blocks 12260b57cec5SDimitry Andric /// that end at the function end need to have a return type signature that 12270b57cec5SDimitry Andric /// matches the function signature, even though it's unreachable. This function 12280b57cec5SDimitry Andric /// checks for such cases and fixes up the signatures. 12290b57cec5SDimitry Andric void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) { 12300b57cec5SDimitry Andric const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 12310b57cec5SDimitry Andric 12320b57cec5SDimitry Andric if (MFI.getResults().empty()) 12330b57cec5SDimitry Andric return; 12340b57cec5SDimitry Andric 1235*8bcb0991SDimitry Andric // MCInstLower will add the proper types to multivalue signatures based on the 1236*8bcb0991SDimitry Andric // function return type 1237*8bcb0991SDimitry Andric WebAssembly::BlockType RetType = 1238*8bcb0991SDimitry Andric MFI.getResults().size() > 1 1239*8bcb0991SDimitry Andric ? WebAssembly::BlockType::Multivalue 1240*8bcb0991SDimitry Andric : WebAssembly::BlockType( 1241*8bcb0991SDimitry Andric WebAssembly::toValType(MFI.getResults().front())); 12420b57cec5SDimitry Andric 12430b57cec5SDimitry Andric for (MachineBasicBlock &MBB : reverse(MF)) { 12440b57cec5SDimitry Andric for (MachineInstr &MI : reverse(MBB)) { 12450b57cec5SDimitry Andric if (MI.isPosition() || MI.isDebugInstr()) 12460b57cec5SDimitry Andric continue; 1247*8bcb0991SDimitry Andric switch (MI.getOpcode()) { 1248*8bcb0991SDimitry Andric case WebAssembly::END_BLOCK: 1249*8bcb0991SDimitry Andric case WebAssembly::END_LOOP: 1250*8bcb0991SDimitry Andric case WebAssembly::END_TRY: 12510b57cec5SDimitry Andric EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType)); 12520b57cec5SDimitry Andric continue; 1253*8bcb0991SDimitry Andric default: 12540b57cec5SDimitry Andric // Something other than an `end`. We're done. 12550b57cec5SDimitry Andric return; 12560b57cec5SDimitry Andric } 12570b57cec5SDimitry Andric } 12580b57cec5SDimitry Andric } 1259*8bcb0991SDimitry Andric } 12600b57cec5SDimitry Andric 12610b57cec5SDimitry Andric // WebAssembly functions end with an end instruction, as if the function body 12620b57cec5SDimitry Andric // were a block. 12630b57cec5SDimitry Andric static void appendEndToFunction(MachineFunction &MF, 12640b57cec5SDimitry Andric const WebAssemblyInstrInfo &TII) { 12650b57cec5SDimitry Andric BuildMI(MF.back(), MF.back().end(), 12660b57cec5SDimitry Andric MF.back().findPrevDebugLoc(MF.back().end()), 12670b57cec5SDimitry Andric TII.get(WebAssembly::END_FUNCTION)); 12680b57cec5SDimitry Andric } 12690b57cec5SDimitry Andric 12700b57cec5SDimitry Andric /// Insert LOOP/TRY/BLOCK markers at appropriate places. 12710b57cec5SDimitry Andric void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) { 12720b57cec5SDimitry Andric // We allocate one more than the number of blocks in the function to 12730b57cec5SDimitry Andric // accommodate for the possible fake block we may insert at the end. 12740b57cec5SDimitry Andric ScopeTops.resize(MF.getNumBlockIDs() + 1); 12750b57cec5SDimitry Andric // Place the LOOP for MBB if MBB is the header of a loop. 12760b57cec5SDimitry Andric for (auto &MBB : MF) 12770b57cec5SDimitry Andric placeLoopMarker(MBB); 12780b57cec5SDimitry Andric 12790b57cec5SDimitry Andric const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 12800b57cec5SDimitry Andric for (auto &MBB : MF) { 12810b57cec5SDimitry Andric if (MBB.isEHPad()) { 12820b57cec5SDimitry Andric // Place the TRY for MBB if MBB is the EH pad of an exception. 12830b57cec5SDimitry Andric if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 12840b57cec5SDimitry Andric MF.getFunction().hasPersonalityFn()) 12850b57cec5SDimitry Andric placeTryMarker(MBB); 12860b57cec5SDimitry Andric } else { 12870b57cec5SDimitry Andric // Place the BLOCK for MBB if MBB is branched to from above. 12880b57cec5SDimitry Andric placeBlockMarker(MBB); 12890b57cec5SDimitry Andric } 12900b57cec5SDimitry Andric } 12910b57cec5SDimitry Andric // Fix mismatches in unwind destinations induced by linearizing the code. 1292*8bcb0991SDimitry Andric if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1293*8bcb0991SDimitry Andric MF.getFunction().hasPersonalityFn()) 12940b57cec5SDimitry Andric fixUnwindMismatches(MF); 12950b57cec5SDimitry Andric } 12960b57cec5SDimitry Andric 12970b57cec5SDimitry Andric void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) { 12980b57cec5SDimitry Andric // Now rewrite references to basic blocks to be depth immediates. 12990b57cec5SDimitry Andric SmallVector<const MachineBasicBlock *, 8> Stack; 13000b57cec5SDimitry Andric for (auto &MBB : reverse(MF)) { 13010b57cec5SDimitry Andric for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) { 13020b57cec5SDimitry Andric MachineInstr &MI = *I; 13030b57cec5SDimitry Andric switch (MI.getOpcode()) { 13040b57cec5SDimitry Andric case WebAssembly::BLOCK: 13050b57cec5SDimitry Andric case WebAssembly::TRY: 13060b57cec5SDimitry Andric assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= 13070b57cec5SDimitry Andric MBB.getNumber() && 13080b57cec5SDimitry Andric "Block/try marker should be balanced"); 13090b57cec5SDimitry Andric Stack.pop_back(); 13100b57cec5SDimitry Andric break; 13110b57cec5SDimitry Andric 13120b57cec5SDimitry Andric case WebAssembly::LOOP: 13130b57cec5SDimitry Andric assert(Stack.back() == &MBB && "Loop top should be balanced"); 13140b57cec5SDimitry Andric Stack.pop_back(); 13150b57cec5SDimitry Andric break; 13160b57cec5SDimitry Andric 13170b57cec5SDimitry Andric case WebAssembly::END_BLOCK: 13180b57cec5SDimitry Andric case WebAssembly::END_TRY: 13190b57cec5SDimitry Andric Stack.push_back(&MBB); 13200b57cec5SDimitry Andric break; 13210b57cec5SDimitry Andric 13220b57cec5SDimitry Andric case WebAssembly::END_LOOP: 13230b57cec5SDimitry Andric Stack.push_back(EndToBegin[&MI]->getParent()); 13240b57cec5SDimitry Andric break; 13250b57cec5SDimitry Andric 13260b57cec5SDimitry Andric default: 13270b57cec5SDimitry Andric if (MI.isTerminator()) { 13280b57cec5SDimitry Andric // Rewrite MBB operands to be depth immediates. 13290b57cec5SDimitry Andric SmallVector<MachineOperand, 4> Ops(MI.operands()); 13300b57cec5SDimitry Andric while (MI.getNumOperands() > 0) 13310b57cec5SDimitry Andric MI.RemoveOperand(MI.getNumOperands() - 1); 13320b57cec5SDimitry Andric for (auto MO : Ops) { 13330b57cec5SDimitry Andric if (MO.isMBB()) 13340b57cec5SDimitry Andric MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB())); 13350b57cec5SDimitry Andric MI.addOperand(MF, MO); 13360b57cec5SDimitry Andric } 13370b57cec5SDimitry Andric } 13380b57cec5SDimitry Andric break; 13390b57cec5SDimitry Andric } 13400b57cec5SDimitry Andric } 13410b57cec5SDimitry Andric } 13420b57cec5SDimitry Andric assert(Stack.empty() && "Control flow should be balanced"); 13430b57cec5SDimitry Andric } 13440b57cec5SDimitry Andric 13450b57cec5SDimitry Andric void WebAssemblyCFGStackify::releaseMemory() { 13460b57cec5SDimitry Andric ScopeTops.clear(); 13470b57cec5SDimitry Andric BeginToEnd.clear(); 13480b57cec5SDimitry Andric EndToBegin.clear(); 13490b57cec5SDimitry Andric TryToEHPad.clear(); 13500b57cec5SDimitry Andric EHPadToTry.clear(); 13510b57cec5SDimitry Andric AppendixBB = nullptr; 13520b57cec5SDimitry Andric } 13530b57cec5SDimitry Andric 13540b57cec5SDimitry Andric bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 13550b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n" 13560b57cec5SDimitry Andric "********** Function: " 13570b57cec5SDimitry Andric << MF.getName() << '\n'); 13580b57cec5SDimitry Andric const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 13590b57cec5SDimitry Andric 13600b57cec5SDimitry Andric releaseMemory(); 13610b57cec5SDimitry Andric 13620b57cec5SDimitry Andric // Liveness is not tracked for VALUE_STACK physreg. 13630b57cec5SDimitry Andric MF.getRegInfo().invalidateLiveness(); 13640b57cec5SDimitry Andric 13650b57cec5SDimitry Andric // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes. 13660b57cec5SDimitry Andric placeMarkers(MF); 13670b57cec5SDimitry Andric 13680b57cec5SDimitry Andric // Remove unnecessary instructions possibly introduced by try/end_trys. 13690b57cec5SDimitry Andric if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 13700b57cec5SDimitry Andric MF.getFunction().hasPersonalityFn()) 13710b57cec5SDimitry Andric removeUnnecessaryInstrs(MF); 13720b57cec5SDimitry Andric 13730b57cec5SDimitry Andric // Convert MBB operands in terminators to relative depth immediates. 13740b57cec5SDimitry Andric rewriteDepthImmediates(MF); 13750b57cec5SDimitry Andric 13760b57cec5SDimitry Andric // Fix up block/loop/try signatures at the end of the function to conform to 13770b57cec5SDimitry Andric // WebAssembly's rules. 13780b57cec5SDimitry Andric fixEndsAtEndOfFunction(MF); 13790b57cec5SDimitry Andric 13800b57cec5SDimitry Andric // Add an end instruction at the end of the function body. 13810b57cec5SDimitry Andric const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 13820b57cec5SDimitry Andric if (!MF.getSubtarget<WebAssemblySubtarget>() 13830b57cec5SDimitry Andric .getTargetTriple() 13840b57cec5SDimitry Andric .isOSBinFormatELF()) 13850b57cec5SDimitry Andric appendEndToFunction(MF, TII); 13860b57cec5SDimitry Andric 13870b57cec5SDimitry Andric MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified(); 13880b57cec5SDimitry Andric return true; 13890b57cec5SDimitry Andric } 1390