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 11950a13cfSDan Gohman /// \brief This file implements a CFG stacking pass. 12950a13cfSDan Gohman /// 13950a13cfSDan Gohman /// This pass reorders the blocks in a function to put them into a reverse 14950a13cfSDan Gohman /// post-order [0], with special care to keep the order as similar as possible 15950a13cfSDan Gohman /// to the original order, and to keep loops contiguous even in the case of 16950a13cfSDan Gohman /// split backedges. 17950a13cfSDan Gohman /// 18950a13cfSDan Gohman /// Then, it inserts BLOCK and LOOP markers to mark the start of scopes, since 19950a13cfSDan Gohman /// scope boundaries serve as the labels for WebAssembly's control transfers. 20950a13cfSDan Gohman /// 21950a13cfSDan Gohman /// This is sufficient to convert arbitrary CFGs into a form that works on 22950a13cfSDan Gohman /// WebAssembly, provided that all loops are single-entry. 23950a13cfSDan Gohman /// 24950a13cfSDan Gohman /// [0] https://en.wikipedia.org/wiki/Depth-first_search#Vertex_orderings 25950a13cfSDan Gohman /// 26950a13cfSDan Gohman //===----------------------------------------------------------------------===// 27950a13cfSDan Gohman 28950a13cfSDan Gohman #include "WebAssembly.h" 29950a13cfSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 30950a13cfSDan Gohman #include "WebAssemblySubtarget.h" 31950a13cfSDan Gohman #include "llvm/ADT/SCCIterator.h" 328fe7e86bSDan Gohman #include "llvm/ADT/SetVector.h" 3332807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h" 34950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h" 35950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h" 36950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h" 37*9c3bf318SDerek Schuff #include "llvm/CodeGen/MachineRegisterInfo.h" 38950a13cfSDan Gohman #include "llvm/CodeGen/Passes.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 { 47950a13cfSDan Gohman const char *getPassName() const override { 48950a13cfSDan Gohman return "WebAssembly CFG Stackify"; 49950a13cfSDan Gohman } 50950a13cfSDan Gohman 51950a13cfSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override { 52950a13cfSDan Gohman AU.setPreservesCFG(); 5332807932SDan Gohman AU.addRequired<MachineDominatorTree>(); 5432807932SDan Gohman AU.addPreserved<MachineDominatorTree>(); 55950a13cfSDan Gohman AU.addRequired<MachineLoopInfo>(); 56950a13cfSDan Gohman AU.addPreserved<MachineLoopInfo>(); 57950a13cfSDan Gohman MachineFunctionPass::getAnalysisUsage(AU); 58950a13cfSDan Gohman } 59950a13cfSDan Gohman 60950a13cfSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override; 61950a13cfSDan Gohman 62950a13cfSDan Gohman public: 63950a13cfSDan Gohman static char ID; // Pass identification, replacement for typeid 64950a13cfSDan Gohman WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 65950a13cfSDan Gohman }; 66950a13cfSDan Gohman } // end anonymous namespace 67950a13cfSDan Gohman 68950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0; 69950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() { 70950a13cfSDan Gohman return new WebAssemblyCFGStackify(); 71950a13cfSDan Gohman } 72950a13cfSDan Gohman 73950a13cfSDan Gohman static void EliminateMultipleEntryLoops(MachineFunction &MF, 74950a13cfSDan Gohman const MachineLoopInfo &MLI) { 75950a13cfSDan Gohman SmallPtrSet<MachineBasicBlock *, 8> InSet; 76950a13cfSDan Gohman for (scc_iterator<MachineFunction *> I = scc_begin(&MF), E = scc_end(&MF); 77950a13cfSDan Gohman I != E; ++I) { 78950a13cfSDan Gohman const std::vector<MachineBasicBlock *> &CurrentSCC = *I; 79950a13cfSDan Gohman 80950a13cfSDan Gohman // Skip trivial SCCs. 81950a13cfSDan Gohman if (CurrentSCC.size() == 1) 82950a13cfSDan Gohman continue; 83950a13cfSDan Gohman 84950a13cfSDan Gohman InSet.insert(CurrentSCC.begin(), CurrentSCC.end()); 85950a13cfSDan Gohman MachineBasicBlock *Header = nullptr; 86950a13cfSDan Gohman for (MachineBasicBlock *MBB : CurrentSCC) { 87950a13cfSDan Gohman for (MachineBasicBlock *Pred : MBB->predecessors()) { 88950a13cfSDan Gohman if (InSet.count(Pred)) 89950a13cfSDan Gohman continue; 90950a13cfSDan Gohman if (!Header) { 91950a13cfSDan Gohman Header = MBB; 92950a13cfSDan Gohman break; 93950a13cfSDan Gohman } 94950a13cfSDan Gohman // TODO: Implement multiple-entry loops. 95950a13cfSDan Gohman report_fatal_error("multiple-entry loops are not supported yet"); 96950a13cfSDan Gohman } 97950a13cfSDan Gohman } 98950a13cfSDan Gohman assert(MLI.isLoopHeader(Header)); 99950a13cfSDan Gohman 100950a13cfSDan Gohman InSet.clear(); 101950a13cfSDan Gohman } 102950a13cfSDan Gohman } 103950a13cfSDan Gohman 104950a13cfSDan Gohman namespace { 105950a13cfSDan Gohman /// Post-order traversal stack entry. 106950a13cfSDan Gohman struct POStackEntry { 107950a13cfSDan Gohman MachineBasicBlock *MBB; 108950a13cfSDan Gohman SmallVector<MachineBasicBlock *, 0> Succs; 109950a13cfSDan Gohman 110950a13cfSDan Gohman POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF, 111950a13cfSDan Gohman const MachineLoopInfo &MLI); 112950a13cfSDan Gohman }; 113950a13cfSDan Gohman } // end anonymous namespace 114950a13cfSDan Gohman 11532807932SDan Gohman static bool LoopContains(const MachineLoop *Loop, 11632807932SDan Gohman const MachineBasicBlock *MBB) { 11732807932SDan Gohman return Loop ? Loop->contains(MBB) : true; 11832807932SDan Gohman } 11932807932SDan Gohman 120950a13cfSDan Gohman POStackEntry::POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF, 121950a13cfSDan Gohman const MachineLoopInfo &MLI) 122950a13cfSDan Gohman : MBB(MBB), Succs(MBB->successors()) { 123950a13cfSDan Gohman // RPO is not a unique form, since at every basic block with multiple 124950a13cfSDan Gohman // successors, the DFS has to pick which order to visit the successors in. 125950a13cfSDan Gohman // Sort them strategically (see below). 126950a13cfSDan Gohman MachineLoop *Loop = MLI.getLoopFor(MBB); 127950a13cfSDan Gohman MachineFunction::iterator Next = next(MachineFunction::iterator(MBB)); 128950a13cfSDan Gohman MachineBasicBlock *LayoutSucc = Next == MF.end() ? nullptr : &*Next; 129950a13cfSDan Gohman std::stable_sort( 130950a13cfSDan Gohman Succs.begin(), Succs.end(), 131950a13cfSDan Gohman [=, &MLI](const MachineBasicBlock *A, const MachineBasicBlock *B) { 132950a13cfSDan Gohman if (A == B) 133950a13cfSDan Gohman return false; 134950a13cfSDan Gohman 135950a13cfSDan Gohman // Keep loops contiguous by preferring the block that's in the same 136950a13cfSDan Gohman // loop. 13732807932SDan Gohman bool LoopContainsA = LoopContains(Loop, A); 13832807932SDan Gohman bool LoopContainsB = LoopContains(Loop, B); 13932807932SDan Gohman if (LoopContainsA && !LoopContainsB) 140950a13cfSDan Gohman return true; 14132807932SDan Gohman if (!LoopContainsA && LoopContainsB) 142950a13cfSDan Gohman return false; 143950a13cfSDan Gohman 144950a13cfSDan Gohman // Minimize perturbation by preferring the block which is the immediate 145950a13cfSDan Gohman // layout successor. 146950a13cfSDan Gohman if (A == LayoutSucc) 147950a13cfSDan Gohman return true; 148950a13cfSDan Gohman if (B == LayoutSucc) 149950a13cfSDan Gohman return false; 150950a13cfSDan Gohman 151950a13cfSDan Gohman // TODO: More sophisticated orderings may be profitable here. 152950a13cfSDan Gohman 153950a13cfSDan Gohman return false; 154950a13cfSDan Gohman }); 155950a13cfSDan Gohman } 156950a13cfSDan Gohman 1578fe7e86bSDan Gohman /// Return the "bottom" block of a loop. This differs from 1588fe7e86bSDan Gohman /// MachineLoop::getBottomBlock in that it works even if the loop is 1598fe7e86bSDan Gohman /// discontiguous. 1608fe7e86bSDan Gohman static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) { 1618fe7e86bSDan Gohman MachineBasicBlock *Bottom = Loop->getHeader(); 1628fe7e86bSDan Gohman for (MachineBasicBlock *MBB : Loop->blocks()) 1638fe7e86bSDan Gohman if (MBB->getNumber() > Bottom->getNumber()) 1648fe7e86bSDan Gohman Bottom = MBB; 1658fe7e86bSDan Gohman return Bottom; 1668fe7e86bSDan Gohman } 1678fe7e86bSDan Gohman 168950a13cfSDan Gohman /// Sort the blocks in RPO, taking special care to make sure that loops are 169950a13cfSDan Gohman /// contiguous even in the case of split backedges. 1708fe7e86bSDan Gohman /// 1718fe7e86bSDan Gohman /// TODO: Determine whether RPO is actually worthwhile, or whether we should 1728fe7e86bSDan Gohman /// move to just a stable-topological-sort-based approach that would preserve 1738fe7e86bSDan Gohman /// more of the original order. 174950a13cfSDan Gohman static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI) { 175950a13cfSDan Gohman // Note that we do our own RPO rather than using 176950a13cfSDan Gohman // "llvm/ADT/PostOrderIterator.h" because we want control over the order that 177950a13cfSDan Gohman // successors are visited in (see above). Also, we can sort the blocks in the 178950a13cfSDan Gohman // MachineFunction as we go. 179950a13cfSDan Gohman SmallPtrSet<MachineBasicBlock *, 16> Visited; 180950a13cfSDan Gohman SmallVector<POStackEntry, 16> Stack; 181950a13cfSDan Gohman 18296029f78SDan Gohman MachineBasicBlock *EntryBlock = &*MF.begin(); 18396029f78SDan Gohman Visited.insert(EntryBlock); 18496029f78SDan Gohman Stack.push_back(POStackEntry(EntryBlock, MF, MLI)); 185950a13cfSDan Gohman 186950a13cfSDan Gohman for (;;) { 187950a13cfSDan Gohman POStackEntry &Entry = Stack.back(); 188950a13cfSDan Gohman SmallVectorImpl<MachineBasicBlock *> &Succs = Entry.Succs; 189950a13cfSDan Gohman if (!Succs.empty()) { 190950a13cfSDan Gohman MachineBasicBlock *Succ = Succs.pop_back_val(); 191950a13cfSDan Gohman if (Visited.insert(Succ).second) 192950a13cfSDan Gohman Stack.push_back(POStackEntry(Succ, MF, MLI)); 193950a13cfSDan Gohman continue; 194950a13cfSDan Gohman } 195950a13cfSDan Gohman 196950a13cfSDan Gohman // Put the block in its position in the MachineFunction. 197950a13cfSDan Gohman MachineBasicBlock &MBB = *Entry.MBB; 19800406472SNico Weber MBB.moveBefore(&*MF.begin()); 199950a13cfSDan Gohman 200950a13cfSDan Gohman // Branch instructions may utilize a fallthrough, so update them if a 201950a13cfSDan Gohman // fallthrough has been added or removed. 202950a13cfSDan Gohman if (!MBB.empty() && MBB.back().isTerminator() && !MBB.back().isBranch() && 203950a13cfSDan Gohman !MBB.back().isBarrier()) 204950a13cfSDan Gohman report_fatal_error( 205950a13cfSDan Gohman "Non-branch terminator with fallthrough cannot yet be rewritten"); 206950a13cfSDan Gohman if (MBB.empty() || !MBB.back().isTerminator() || MBB.back().isBranch()) 207950a13cfSDan Gohman MBB.updateTerminator(); 208950a13cfSDan Gohman 209950a13cfSDan Gohman Stack.pop_back(); 210950a13cfSDan Gohman if (Stack.empty()) 211950a13cfSDan Gohman break; 212950a13cfSDan Gohman } 213950a13cfSDan Gohman 214950a13cfSDan Gohman // Now that we've sorted the blocks in RPO, renumber them. 215950a13cfSDan Gohman MF.RenumberBlocks(); 216950a13cfSDan Gohman 217950a13cfSDan Gohman #ifndef NDEBUG 2188fe7e86bSDan Gohman SmallSetVector<MachineLoop *, 8> OnStack; 2198fe7e86bSDan Gohman 2208fe7e86bSDan Gohman // Insert a sentinel representing the degenerate loop that starts at the 2218fe7e86bSDan Gohman // function entry block and includes the entire function as a "loop" that 2228fe7e86bSDan Gohman // executes once. 2238fe7e86bSDan Gohman OnStack.insert(nullptr); 2248fe7e86bSDan Gohman 2258fe7e86bSDan Gohman for (auto &MBB : MF) { 2268fe7e86bSDan Gohman assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative."); 2278fe7e86bSDan Gohman 2288fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 2298fe7e86bSDan Gohman if (Loop && &MBB == Loop->getHeader()) { 2308fe7e86bSDan Gohman // Loop header. The loop predecessor should be sorted above, and the other 2318fe7e86bSDan Gohman // predecessors should be backedges below. 2328fe7e86bSDan Gohman for (auto Pred : MBB.predecessors()) 2338fe7e86bSDan Gohman assert( 2348fe7e86bSDan Gohman (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) && 2358fe7e86bSDan Gohman "Loop header predecessors must be loop predecessors or backedges"); 2368fe7e86bSDan Gohman assert(OnStack.insert(Loop) && "Loops should be declared at most once."); 23732807932SDan Gohman } else { 2388fe7e86bSDan Gohman // Not a loop header. All predecessors should be sorted above. 239950a13cfSDan Gohman for (auto Pred : MBB.predecessors()) 240950a13cfSDan Gohman assert(Pred->getNumber() < MBB.getNumber() && 2418fe7e86bSDan Gohman "Non-loop-header predecessors should be topologically sorted"); 2428fe7e86bSDan Gohman assert(OnStack.count(MLI.getLoopFor(&MBB)) && 2438fe7e86bSDan Gohman "Blocks must be nested in their loops"); 244950a13cfSDan Gohman } 2458fe7e86bSDan Gohman while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back())) 2468fe7e86bSDan Gohman OnStack.pop_back(); 2478fe7e86bSDan Gohman } 2488fe7e86bSDan Gohman assert(OnStack.pop_back_val() == nullptr && 2498fe7e86bSDan Gohman "The function entry block shouldn't actually be a loop header"); 2508fe7e86bSDan Gohman assert(OnStack.empty() && 2518fe7e86bSDan Gohman "Control flow stack pushes and pops should be balanced."); 252950a13cfSDan Gohman #endif 253950a13cfSDan Gohman } 254950a13cfSDan Gohman 255b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as 256b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized 257b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough 258b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any 259b3aa1ecaSDan Gohman /// explicit mentions. 26035e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred, 26135e4a289SDan Gohman MachineBasicBlock *MBB) { 262b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators()) 263b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands()) 264b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB) 265b3aa1ecaSDan Gohman return true; 266b3aa1ecaSDan Gohman return false; 267b3aa1ecaSDan Gohman } 268b3aa1ecaSDan Gohman 26932807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed). 2708fe7e86bSDan Gohman static void PlaceBlockMarker(MachineBasicBlock &MBB, MachineFunction &MF, 2718fe7e86bSDan Gohman SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 27232807932SDan Gohman const WebAssemblyInstrInfo &TII, 2738fe7e86bSDan Gohman const MachineLoopInfo &MLI, 2748fe7e86bSDan Gohman MachineDominatorTree &MDT) { 2758fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough 2768fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack, 2778fe7e86bSDan Gohman // which reduces overall stack height. 27832807932SDan Gohman MachineBasicBlock *Header = nullptr; 27932807932SDan Gohman bool IsBranchedTo = false; 28032807932SDan Gohman int MBBNumber = MBB.getNumber(); 28132807932SDan Gohman for (MachineBasicBlock *Pred : MBB.predecessors()) 28232807932SDan Gohman if (Pred->getNumber() < MBBNumber) { 28332807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 284b3aa1ecaSDan Gohman if (ExplicitlyBranchesTo(Pred, &MBB)) 28532807932SDan Gohman IsBranchedTo = true; 28632807932SDan Gohman } 28732807932SDan Gohman if (!Header) 28832807932SDan Gohman return; 28932807932SDan Gohman if (!IsBranchedTo) 29032807932SDan Gohman return; 29132807932SDan Gohman 2928fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 2938fe7e86bSDan Gohman MachineBasicBlock *LayoutPred = &*prev(MachineFunction::iterator(&MBB)); 2948fe7e86bSDan Gohman 2958fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context, 2968fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested. 2978fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 2988fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 2998fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) { 3008fe7e86bSDan Gohman // Skip over an intervening scope. 3018fe7e86bSDan Gohman I = next(MachineFunction::iterator(ScopeTop)); 3028fe7e86bSDan Gohman } else { 3038fe7e86bSDan Gohman // We found a scope level at an appropriate depth. 3048fe7e86bSDan Gohman Header = ScopeTop; 3058fe7e86bSDan Gohman break; 3068fe7e86bSDan Gohman } 3078fe7e86bSDan Gohman } 3088fe7e86bSDan Gohman } 3098fe7e86bSDan Gohman 3108fe7e86bSDan Gohman // If there's a loop which ends just before MBB which contains Header, we can 3118fe7e86bSDan Gohman // reuse its label instead of inserting a new BLOCK. 3128fe7e86bSDan Gohman for (MachineLoop *Loop = MLI.getLoopFor(LayoutPred); 3138fe7e86bSDan Gohman Loop && Loop->contains(LayoutPred); Loop = Loop->getParentLoop()) 3148fe7e86bSDan Gohman if (Loop && LoopBottom(Loop) == LayoutPred && Loop->contains(Header)) 3158fe7e86bSDan Gohman return; 3168fe7e86bSDan Gohman 3178fe7e86bSDan Gohman // Decide where in Header to put the BLOCK. 31832807932SDan Gohman MachineBasicBlock::iterator InsertPos; 31932807932SDan Gohman MachineLoop *HeaderLoop = MLI.getLoopFor(Header); 3208fe7e86bSDan Gohman if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) { 3218fe7e86bSDan Gohman // Header is the header of a loop that does not lexically contain MBB, so 3228fe7e86bSDan Gohman // the BLOCK needs to be above the LOOP. 32332807932SDan Gohman InsertPos = Header->begin(); 32432807932SDan Gohman } else { 3258887d1faSDan Gohman // Otherwise, insert the BLOCK as late in Header as we can, but before the 3268887d1faSDan Gohman // beginning of the local expression tree and any nested BLOCKs. 32732807932SDan Gohman InsertPos = Header->getFirstTerminator(); 32832807932SDan Gohman while (InsertPos != Header->begin() && 3298887d1faSDan Gohman prev(InsertPos)->definesRegister(WebAssembly::EXPR_STACK) && 3301d68e80fSDan Gohman prev(InsertPos)->getOpcode() != WebAssembly::LOOP && 3311d68e80fSDan Gohman prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK && 3321d68e80fSDan Gohman prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP) 33332807932SDan Gohman --InsertPos; 33432807932SDan Gohman } 33532807932SDan Gohman 3368fe7e86bSDan Gohman // Add the BLOCK. 3371d68e80fSDan Gohman BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK)); 3381d68e80fSDan Gohman 3391d68e80fSDan Gohman // Mark the end of the block. 3401d68e80fSDan Gohman InsertPos = MBB.begin(); 3411d68e80fSDan Gohman while (InsertPos != MBB.end() && 3421d68e80fSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP) 3431d68e80fSDan Gohman ++InsertPos; 3441d68e80fSDan Gohman BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK)); 3458fe7e86bSDan Gohman 3468fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3478fe7e86bSDan Gohman int Number = MBB.getNumber(); 3488fe7e86bSDan Gohman if (!ScopeTops[Number] || 3498fe7e86bSDan Gohman ScopeTops[Number]->getNumber() > Header->getNumber()) 3508fe7e86bSDan Gohman ScopeTops[Number] = Header; 351950a13cfSDan Gohman } 352950a13cfSDan Gohman 3538fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 3541d68e80fSDan Gohman static void PlaceLoopMarker( 3551d68e80fSDan Gohman MachineBasicBlock &MBB, MachineFunction &MF, 3568fe7e86bSDan Gohman SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 3571d68e80fSDan Gohman DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops, 3581d68e80fSDan Gohman const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) { 3598fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 3608fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 3618fe7e86bSDan Gohman return; 3628fe7e86bSDan Gohman 3638fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 3648fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 3658fe7e86bSDan Gohman MachineBasicBlock *Bottom = LoopBottom(Loop); 366e3e4a5ffSDan Gohman auto Iter = next(MachineFunction::iterator(Bottom)); 367e3e4a5ffSDan Gohman if (Iter == MF.end()) { 368f6857223SDan Gohman MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 369f6857223SDan Gohman // Give it a fake predecessor so that AsmPrinter prints its label. 370f6857223SDan Gohman Label->addSuccessor(Label); 371f6857223SDan Gohman MF.push_back(Label); 372e3e4a5ffSDan Gohman Iter = next(MachineFunction::iterator(Bottom)); 373e3e4a5ffSDan Gohman } 3748fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 375f6857223SDan Gohman 3761d68e80fSDan Gohman // Mark the beginning of the loop (after the end of any existing loop that 3771d68e80fSDan Gohman // ends here). 3781d68e80fSDan Gohman auto InsertPos = MBB.begin(); 3791d68e80fSDan Gohman while (InsertPos != MBB.end() && 3801d68e80fSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP) 3811d68e80fSDan Gohman ++InsertPos; 3821d68e80fSDan Gohman BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP)); 3831d68e80fSDan Gohman 3841d68e80fSDan Gohman // Mark the end of the loop. 3851d68e80fSDan Gohman MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(), 3861d68e80fSDan Gohman TII.get(WebAssembly::END_LOOP)); 3871d68e80fSDan Gohman LoopTops[End] = &MBB; 3888fe7e86bSDan Gohman 3898fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 3908fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 3918fe7e86bSDan Gohman "With RPO we should visit the outer-most loop for a block first."); 3928fe7e86bSDan Gohman if (!ScopeTops[AfterLoop->getNumber()]) 3938fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()] = &MBB; 394e3e4a5ffSDan Gohman } 395950a13cfSDan Gohman 3961d68e80fSDan Gohman static unsigned 3971d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 3981d68e80fSDan Gohman const MachineBasicBlock *MBB) { 3991d68e80fSDan Gohman unsigned Depth = 0; 4001d68e80fSDan Gohman for (auto X : reverse(Stack)) { 4011d68e80fSDan Gohman if (X == MBB) 4021d68e80fSDan Gohman break; 4031d68e80fSDan Gohman ++Depth; 4041d68e80fSDan Gohman } 4051d68e80fSDan Gohman assert(Depth < Stack.size() && "Branch destination should be in scope"); 4061d68e80fSDan Gohman return Depth; 4071d68e80fSDan Gohman } 4081d68e80fSDan Gohman 4098fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places. 4108fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI, 4118fe7e86bSDan Gohman const WebAssemblyInstrInfo &TII, 4128fe7e86bSDan Gohman MachineDominatorTree &MDT) { 4138fe7e86bSDan Gohman // For each block whose label represents the end of a scope, record the block 4148fe7e86bSDan Gohman // which holds the beginning of the scope. This will allow us to quickly skip 4158fe7e86bSDan Gohman // over scoped regions when walking blocks. We allocate one more than the 4168fe7e86bSDan Gohman // number of blocks in the function to accommodate for the possible fake block 4178fe7e86bSDan Gohman // we may insert at the end. 4188fe7e86bSDan Gohman SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1); 4198fe7e86bSDan Gohman 4201d68e80fSDan Gohman // For eacn LOOP_END, the corresponding LOOP. 4211d68e80fSDan Gohman DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops; 4221d68e80fSDan Gohman 4238fe7e86bSDan Gohman for (auto &MBB : MF) { 4248fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 4251d68e80fSDan Gohman PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI); 4268fe7e86bSDan Gohman 42732807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 4288fe7e86bSDan Gohman PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT); 429950a13cfSDan Gohman } 430950a13cfSDan Gohman 4311d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 4321d68e80fSDan Gohman SmallVector<const MachineBasicBlock *, 8> Stack; 4331d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 4341d68e80fSDan Gohman for (auto &MI : reverse(MBB)) { 4351d68e80fSDan Gohman switch (MI.getOpcode()) { 4361d68e80fSDan Gohman case WebAssembly::BLOCK: 4371d68e80fSDan Gohman assert(ScopeTops[Stack.back()->getNumber()] == &MBB && 4381d68e80fSDan Gohman "Block should be balanced"); 4391d68e80fSDan Gohman Stack.pop_back(); 4401d68e80fSDan Gohman break; 4411d68e80fSDan Gohman case WebAssembly::LOOP: 4421d68e80fSDan Gohman assert(Stack.back() == &MBB && "Loop top should be balanced"); 4431d68e80fSDan Gohman Stack.pop_back(); 4441d68e80fSDan Gohman Stack.pop_back(); 4451d68e80fSDan Gohman break; 4461d68e80fSDan Gohman case WebAssembly::END_BLOCK: 4471d68e80fSDan Gohman Stack.push_back(&MBB); 4481d68e80fSDan Gohman break; 4491d68e80fSDan Gohman case WebAssembly::END_LOOP: 4501d68e80fSDan Gohman Stack.push_back(&MBB); 4511d68e80fSDan Gohman Stack.push_back(LoopTops[&MI]); 4521d68e80fSDan Gohman break; 4531d68e80fSDan Gohman default: 4541d68e80fSDan Gohman if (MI.isTerminator()) { 4551d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 4561d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 4571d68e80fSDan Gohman while (MI.getNumOperands() > 0) 4581d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 4591d68e80fSDan Gohman for (auto MO : Ops) { 4601d68e80fSDan Gohman if (MO.isMBB()) 4611d68e80fSDan Gohman MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB())); 4621d68e80fSDan Gohman MI.addOperand(MF, MO); 46332807932SDan Gohman } 4641d68e80fSDan Gohman } 4651d68e80fSDan Gohman break; 4661d68e80fSDan Gohman } 4671d68e80fSDan Gohman } 4681d68e80fSDan Gohman } 4691d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 4701d68e80fSDan Gohman } 47132807932SDan Gohman 472950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 473950a13cfSDan Gohman DEBUG(dbgs() << "********** CFG Stackifying **********\n" 474950a13cfSDan Gohman "********** Function: " 475950a13cfSDan Gohman << MF.getName() << '\n'); 476950a13cfSDan Gohman 477950a13cfSDan Gohman const auto &MLI = getAnalysis<MachineLoopInfo>(); 47832807932SDan Gohman auto &MDT = getAnalysis<MachineDominatorTree>(); 479*9c3bf318SDerek Schuff // Liveness is not tracked for EXPR_STACK physreg. 480950a13cfSDan Gohman const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 481*9c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness(); 482950a13cfSDan Gohman 483950a13cfSDan Gohman // RPO sorting needs all loops to be single-entry. 484950a13cfSDan Gohman EliminateMultipleEntryLoops(MF, MLI); 485950a13cfSDan Gohman 486950a13cfSDan Gohman // Sort the blocks in RPO, with contiguous loops. 487950a13cfSDan Gohman SortBlocks(MF, MLI); 488950a13cfSDan Gohman 489950a13cfSDan Gohman // Place the BLOCK and LOOP markers to indicate the beginnings of scopes. 49032807932SDan Gohman PlaceMarkers(MF, MLI, TII, MDT); 49132807932SDan Gohman 492950a13cfSDan Gohman return true; 493950a13cfSDan Gohman } 494