1950a13cfSDan Gohman //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===// 2950a13cfSDan Gohman // 3950a13cfSDan Gohman // The LLVM Compiler Infrastructure 4950a13cfSDan Gohman // 5950a13cfSDan Gohman // This file is distributed under the University of Illinois Open Source 6950a13cfSDan Gohman // License. See LICENSE.TXT for details. 7950a13cfSDan Gohman // 8950a13cfSDan Gohman //===----------------------------------------------------------------------===// 9950a13cfSDan Gohman /// 10950a13cfSDan Gohman /// \file 115f8f34e4SAdrian Prantl /// This file implements a CFG stacking pass. 12950a13cfSDan Gohman /// 13*e76fa9ecSHeejin Ahn /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes, 14*e76fa9ecSHeejin Ahn /// since scope boundaries serve as the labels for WebAssembly's control 15*e76fa9ecSHeejin Ahn /// transfers. 16950a13cfSDan Gohman /// 17950a13cfSDan Gohman /// This is sufficient to convert arbitrary CFGs into a form that works on 18950a13cfSDan Gohman /// WebAssembly, provided that all loops are single-entry. 19950a13cfSDan Gohman /// 20*e76fa9ecSHeejin Ahn /// In case we use exceptions, this pass also fixes mismatches in unwind 21*e76fa9ecSHeejin Ahn /// destinations created during transforming CFG into wasm structured format. 22*e76fa9ecSHeejin Ahn /// 23950a13cfSDan Gohman //===----------------------------------------------------------------------===// 24950a13cfSDan Gohman 25950a13cfSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 266bda14b3SChandler Carruth #include "WebAssembly.h" 27*e76fa9ecSHeejin Ahn #include "WebAssemblyExceptionInfo.h" 28ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h" 29950a13cfSDan Gohman #include "WebAssemblySubtarget.h" 304fc4e42dSDan Gohman #include "WebAssemblyUtilities.h" 3132807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h" 32950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h" 33950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h" 34950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h" 359c3bf318SDerek Schuff #include "llvm/CodeGen/MachineRegisterInfo.h" 36950a13cfSDan Gohman #include "llvm/CodeGen/Passes.h" 37*e76fa9ecSHeejin Ahn #include "llvm/CodeGen/WasmEHFuncInfo.h" 38*e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h" 39950a13cfSDan Gohman #include "llvm/Support/Debug.h" 40950a13cfSDan Gohman #include "llvm/Support/raw_ostream.h" 41950a13cfSDan Gohman using namespace llvm; 42950a13cfSDan Gohman 43950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify" 44950a13cfSDan Gohman 45950a13cfSDan Gohman namespace { 46950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass { 47117296c0SMehdi Amini StringRef getPassName() const override { return "WebAssembly CFG Stackify"; } 48950a13cfSDan Gohman 49950a13cfSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override { 5032807932SDan Gohman AU.addRequired<MachineDominatorTree>(); 51950a13cfSDan Gohman AU.addRequired<MachineLoopInfo>(); 52*e76fa9ecSHeejin Ahn AU.addRequired<WebAssemblyExceptionInfo>(); 53950a13cfSDan Gohman MachineFunctionPass::getAnalysisUsage(AU); 54950a13cfSDan Gohman } 55950a13cfSDan Gohman 56950a13cfSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override; 57950a13cfSDan Gohman 58*e76fa9ecSHeejin Ahn // For each block whose label represents the end of a scope, record the block 59*e76fa9ecSHeejin Ahn // which holds the beginning of the scope. This will allow us to quickly skip 60*e76fa9ecSHeejin Ahn // over scoped regions when walking blocks. 61*e76fa9ecSHeejin Ahn SmallVector<MachineBasicBlock *, 8> ScopeTops; 62*e76fa9ecSHeejin Ahn 63*e76fa9ecSHeejin Ahn void placeMarkers(MachineFunction &MF); 64*e76fa9ecSHeejin Ahn void placeBlockMarker(MachineBasicBlock &MBB); 65*e76fa9ecSHeejin Ahn void placeLoopMarker(MachineBasicBlock &MBB); 66*e76fa9ecSHeejin Ahn void placeTryMarker(MachineBasicBlock &MBB); 67*e76fa9ecSHeejin Ahn void rewriteDepthImmediates(MachineFunction &MF); 68*e76fa9ecSHeejin Ahn void fixEndsAtEndOfFunction(MachineFunction &MF); 69*e76fa9ecSHeejin Ahn 70*e76fa9ecSHeejin Ahn // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY). 71*e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd; 72*e76fa9ecSHeejin Ahn // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY. 73*e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> EndToBegin; 74*e76fa9ecSHeejin Ahn // <TRY marker, EH pad> map 75*e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad; 76*e76fa9ecSHeejin Ahn // <EH pad, TRY marker> map 77*e76fa9ecSHeejin Ahn DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry; 78*e76fa9ecSHeejin Ahn // <LOOP|TRY marker, Loop/exception bottom BB> map 79*e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineBasicBlock *> BeginToBottom; 80*e76fa9ecSHeejin Ahn 81*e76fa9ecSHeejin Ahn // Helper functions to register / unregister scope information created by 82*e76fa9ecSHeejin Ahn // marker instructions. 83*e76fa9ecSHeejin Ahn void registerScope(MachineInstr *Begin, MachineInstr *End); 84*e76fa9ecSHeejin Ahn void registerTryScope(MachineInstr *Begin, MachineInstr *End, 85*e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad); 86*e76fa9ecSHeejin Ahn void unregisterScope(MachineInstr *Begin); 87*e76fa9ecSHeejin Ahn 88*e76fa9ecSHeejin Ahn MachineBasicBlock *getBottom(const MachineInstr *Begin); 89*e76fa9ecSHeejin Ahn 90950a13cfSDan Gohman public: 91950a13cfSDan Gohman static char ID; // Pass identification, replacement for typeid 92950a13cfSDan Gohman WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 93*e76fa9ecSHeejin Ahn ~WebAssemblyCFGStackify() override { releaseMemory(); } 94*e76fa9ecSHeejin Ahn void releaseMemory() override; 95950a13cfSDan Gohman }; 96950a13cfSDan Gohman } // end anonymous namespace 97950a13cfSDan Gohman 98950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0; 9940926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE, 10040926451SJacob Gravelle "Insert BLOCK and LOOP markers for WebAssembly scopes", 10140926451SJacob Gravelle false, false) 10240926451SJacob Gravelle 103950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() { 104950a13cfSDan Gohman return new WebAssemblyCFGStackify(); 105950a13cfSDan Gohman } 106950a13cfSDan Gohman 107b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as 108b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized 109b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough 110b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any 111b3aa1ecaSDan Gohman /// explicit mentions. 11235e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred, 11335e4a289SDan Gohman MachineBasicBlock *MBB) { 114b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators()) 115*e76fa9ecSHeejin Ahn // Even if a rethrow takes a BB argument, it is not a branch 116*e76fa9ecSHeejin Ahn if (!WebAssembly::isRethrow(MI)) 117b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands()) 118b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB) 119b3aa1ecaSDan Gohman return true; 120b3aa1ecaSDan Gohman return false; 121b3aa1ecaSDan Gohman } 122b3aa1ecaSDan Gohman 123*e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB, 124*e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 125*e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 126*e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only 127*e76fa9ecSHeejin Ahn // used for sanity checking. 128*e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 129*e76fa9ecSHeejin Ahn GetEarliestInsertPos(MachineBasicBlock *MBB, 130*e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 131*e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 132*e76fa9ecSHeejin Ahn auto InsertPos = MBB->end(); 133*e76fa9ecSHeejin Ahn while (InsertPos != MBB->begin()) { 134*e76fa9ecSHeejin Ahn if (BeforeSet.count(&*std::prev(InsertPos))) { 135*e76fa9ecSHeejin Ahn #ifndef NDEBUG 136*e76fa9ecSHeejin Ahn // Sanity check 137*e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos) 138*e76fa9ecSHeejin Ahn assert(!AfterSet.count(&*std::prev(Pos))); 139*e76fa9ecSHeejin Ahn #endif 140*e76fa9ecSHeejin Ahn break; 141*e76fa9ecSHeejin Ahn } 142*e76fa9ecSHeejin Ahn --InsertPos; 143*e76fa9ecSHeejin Ahn } 144*e76fa9ecSHeejin Ahn return InsertPos; 145*e76fa9ecSHeejin Ahn } 146*e76fa9ecSHeejin Ahn 147*e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB, 148*e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 149*e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 150*e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only 151*e76fa9ecSHeejin Ahn // used for sanity checking. 152*e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 153*e76fa9ecSHeejin Ahn GetLatestInsertPos(MachineBasicBlock *MBB, 154*e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 155*e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 156*e76fa9ecSHeejin Ahn auto InsertPos = MBB->begin(); 157*e76fa9ecSHeejin Ahn while (InsertPos != MBB->end()) { 158*e76fa9ecSHeejin Ahn if (AfterSet.count(&*InsertPos)) { 159*e76fa9ecSHeejin Ahn #ifndef NDEBUG 160*e76fa9ecSHeejin Ahn // Sanity check 161*e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos) 162*e76fa9ecSHeejin Ahn assert(!BeforeSet.count(&*Pos)); 163*e76fa9ecSHeejin Ahn #endif 164*e76fa9ecSHeejin Ahn break; 165*e76fa9ecSHeejin Ahn } 166*e76fa9ecSHeejin Ahn ++InsertPos; 167*e76fa9ecSHeejin Ahn } 168*e76fa9ecSHeejin Ahn return InsertPos; 169*e76fa9ecSHeejin Ahn } 170*e76fa9ecSHeejin Ahn 171*e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin, 172*e76fa9ecSHeejin Ahn MachineInstr *End) { 173*e76fa9ecSHeejin Ahn BeginToEnd[Begin] = End; 174*e76fa9ecSHeejin Ahn EndToBegin[End] = Begin; 175*e76fa9ecSHeejin Ahn } 176*e76fa9ecSHeejin Ahn 177*e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin, 178*e76fa9ecSHeejin Ahn MachineInstr *End, 179*e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad) { 180*e76fa9ecSHeejin Ahn registerScope(Begin, End); 181*e76fa9ecSHeejin Ahn TryToEHPad[Begin] = EHPad; 182*e76fa9ecSHeejin Ahn EHPadToTry[EHPad] = Begin; 183*e76fa9ecSHeejin Ahn } 184*e76fa9ecSHeejin Ahn 185*e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) { 186*e76fa9ecSHeejin Ahn assert(BeginToEnd.count(Begin)); 187*e76fa9ecSHeejin Ahn MachineInstr *End = BeginToEnd[Begin]; 188*e76fa9ecSHeejin Ahn assert(EndToBegin.count(End)); 189*e76fa9ecSHeejin Ahn BeginToEnd.erase(Begin); 190*e76fa9ecSHeejin Ahn EndToBegin.erase(End); 191*e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin); 192*e76fa9ecSHeejin Ahn if (EHPad) { 193*e76fa9ecSHeejin Ahn assert(EHPadToTry.count(EHPad)); 194*e76fa9ecSHeejin Ahn TryToEHPad.erase(Begin); 195*e76fa9ecSHeejin Ahn EHPadToTry.erase(EHPad); 196*e76fa9ecSHeejin Ahn } 197*e76fa9ecSHeejin Ahn MachineBasicBlock *Bottom = BeginToBottom.lookup(Begin); 198*e76fa9ecSHeejin Ahn if (Bottom) 199*e76fa9ecSHeejin Ahn BeginToBottom.erase(Begin); 200*e76fa9ecSHeejin Ahn } 201*e76fa9ecSHeejin Ahn 202*e76fa9ecSHeejin Ahn // Given a LOOP/TRY marker, returns its bottom BB. Use cached information if any 203*e76fa9ecSHeejin Ahn // to prevent recomputation. 204*e76fa9ecSHeejin Ahn MachineBasicBlock * 205*e76fa9ecSHeejin Ahn WebAssemblyCFGStackify::getBottom(const MachineInstr *Begin) { 206*e76fa9ecSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 207*e76fa9ecSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 208*e76fa9ecSHeejin Ahn if (BeginToBottom.count(Begin)) 209*e76fa9ecSHeejin Ahn return BeginToBottom[Begin]; 210*e76fa9ecSHeejin Ahn if (Begin->getOpcode() == WebAssembly::LOOP) { 211*e76fa9ecSHeejin Ahn MachineLoop *L = MLI.getLoopFor(Begin->getParent()); 212*e76fa9ecSHeejin Ahn assert(L); 213*e76fa9ecSHeejin Ahn BeginToBottom[Begin] = WebAssembly::getBottom(L); 214*e76fa9ecSHeejin Ahn } else if (Begin->getOpcode() == WebAssembly::TRY) { 215*e76fa9ecSHeejin Ahn WebAssemblyException *WE = WEI.getExceptionFor(TryToEHPad[Begin]); 216*e76fa9ecSHeejin Ahn assert(WE); 217*e76fa9ecSHeejin Ahn BeginToBottom[Begin] = WebAssembly::getBottom(WE); 218*e76fa9ecSHeejin Ahn } else 219*e76fa9ecSHeejin Ahn assert(false); 220*e76fa9ecSHeejin Ahn return BeginToBottom[Begin]; 221*e76fa9ecSHeejin Ahn } 222*e76fa9ecSHeejin Ahn 22332807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed). 224*e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) { 225*e76fa9ecSHeejin Ahn // This should have been handled in placeTryMarker. 226*e76fa9ecSHeejin Ahn if (MBB.isEHPad()) 227*e76fa9ecSHeejin Ahn return; 228*e76fa9ecSHeejin Ahn 229*e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 230*e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 231*e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 232*e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 233*e76fa9ecSHeejin Ahn 2348fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough 2358fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack, 2368fe7e86bSDan Gohman // which reduces overall stack height. 23732807932SDan Gohman MachineBasicBlock *Header = nullptr; 23832807932SDan Gohman bool IsBranchedTo = false; 23932807932SDan Gohman int MBBNumber = MBB.getNumber(); 240*e76fa9ecSHeejin Ahn for (MachineBasicBlock *Pred : MBB.predecessors()) { 24132807932SDan Gohman if (Pred->getNumber() < MBBNumber) { 24232807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 243b3aa1ecaSDan Gohman if (ExplicitlyBranchesTo(Pred, &MBB)) 24432807932SDan Gohman IsBranchedTo = true; 24532807932SDan Gohman } 246*e76fa9ecSHeejin Ahn } 24732807932SDan Gohman if (!Header) 24832807932SDan Gohman return; 24932807932SDan Gohman if (!IsBranchedTo) 25032807932SDan Gohman return; 25132807932SDan Gohman 2528fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 253ef0a45aaSBenjamin Kramer MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB)); 2548fe7e86bSDan Gohman 2558fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context, 2568fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested. 2578fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 2588fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 2598fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) { 2608fe7e86bSDan Gohman // Skip over an intervening scope. 261ef0a45aaSBenjamin Kramer I = std::next(MachineFunction::iterator(ScopeTop)); 2628fe7e86bSDan Gohman } else { 2638fe7e86bSDan Gohman // We found a scope level at an appropriate depth. 2648fe7e86bSDan Gohman Header = ScopeTop; 2658fe7e86bSDan Gohman break; 2668fe7e86bSDan Gohman } 2678fe7e86bSDan Gohman } 2688fe7e86bSDan Gohman } 2698fe7e86bSDan Gohman 2708fe7e86bSDan Gohman // Decide where in Header to put the BLOCK. 271*e76fa9ecSHeejin Ahn 272*e76fa9ecSHeejin Ahn // Instructions that should go before the BLOCK. 273*e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 274*e76fa9ecSHeejin Ahn // Instructions that should go after the BLOCK. 275*e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 276*e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 277*e76fa9ecSHeejin Ahn // If there is a previously placed LOOP/TRY marker and the bottom block of 278*e76fa9ecSHeejin Ahn // the loop/exception is above MBB, it should be after the BLOCK, because 279*e76fa9ecSHeejin Ahn // the loop/exception is nested in this block. Otherwise it should be before 280*e76fa9ecSHeejin Ahn // the BLOCK. 281*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 282*e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) { 283*e76fa9ecSHeejin Ahn if (MBB.getNumber() > getBottom(&MI)->getNumber()) 284*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 285*e76fa9ecSHeejin Ahn #ifndef NDEBUG 286*e76fa9ecSHeejin Ahn else 287*e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 288*e76fa9ecSHeejin Ahn #endif 289*e76fa9ecSHeejin Ahn } 290*e76fa9ecSHeejin Ahn 291*e76fa9ecSHeejin Ahn // All previously inserted BLOCK markers should be after the BLOCK because 292*e76fa9ecSHeejin Ahn // they are all nested blocks. 293*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK) 294*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 295*e76fa9ecSHeejin Ahn 296*e76fa9ecSHeejin Ahn #ifndef NDEBUG 297*e76fa9ecSHeejin Ahn // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK. 298*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK || 299*e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP || 300*e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 301*e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 302*e76fa9ecSHeejin Ahn #endif 303*e76fa9ecSHeejin Ahn 304*e76fa9ecSHeejin Ahn // Terminators should go after the BLOCK. 305*e76fa9ecSHeejin Ahn if (MI.isTerminator()) 306*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 307*e76fa9ecSHeejin Ahn } 308*e76fa9ecSHeejin Ahn 309*e76fa9ecSHeejin Ahn // Local expression tree should go after the BLOCK. 310*e76fa9ecSHeejin Ahn for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 311*e76fa9ecSHeejin Ahn --I) { 312*e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 313*e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 314*e76fa9ecSHeejin Ahn else 315*e76fa9ecSHeejin Ahn break; 31632807932SDan Gohman } 31732807932SDan Gohman 3188fe7e86bSDan Gohman // Add the BLOCK. 319*e76fa9ecSHeejin Ahn auto InsertPos = GetLatestInsertPos(Header, BeforeSet, AfterSet); 32092401cc1SHeejin Ahn MachineInstr *Begin = 32192401cc1SHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 3222726b88cSDan Gohman TII.get(WebAssembly::BLOCK)) 3234fc4e42dSDan Gohman .addImm(int64_t(WebAssembly::ExprType::Void)); 3241d68e80fSDan Gohman 325*e76fa9ecSHeejin Ahn // Decide where in Header to put the END_BLOCK. 326*e76fa9ecSHeejin Ahn BeforeSet.clear(); 327*e76fa9ecSHeejin Ahn AfterSet.clear(); 328*e76fa9ecSHeejin Ahn for (auto &MI : MBB) { 329*e76fa9ecSHeejin Ahn #ifndef NDEBUG 330*e76fa9ecSHeejin Ahn // END_BLOCK should precede existing LOOP and TRY markers. 331*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 332*e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) 333*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 334*e76fa9ecSHeejin Ahn #endif 335*e76fa9ecSHeejin Ahn 336*e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and the header of the 337*e76fa9ecSHeejin Ahn // loop is above this block's header, the END_LOOP should be placed after 338*e76fa9ecSHeejin Ahn // the BLOCK, because the loop contains this block. Otherwise the END_LOOP 339*e76fa9ecSHeejin Ahn // should be placed before the BLOCK. The same for END_TRY. 340*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP || 341*e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) { 342*e76fa9ecSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 343*e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 344*e76fa9ecSHeejin Ahn #ifndef NDEBUG 345*e76fa9ecSHeejin Ahn else 346*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 347*e76fa9ecSHeejin Ahn #endif 348*e76fa9ecSHeejin Ahn } 349*e76fa9ecSHeejin Ahn } 350*e76fa9ecSHeejin Ahn 3511d68e80fSDan Gohman // Mark the end of the block. 352*e76fa9ecSHeejin Ahn InsertPos = GetEarliestInsertPos(&MBB, BeforeSet, AfterSet); 35310b31358SDerek Schuff MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos), 3542726b88cSDan Gohman TII.get(WebAssembly::END_BLOCK)); 355*e76fa9ecSHeejin Ahn registerScope(Begin, End); 3568fe7e86bSDan Gohman 3578fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3588fe7e86bSDan Gohman int Number = MBB.getNumber(); 3598fe7e86bSDan Gohman if (!ScopeTops[Number] || 3608fe7e86bSDan Gohman ScopeTops[Number]->getNumber() > Header->getNumber()) 3618fe7e86bSDan Gohman ScopeTops[Number] = Header; 362950a13cfSDan Gohman } 363950a13cfSDan Gohman 3648fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 365*e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) { 366*e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 367*e76fa9ecSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 368*e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 369*e76fa9ecSHeejin Ahn 3708fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 3718fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 3728fe7e86bSDan Gohman return; 3738fe7e86bSDan Gohman 3748fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 3758fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 376817811caSHeejin Ahn MachineBasicBlock *Bottom = WebAssembly::getBottom(Loop); 377ef0a45aaSBenjamin Kramer auto Iter = std::next(MachineFunction::iterator(Bottom)); 378e3e4a5ffSDan Gohman if (Iter == MF.end()) { 379f6857223SDan Gohman MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 380f6857223SDan Gohman // Give it a fake predecessor so that AsmPrinter prints its label. 381f6857223SDan Gohman Label->addSuccessor(Label); 382f6857223SDan Gohman MF.push_back(Label); 383ef0a45aaSBenjamin Kramer Iter = std::next(MachineFunction::iterator(Bottom)); 384e3e4a5ffSDan Gohman } 3858fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 386f6857223SDan Gohman 387*e76fa9ecSHeejin Ahn // Decide where in Header to put the LOOP. 388*e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 389*e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 390*e76fa9ecSHeejin Ahn for (const auto &MI : MBB) { 391*e76fa9ecSHeejin Ahn // LOOP marker should be after any existing loop that ends here. Otherwise 392*e76fa9ecSHeejin Ahn // we assume the instruction belongs to the loop. 393*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 394*e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 395*e76fa9ecSHeejin Ahn #ifndef NDEBUG 396*e76fa9ecSHeejin Ahn else 397*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 398*e76fa9ecSHeejin Ahn #endif 399*e76fa9ecSHeejin Ahn } 400*e76fa9ecSHeejin Ahn 401*e76fa9ecSHeejin Ahn // Mark the beginning of the loop. 402*e76fa9ecSHeejin Ahn auto InsertPos = GetEarliestInsertPos(&MBB, BeforeSet, AfterSet); 40310b31358SDerek Schuff MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos), 4042726b88cSDan Gohman TII.get(WebAssembly::LOOP)) 4054fc4e42dSDan Gohman .addImm(int64_t(WebAssembly::ExprType::Void)); 4061d68e80fSDan Gohman 407*e76fa9ecSHeejin Ahn // Decide where in Header to put the END_LOOP. 408*e76fa9ecSHeejin Ahn BeforeSet.clear(); 409*e76fa9ecSHeejin Ahn AfterSet.clear(); 410*e76fa9ecSHeejin Ahn #ifndef NDEBUG 411*e76fa9ecSHeejin Ahn for (const auto &MI : MBB) 412*e76fa9ecSHeejin Ahn // Existing END_LOOP markers belong to parent loops of this loop 413*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 414*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 415*e76fa9ecSHeejin Ahn #endif 416*e76fa9ecSHeejin Ahn 417*e76fa9ecSHeejin Ahn // Mark the end of the loop (using arbitrary debug location that branched to 418*e76fa9ecSHeejin Ahn // the loop end as its location). 419*e76fa9ecSHeejin Ahn InsertPos = GetEarliestInsertPos(AfterLoop, BeforeSet, AfterSet); 42010b31358SDerek Schuff DebugLoc EndDL = (*AfterLoop->pred_rbegin())->findBranchDebugLoc(); 421*e76fa9ecSHeejin Ahn MachineInstr *End = 422*e76fa9ecSHeejin Ahn BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP)); 423*e76fa9ecSHeejin Ahn registerScope(Begin, End); 4248fe7e86bSDan Gohman 4258fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 4268fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 427442bfcecSDan Gohman "With block sorting the outermost loop for a block should be first."); 4288fe7e86bSDan Gohman if (!ScopeTops[AfterLoop->getNumber()]) 4298fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()] = &MBB; 430e3e4a5ffSDan Gohman } 431950a13cfSDan Gohman 432*e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) { 433*e76fa9ecSHeejin Ahn if (!MBB.isEHPad()) 434*e76fa9ecSHeejin Ahn return; 435*e76fa9ecSHeejin Ahn 436*e76fa9ecSHeejin Ahn // catch_all terminate pad is grouped together with catch terminate pad and 437*e76fa9ecSHeejin Ahn // does not need a separate TRY and END_TRY marker. 438*e76fa9ecSHeejin Ahn if (WebAssembly::isCatchAllTerminatePad(MBB)) 439*e76fa9ecSHeejin Ahn return; 440*e76fa9ecSHeejin Ahn 441*e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 442*e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 443*e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 444*e76fa9ecSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 445*e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 446*e76fa9ecSHeejin Ahn 447*e76fa9ecSHeejin Ahn // Compute the nearest common dominator of all unwind predecessors 448*e76fa9ecSHeejin Ahn MachineBasicBlock *Header = nullptr; 449*e76fa9ecSHeejin Ahn int MBBNumber = MBB.getNumber(); 450*e76fa9ecSHeejin Ahn for (auto *Pred : MBB.predecessors()) { 451*e76fa9ecSHeejin Ahn if (Pred->getNumber() < MBBNumber) { 452*e76fa9ecSHeejin Ahn Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 453*e76fa9ecSHeejin Ahn assert(!ExplicitlyBranchesTo(Pred, &MBB) && 454*e76fa9ecSHeejin Ahn "Explicit branch to an EH pad!"); 455*e76fa9ecSHeejin Ahn } 456*e76fa9ecSHeejin Ahn } 457*e76fa9ecSHeejin Ahn if (!Header) 458*e76fa9ecSHeejin Ahn return; 459*e76fa9ecSHeejin Ahn 460*e76fa9ecSHeejin Ahn // If this try is at the bottom of the function, insert a dummy block at the 461*e76fa9ecSHeejin Ahn // end. 462*e76fa9ecSHeejin Ahn WebAssemblyException *WE = WEI.getExceptionFor(&MBB); 463*e76fa9ecSHeejin Ahn assert(WE); 464*e76fa9ecSHeejin Ahn MachineBasicBlock *Bottom = WebAssembly::getBottom(WE); 465*e76fa9ecSHeejin Ahn 466*e76fa9ecSHeejin Ahn auto Iter = std::next(MachineFunction::iterator(Bottom)); 467*e76fa9ecSHeejin Ahn if (Iter == MF.end()) { 468*e76fa9ecSHeejin Ahn MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 469*e76fa9ecSHeejin Ahn // Give it a fake predecessor so that AsmPrinter prints its label. 470*e76fa9ecSHeejin Ahn Label->addSuccessor(Label); 471*e76fa9ecSHeejin Ahn MF.push_back(Label); 472*e76fa9ecSHeejin Ahn Iter = std::next(MachineFunction::iterator(Bottom)); 473*e76fa9ecSHeejin Ahn } 474*e76fa9ecSHeejin Ahn MachineBasicBlock *AfterTry = &*Iter; 475*e76fa9ecSHeejin Ahn 476*e76fa9ecSHeejin Ahn assert(AfterTry != &MF.front()); 477*e76fa9ecSHeejin Ahn MachineBasicBlock *LayoutPred = 478*e76fa9ecSHeejin Ahn &*std::prev(MachineFunction::iterator(AfterTry)); 479*e76fa9ecSHeejin Ahn 480*e76fa9ecSHeejin Ahn // If the nearest common dominator is inside a more deeply nested context, 481*e76fa9ecSHeejin Ahn // walk out to the nearest scope which isn't more deeply nested. 482*e76fa9ecSHeejin Ahn for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 483*e76fa9ecSHeejin Ahn if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 484*e76fa9ecSHeejin Ahn if (ScopeTop->getNumber() > Header->getNumber()) { 485*e76fa9ecSHeejin Ahn // Skip over an intervening scope. 486*e76fa9ecSHeejin Ahn I = std::next(MachineFunction::iterator(ScopeTop)); 487*e76fa9ecSHeejin Ahn } else { 488*e76fa9ecSHeejin Ahn // We found a scope level at an appropriate depth. 489*e76fa9ecSHeejin Ahn Header = ScopeTop; 490*e76fa9ecSHeejin Ahn break; 491*e76fa9ecSHeejin Ahn } 492*e76fa9ecSHeejin Ahn } 493*e76fa9ecSHeejin Ahn } 494*e76fa9ecSHeejin Ahn 495*e76fa9ecSHeejin Ahn // Decide where in Header to put the TRY. 496*e76fa9ecSHeejin Ahn 497*e76fa9ecSHeejin Ahn // Instructions that should go before the BLOCK. 498*e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 499*e76fa9ecSHeejin Ahn // Instructions that should go after the BLOCK. 500*e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 501*e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 502*e76fa9ecSHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of 503*e76fa9ecSHeejin Ahn // the loop is above MBB, the LOOP should be after the TRY, because the 504*e76fa9ecSHeejin Ahn // loop is nested in this try. Otherwise it should be before the TRY. 505*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) { 506*e76fa9ecSHeejin Ahn if (MBB.getNumber() > Bottom->getNumber()) 507*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 508*e76fa9ecSHeejin Ahn #ifndef NDEBUG 509*e76fa9ecSHeejin Ahn else 510*e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 511*e76fa9ecSHeejin Ahn #endif 512*e76fa9ecSHeejin Ahn } 513*e76fa9ecSHeejin Ahn 514*e76fa9ecSHeejin Ahn // All previously inserted TRY markers should be after the TRY because they 515*e76fa9ecSHeejin Ahn // are all nested trys. 516*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 517*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 518*e76fa9ecSHeejin Ahn 519*e76fa9ecSHeejin Ahn #ifndef NDEBUG 520*e76fa9ecSHeejin Ahn // All END_(LOOP/TRY) markers should be before the TRY. 521*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP || 522*e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 523*e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 524*e76fa9ecSHeejin Ahn #endif 525*e76fa9ecSHeejin Ahn 526*e76fa9ecSHeejin Ahn // Terminators should go after the TRY. 527*e76fa9ecSHeejin Ahn if (MI.isTerminator()) 528*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 529*e76fa9ecSHeejin Ahn } 530*e76fa9ecSHeejin Ahn 531*e76fa9ecSHeejin Ahn // Local expression tree should go after the TRY. 532*e76fa9ecSHeejin Ahn for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 533*e76fa9ecSHeejin Ahn --I) { 534*e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 535*e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 536*e76fa9ecSHeejin Ahn else 537*e76fa9ecSHeejin Ahn break; 538*e76fa9ecSHeejin Ahn } 539*e76fa9ecSHeejin Ahn 540*e76fa9ecSHeejin Ahn // If Header unwinds to MBB (= Header contains 'invoke'), the try block should 541*e76fa9ecSHeejin Ahn // contain the call within it. So the call should go after the TRY. The 542*e76fa9ecSHeejin Ahn // exception is when the header's terminator is a rethrow instruction, in 543*e76fa9ecSHeejin Ahn // which case that instruction, not a call instruction before it, is gonna 544*e76fa9ecSHeejin Ahn // throw. 545*e76fa9ecSHeejin Ahn if (MBB.isPredecessor(Header)) { 546*e76fa9ecSHeejin Ahn auto TermPos = Header->getFirstTerminator(); 547*e76fa9ecSHeejin Ahn if (TermPos == Header->end() || !WebAssembly::isRethrow(*TermPos)) { 548*e76fa9ecSHeejin Ahn for (const auto &MI : reverse(*Header)) { 549*e76fa9ecSHeejin Ahn if (MI.isCall()) { 550*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 551*e76fa9ecSHeejin Ahn break; 552*e76fa9ecSHeejin Ahn } 553*e76fa9ecSHeejin Ahn } 554*e76fa9ecSHeejin Ahn } 555*e76fa9ecSHeejin Ahn } 556*e76fa9ecSHeejin Ahn 557*e76fa9ecSHeejin Ahn // Add the TRY. 558*e76fa9ecSHeejin Ahn auto InsertPos = GetLatestInsertPos(Header, BeforeSet, AfterSet); 559*e76fa9ecSHeejin Ahn MachineInstr *Begin = 560*e76fa9ecSHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 561*e76fa9ecSHeejin Ahn TII.get(WebAssembly::TRY)) 562*e76fa9ecSHeejin Ahn .addImm(int64_t(WebAssembly::ExprType::Void)); 563*e76fa9ecSHeejin Ahn 564*e76fa9ecSHeejin Ahn // Decide where in Header to put the END_TRY. 565*e76fa9ecSHeejin Ahn BeforeSet.clear(); 566*e76fa9ecSHeejin Ahn AfterSet.clear(); 567*e76fa9ecSHeejin Ahn for (const auto &MI : *AfterTry) { 568*e76fa9ecSHeejin Ahn #ifndef NDEBUG 569*e76fa9ecSHeejin Ahn // END_TRY should precede existing LOOP markers. 570*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) 571*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 572*e76fa9ecSHeejin Ahn 573*e76fa9ecSHeejin Ahn // All END_TRY markers placed earlier belong to exceptions that contains 574*e76fa9ecSHeejin Ahn // this one. 575*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_TRY) 576*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 577*e76fa9ecSHeejin Ahn #endif 578*e76fa9ecSHeejin Ahn 579*e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and its header is after 580*e76fa9ecSHeejin Ahn // where TRY marker is, this loop is contained within the 'catch' part, so 581*e76fa9ecSHeejin Ahn // the END_TRY marker should go after that. Otherwise, the whole try-catch 582*e76fa9ecSHeejin Ahn // is contained within this loop, so the END_TRY should go before that. 583*e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) { 584*e76fa9ecSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 585*e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 586*e76fa9ecSHeejin Ahn #ifndef NDEBUG 587*e76fa9ecSHeejin Ahn else 588*e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 589*e76fa9ecSHeejin Ahn #endif 590*e76fa9ecSHeejin Ahn } 591*e76fa9ecSHeejin Ahn } 592*e76fa9ecSHeejin Ahn 593*e76fa9ecSHeejin Ahn // Mark the end of the TRY. 594*e76fa9ecSHeejin Ahn InsertPos = GetEarliestInsertPos(AfterTry, BeforeSet, AfterSet); 595*e76fa9ecSHeejin Ahn MachineInstr *End = 596*e76fa9ecSHeejin Ahn BuildMI(*AfterTry, InsertPos, Bottom->findBranchDebugLoc(), 597*e76fa9ecSHeejin Ahn TII.get(WebAssembly::END_TRY)); 598*e76fa9ecSHeejin Ahn registerTryScope(Begin, End, &MBB); 599*e76fa9ecSHeejin Ahn 600*e76fa9ecSHeejin Ahn // Track the farthest-spanning scope that ends at this point. 601*e76fa9ecSHeejin Ahn int Number = AfterTry->getNumber(); 602*e76fa9ecSHeejin Ahn if (!ScopeTops[Number] || 603*e76fa9ecSHeejin Ahn ScopeTops[Number]->getNumber() > Header->getNumber()) 604*e76fa9ecSHeejin Ahn ScopeTops[Number] = Header; 605*e76fa9ecSHeejin Ahn } 606*e76fa9ecSHeejin Ahn 6071d68e80fSDan Gohman static unsigned 6081d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 6091d68e80fSDan Gohman const MachineBasicBlock *MBB) { 6101d68e80fSDan Gohman unsigned Depth = 0; 6111d68e80fSDan Gohman for (auto X : reverse(Stack)) { 6121d68e80fSDan Gohman if (X == MBB) 6131d68e80fSDan Gohman break; 6141d68e80fSDan Gohman ++Depth; 6151d68e80fSDan Gohman } 6161d68e80fSDan Gohman assert(Depth < Stack.size() && "Branch destination should be in scope"); 6171d68e80fSDan Gohman return Depth; 6181d68e80fSDan Gohman } 6191d68e80fSDan Gohman 6202726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable, 6212726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar, 6222726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of 6232726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks 6242726b88cSDan Gohman /// that end at the function end need to have a return type signature that 6252726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function 6262726b88cSDan Gohman /// checks for such cases and fixes up the signatures. 627*e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) { 628*e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 6292726b88cSDan Gohman assert(MFI.getResults().size() <= 1); 6302726b88cSDan Gohman 6312726b88cSDan Gohman if (MFI.getResults().empty()) 6322726b88cSDan Gohman return; 6332726b88cSDan Gohman 6342726b88cSDan Gohman WebAssembly::ExprType retType; 6352726b88cSDan Gohman switch (MFI.getResults().front().SimpleTy) { 6364fc4e42dSDan Gohman case MVT::i32: retType = WebAssembly::ExprType::I32; break; 6374fc4e42dSDan Gohman case MVT::i64: retType = WebAssembly::ExprType::I64; break; 6384fc4e42dSDan Gohman case MVT::f32: retType = WebAssembly::ExprType::F32; break; 6394fc4e42dSDan Gohman case MVT::f64: retType = WebAssembly::ExprType::F64; break; 6402c783859SDerek Schuff case MVT::v16i8: 6412c783859SDerek Schuff case MVT::v8i16: 6422c783859SDerek Schuff case MVT::v4i32: 64351ed131eSDerek Schuff case MVT::v2i64: 6442c783859SDerek Schuff case MVT::v4f32: 64551ed131eSDerek Schuff case MVT::v2f64: 6462c783859SDerek Schuff retType = WebAssembly::ExprType::V128; 6472c783859SDerek Schuff break; 6480de58729SHeejin Ahn case MVT::ExceptRef: retType = WebAssembly::ExprType::ExceptRef; break; 6492726b88cSDan Gohman default: llvm_unreachable("unexpected return type"); 6502726b88cSDan Gohman } 6512726b88cSDan Gohman 6522726b88cSDan Gohman for (MachineBasicBlock &MBB : reverse(MF)) { 6532726b88cSDan Gohman for (MachineInstr &MI : reverse(MBB)) { 654801bf7ebSShiva Chen if (MI.isPosition() || MI.isDebugInstr()) 6552726b88cSDan Gohman continue; 6562726b88cSDan Gohman if (MI.getOpcode() == WebAssembly::END_BLOCK) { 657*e76fa9ecSHeejin Ahn EndToBegin[&MI]->getOperand(0).setImm(int32_t(retType)); 6582726b88cSDan Gohman continue; 6592726b88cSDan Gohman } 6602726b88cSDan Gohman if (MI.getOpcode() == WebAssembly::END_LOOP) { 661*e76fa9ecSHeejin Ahn EndToBegin[&MI]->getOperand(0).setImm(int32_t(retType)); 6622726b88cSDan Gohman continue; 6632726b88cSDan Gohman } 6642726b88cSDan Gohman // Something other than an `end`. We're done. 6652726b88cSDan Gohman return; 6662726b88cSDan Gohman } 6672726b88cSDan Gohman } 6682726b88cSDan Gohman } 6692726b88cSDan Gohman 670d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body 671d934cb88SDan Gohman // were a block. 672d934cb88SDan Gohman static void AppendEndToFunction( 673d934cb88SDan Gohman MachineFunction &MF, 674d934cb88SDan Gohman const WebAssemblyInstrInfo &TII) { 67510b31358SDerek Schuff BuildMI(MF.back(), MF.back().end(), 67610b31358SDerek Schuff MF.back().findPrevDebugLoc(MF.back().end()), 677d934cb88SDan Gohman TII.get(WebAssembly::END_FUNCTION)); 678d934cb88SDan Gohman } 679d934cb88SDan Gohman 680*e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places. 681*e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) { 682*e76fa9ecSHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 683*e76fa9ecSHeejin Ahn // We allocate one more than the number of blocks in the function to 684*e76fa9ecSHeejin Ahn // accommodate for the possible fake block we may insert at the end. 685*e76fa9ecSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs() + 1); 6868fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 687*e76fa9ecSHeejin Ahn for (auto &MBB : MF) 688*e76fa9ecSHeejin Ahn placeLoopMarker(MBB); 689*e76fa9ecSHeejin Ahn // Place the TRY for MBB if MBB is the EH pad of an exception. 690*e76fa9ecSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 691*e76fa9ecSHeejin Ahn MF.getFunction().hasPersonalityFn()) 692*e76fa9ecSHeejin Ahn for (auto &MBB : MF) 693*e76fa9ecSHeejin Ahn placeTryMarker(MBB); 69432807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 695*e76fa9ecSHeejin Ahn for (auto &MBB : MF) 696*e76fa9ecSHeejin Ahn placeBlockMarker(MBB); 697950a13cfSDan Gohman } 698950a13cfSDan Gohman 699*e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) { 700*e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 7011d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 702*e76fa9ecSHeejin Ahn // We need two stacks: one for normal scopes and the other for EH pad scopes. 703*e76fa9ecSHeejin Ahn // EH pad stack is used to rewrite depths in rethrow instructions. 7041d68e80fSDan Gohman SmallVector<const MachineBasicBlock *, 8> Stack; 705*e76fa9ecSHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack; 7061d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 707*e76fa9ecSHeejin Ahn for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) { 708*e76fa9ecSHeejin Ahn MachineInstr &MI = *I; 7091d68e80fSDan Gohman switch (MI.getOpcode()) { 7101d68e80fSDan Gohman case WebAssembly::BLOCK: 711*e76fa9ecSHeejin Ahn assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= 712*e76fa9ecSHeejin Ahn MBB.getNumber() && 713*e76fa9ecSHeejin Ahn "Block/try should be balanced"); 7141d68e80fSDan Gohman Stack.pop_back(); 7151d68e80fSDan Gohman break; 716*e76fa9ecSHeejin Ahn 717*e76fa9ecSHeejin Ahn case WebAssembly::TRY: 718*e76fa9ecSHeejin Ahn assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= 719*e76fa9ecSHeejin Ahn MBB.getNumber() && 720*e76fa9ecSHeejin Ahn "Block/try marker should be balanced"); 721*e76fa9ecSHeejin Ahn Stack.pop_back(); 722*e76fa9ecSHeejin Ahn EHPadStack.pop_back(); 723*e76fa9ecSHeejin Ahn break; 724*e76fa9ecSHeejin Ahn 725*e76fa9ecSHeejin Ahn case WebAssembly::CATCH_I32: 726*e76fa9ecSHeejin Ahn case WebAssembly::CATCH_I64: 727*e76fa9ecSHeejin Ahn case WebAssembly::CATCH_ALL: 728*e76fa9ecSHeejin Ahn EHPadStack.push_back(&MBB); 729*e76fa9ecSHeejin Ahn break; 730*e76fa9ecSHeejin Ahn 7311d68e80fSDan Gohman case WebAssembly::LOOP: 7321d68e80fSDan Gohman assert(Stack.back() == &MBB && "Loop top should be balanced"); 7331d68e80fSDan Gohman Stack.pop_back(); 7341d68e80fSDan Gohman break; 735*e76fa9ecSHeejin Ahn 7361d68e80fSDan Gohman case WebAssembly::END_BLOCK: 737*e76fa9ecSHeejin Ahn case WebAssembly::END_TRY: 7381d68e80fSDan Gohman Stack.push_back(&MBB); 7391d68e80fSDan Gohman break; 740*e76fa9ecSHeejin Ahn 7411d68e80fSDan Gohman case WebAssembly::END_LOOP: 742*e76fa9ecSHeejin Ahn Stack.push_back(EndToBegin[&MI]->getParent()); 7431d68e80fSDan Gohman break; 744*e76fa9ecSHeejin Ahn 745*e76fa9ecSHeejin Ahn case WebAssembly::RETHROW: { 746*e76fa9ecSHeejin Ahn // Rewrite MBB operands to be depth immediates. 747*e76fa9ecSHeejin Ahn unsigned EHPadDepth = GetDepth(EHPadStack, MI.getOperand(0).getMBB()); 748*e76fa9ecSHeejin Ahn MI.RemoveOperand(0); 749*e76fa9ecSHeejin Ahn MI.addOperand(MF, MachineOperand::CreateImm(EHPadDepth)); 750*e76fa9ecSHeejin Ahn break; 751*e76fa9ecSHeejin Ahn } 752*e76fa9ecSHeejin Ahn 753*e76fa9ecSHeejin Ahn case WebAssembly::RETHROW_TO_CALLER: { 754*e76fa9ecSHeejin Ahn MachineInstr *Rethrow = 755*e76fa9ecSHeejin Ahn BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(WebAssembly::RETHROW)) 756*e76fa9ecSHeejin Ahn .addImm(Stack.size()); 757*e76fa9ecSHeejin Ahn MI.eraseFromParent(); 758*e76fa9ecSHeejin Ahn I = MachineBasicBlock::reverse_iterator(Rethrow); 759*e76fa9ecSHeejin Ahn break; 760*e76fa9ecSHeejin Ahn } 761*e76fa9ecSHeejin Ahn 7621d68e80fSDan Gohman default: 7631d68e80fSDan Gohman if (MI.isTerminator()) { 7641d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 7651d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 7661d68e80fSDan Gohman while (MI.getNumOperands() > 0) 7671d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 7681d68e80fSDan Gohman for (auto MO : Ops) { 7691d68e80fSDan Gohman if (MO.isMBB()) 7701d68e80fSDan Gohman MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB())); 7711d68e80fSDan Gohman MI.addOperand(MF, MO); 77232807932SDan Gohman } 7731d68e80fSDan Gohman } 7741d68e80fSDan Gohman break; 7751d68e80fSDan Gohman } 7761d68e80fSDan Gohman } 7771d68e80fSDan Gohman } 7781d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 779*e76fa9ecSHeejin Ahn } 7802726b88cSDan Gohman 781*e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() { 782*e76fa9ecSHeejin Ahn ScopeTops.clear(); 783*e76fa9ecSHeejin Ahn BeginToEnd.clear(); 784*e76fa9ecSHeejin Ahn EndToBegin.clear(); 785*e76fa9ecSHeejin Ahn TryToEHPad.clear(); 786*e76fa9ecSHeejin Ahn EHPadToTry.clear(); 787*e76fa9ecSHeejin Ahn BeginToBottom.clear(); 7881d68e80fSDan Gohman } 78932807932SDan Gohman 790950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 791d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n" 792950a13cfSDan Gohman "********** Function: " 793950a13cfSDan Gohman << MF.getName() << '\n'); 794950a13cfSDan Gohman 795*e76fa9ecSHeejin Ahn releaseMemory(); 796*e76fa9ecSHeejin Ahn 797e040533eSDan Gohman // Liveness is not tracked for VALUE_STACK physreg. 7989c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness(); 799950a13cfSDan Gohman 800*e76fa9ecSHeejin Ahn // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes. 801*e76fa9ecSHeejin Ahn placeMarkers(MF); 802*e76fa9ecSHeejin Ahn 803*e76fa9ecSHeejin Ahn // Convert MBB operands in terminators to relative depth immediates. 804*e76fa9ecSHeejin Ahn rewriteDepthImmediates(MF); 805*e76fa9ecSHeejin Ahn 806*e76fa9ecSHeejin Ahn // Fix up block/loop/try signatures at the end of the function to conform to 807*e76fa9ecSHeejin Ahn // WebAssembly's rules. 808*e76fa9ecSHeejin Ahn fixEndsAtEndOfFunction(MF); 809*e76fa9ecSHeejin Ahn 810*e76fa9ecSHeejin Ahn // Add an end instruction at the end of the function body. 811*e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 812*e76fa9ecSHeejin Ahn if (!MF.getSubtarget<WebAssemblySubtarget>() 813*e76fa9ecSHeejin Ahn .getTargetTriple() 814*e76fa9ecSHeejin Ahn .isOSBinFormatELF()) 815*e76fa9ecSHeejin Ahn AppendEndToFunction(MF, TII); 81632807932SDan Gohman 817950a13cfSDan Gohman return true; 818950a13cfSDan Gohman } 819