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 /// 13442bfcecSDan Gohman /// This pass reorders the blocks in a function to put them into topological 14442bfcecSDan Gohman /// order, ignoring loop backedges, and without any loop being interrupted 15442bfcecSDan Gohman /// by a block not dominated by the loop header, with special care to keep the 16442bfcecSDan Gohman /// order as similar as possible to the original order. 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 //===----------------------------------------------------------------------===// 25950a13cfSDan Gohman 26950a13cfSDan Gohman #include "WebAssembly.h" 27950a13cfSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 28ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h" 29950a13cfSDan Gohman #include "WebAssemblySubtarget.h" 30442bfcecSDan Gohman #include "llvm/ADT/PriorityQueue.h" 318fe7e86bSDan Gohman #include "llvm/ADT/SetVector.h" 3232807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h" 33950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h" 34950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h" 35950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h" 369c3bf318SDerek Schuff #include "llvm/CodeGen/MachineRegisterInfo.h" 37950a13cfSDan Gohman #include "llvm/CodeGen/Passes.h" 38950a13cfSDan Gohman #include "llvm/Support/Debug.h" 39950a13cfSDan Gohman #include "llvm/Support/raw_ostream.h" 40950a13cfSDan Gohman using namespace llvm; 41950a13cfSDan Gohman 42950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify" 43950a13cfSDan Gohman 44950a13cfSDan Gohman namespace { 45950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass { 46117296c0SMehdi Amini StringRef getPassName() const override { return "WebAssembly CFG Stackify"; } 47950a13cfSDan Gohman 48950a13cfSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override { 49950a13cfSDan Gohman AU.setPreservesCFG(); 5032807932SDan Gohman AU.addRequired<MachineDominatorTree>(); 5132807932SDan Gohman AU.addPreserved<MachineDominatorTree>(); 52950a13cfSDan Gohman AU.addRequired<MachineLoopInfo>(); 53950a13cfSDan Gohman AU.addPreserved<MachineLoopInfo>(); 54950a13cfSDan Gohman MachineFunctionPass::getAnalysisUsage(AU); 55950a13cfSDan Gohman } 56950a13cfSDan Gohman 57950a13cfSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override; 58950a13cfSDan Gohman 59950a13cfSDan Gohman public: 60950a13cfSDan Gohman static char ID; // Pass identification, replacement for typeid 61950a13cfSDan Gohman WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 62950a13cfSDan Gohman }; 63950a13cfSDan Gohman } // end anonymous namespace 64950a13cfSDan Gohman 65950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0; 66950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() { 67950a13cfSDan Gohman return new WebAssemblyCFGStackify(); 68950a13cfSDan Gohman } 69950a13cfSDan Gohman 708fe7e86bSDan Gohman /// Return the "bottom" block of a loop. This differs from 718fe7e86bSDan Gohman /// MachineLoop::getBottomBlock in that it works even if the loop is 728fe7e86bSDan Gohman /// discontiguous. 738fe7e86bSDan Gohman static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) { 748fe7e86bSDan Gohman MachineBasicBlock *Bottom = Loop->getHeader(); 758fe7e86bSDan Gohman for (MachineBasicBlock *MBB : Loop->blocks()) 768fe7e86bSDan Gohman if (MBB->getNumber() > Bottom->getNumber()) 778fe7e86bSDan Gohman Bottom = MBB; 788fe7e86bSDan Gohman return Bottom; 798fe7e86bSDan Gohman } 808fe7e86bSDan Gohman 81442bfcecSDan Gohman static void MaybeUpdateTerminator(MachineBasicBlock *MBB) { 82442bfcecSDan Gohman #ifndef NDEBUG 83442bfcecSDan Gohman bool AnyBarrier = false; 84442bfcecSDan Gohman #endif 85442bfcecSDan Gohman bool AllAnalyzable = true; 86442bfcecSDan Gohman for (const MachineInstr &Term : MBB->terminators()) { 87442bfcecSDan Gohman #ifndef NDEBUG 88442bfcecSDan Gohman AnyBarrier |= Term.isBarrier(); 89442bfcecSDan Gohman #endif 90442bfcecSDan Gohman AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch(); 91442bfcecSDan Gohman } 92442bfcecSDan Gohman assert((AnyBarrier || AllAnalyzable) && 93442bfcecSDan Gohman "AnalyzeBranch needs to analyze any block with a fallthrough"); 94442bfcecSDan Gohman if (AllAnalyzable) 95442bfcecSDan Gohman MBB->updateTerminator(); 96442bfcecSDan Gohman } 97950a13cfSDan Gohman 98442bfcecSDan Gohman namespace { 99442bfcecSDan Gohman /// Sort blocks by their number. 100442bfcecSDan Gohman struct CompareBlockNumbers { 101442bfcecSDan Gohman bool operator()(const MachineBasicBlock *A, 102442bfcecSDan Gohman const MachineBasicBlock *B) const { 103442bfcecSDan Gohman return A->getNumber() > B->getNumber(); 104442bfcecSDan Gohman } 105442bfcecSDan Gohman }; 106442bfcecSDan Gohman /// Sort blocks by their number in the opposite order.. 107442bfcecSDan Gohman struct CompareBlockNumbersBackwards { 108442bfcecSDan Gohman bool operator()(const MachineBasicBlock *A, 109442bfcecSDan Gohman const MachineBasicBlock *B) const { 110442bfcecSDan Gohman return A->getNumber() < B->getNumber(); 111442bfcecSDan Gohman } 112442bfcecSDan Gohman }; 113442bfcecSDan Gohman /// Bookkeeping for a loop to help ensure that we don't mix blocks not dominated 114442bfcecSDan Gohman /// by the loop header among the loop's blocks. 115442bfcecSDan Gohman struct Entry { 116442bfcecSDan Gohman const MachineLoop *Loop; 117442bfcecSDan Gohman unsigned NumBlocksLeft; 118950a13cfSDan Gohman 119442bfcecSDan Gohman /// List of blocks not dominated by Loop's header that are deferred until 120442bfcecSDan Gohman /// after all of Loop's blocks have been seen. 121442bfcecSDan Gohman std::vector<MachineBasicBlock *> Deferred; 122442bfcecSDan Gohman 123442bfcecSDan Gohman explicit Entry(const MachineLoop *L) 124442bfcecSDan Gohman : Loop(L), NumBlocksLeft(L->getNumBlocks()) {} 125442bfcecSDan Gohman }; 126442bfcecSDan Gohman } 127442bfcecSDan Gohman 128442bfcecSDan Gohman /// Sort the blocks, taking special care to make sure that loops are not 129442bfcecSDan Gohman /// interrupted by blocks not dominated by their header. 130442bfcecSDan Gohman /// TODO: There are many opportunities for improving the heuristics here. 131442bfcecSDan Gohman /// Explore them. 132442bfcecSDan Gohman static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI, 133442bfcecSDan Gohman const MachineDominatorTree &MDT) { 134442bfcecSDan Gohman // Prepare for a topological sort: Record the number of predecessors each 135442bfcecSDan Gohman // block has, ignoring loop backedges. 136442bfcecSDan Gohman MF.RenumberBlocks(); 137442bfcecSDan Gohman SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0); 138442bfcecSDan Gohman for (MachineBasicBlock &MBB : MF) { 139442bfcecSDan Gohman unsigned N = MBB.pred_size(); 140442bfcecSDan Gohman if (MachineLoop *L = MLI.getLoopFor(&MBB)) 141442bfcecSDan Gohman if (L->getHeader() == &MBB) 142442bfcecSDan Gohman for (const MachineBasicBlock *Pred : MBB.predecessors()) 143442bfcecSDan Gohman if (L->contains(Pred)) 144442bfcecSDan Gohman --N; 145442bfcecSDan Gohman NumPredsLeft[MBB.getNumber()] = N; 146442bfcecSDan Gohman } 147442bfcecSDan Gohman 148442bfcecSDan Gohman // Topological sort the CFG, with additional constraints: 149442bfcecSDan Gohman // - Between a loop header and the last block in the loop, there can be 150442bfcecSDan Gohman // no blocks not dominated by the loop header. 151442bfcecSDan Gohman // - It's desirable to preserve the original block order when possible. 152442bfcecSDan Gohman // We use two ready lists; Preferred and Ready. Preferred has recently 153442bfcecSDan Gohman // processed sucessors, to help preserve block sequences from the original 154442bfcecSDan Gohman // order. Ready has the remaining ready blocks. 155442bfcecSDan Gohman PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>, 156442bfcecSDan Gohman CompareBlockNumbers> 157442bfcecSDan Gohman Preferred; 158442bfcecSDan Gohman PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>, 159442bfcecSDan Gohman CompareBlockNumbersBackwards> 160442bfcecSDan Gohman Ready; 161442bfcecSDan Gohman SmallVector<Entry, 4> Loops; 162442bfcecSDan Gohman for (MachineBasicBlock *MBB = &MF.front();;) { 163442bfcecSDan Gohman const MachineLoop *L = MLI.getLoopFor(MBB); 164442bfcecSDan Gohman if (L) { 165442bfcecSDan Gohman // If MBB is a loop header, add it to the active loop list. We can't put 166442bfcecSDan Gohman // any blocks that it doesn't dominate until we see the end of the loop. 167442bfcecSDan Gohman if (L->getHeader() == MBB) 168442bfcecSDan Gohman Loops.push_back(Entry(L)); 169442bfcecSDan Gohman // For each active loop the block is in, decrement the count. If MBB is 170442bfcecSDan Gohman // the last block in an active loop, take it off the list and pick up any 171442bfcecSDan Gohman // blocks deferred because the header didn't dominate them. 172442bfcecSDan Gohman for (Entry &E : Loops) 173442bfcecSDan Gohman if (E.Loop->contains(MBB) && --E.NumBlocksLeft == 0) 174442bfcecSDan Gohman for (auto DeferredBlock : E.Deferred) 175442bfcecSDan Gohman Ready.push(DeferredBlock); 176442bfcecSDan Gohman while (!Loops.empty() && Loops.back().NumBlocksLeft == 0) 177442bfcecSDan Gohman Loops.pop_back(); 178442bfcecSDan Gohman } 179442bfcecSDan Gohman // The main topological sort logic. 180442bfcecSDan Gohman for (MachineBasicBlock *Succ : MBB->successors()) { 181442bfcecSDan Gohman // Ignore backedges. 182442bfcecSDan Gohman if (MachineLoop *SuccL = MLI.getLoopFor(Succ)) 183442bfcecSDan Gohman if (SuccL->getHeader() == Succ && SuccL->contains(MBB)) 184442bfcecSDan Gohman continue; 185442bfcecSDan Gohman // Decrement the predecessor count. If it's now zero, it's ready. 186442bfcecSDan Gohman if (--NumPredsLeft[Succ->getNumber()] == 0) 187442bfcecSDan Gohman Preferred.push(Succ); 188442bfcecSDan Gohman } 189442bfcecSDan Gohman // Determine the block to follow MBB. First try to find a preferred block, 190442bfcecSDan Gohman // to preserve the original block order when possible. 191442bfcecSDan Gohman MachineBasicBlock *Next = nullptr; 192442bfcecSDan Gohman while (!Preferred.empty()) { 193442bfcecSDan Gohman Next = Preferred.top(); 194442bfcecSDan Gohman Preferred.pop(); 195442bfcecSDan Gohman // If X isn't dominated by the top active loop header, defer it until that 196442bfcecSDan Gohman // loop is done. 197442bfcecSDan Gohman if (!Loops.empty() && 198442bfcecSDan Gohman !MDT.dominates(Loops.back().Loop->getHeader(), Next)) { 199442bfcecSDan Gohman Loops.back().Deferred.push_back(Next); 200442bfcecSDan Gohman Next = nullptr; 201950a13cfSDan Gohman continue; 202950a13cfSDan Gohman } 203442bfcecSDan Gohman // If Next was originally ordered before MBB, and it isn't because it was 204442bfcecSDan Gohman // loop-rotated above the header, it's not preferred. 205442bfcecSDan Gohman if (Next->getNumber() < MBB->getNumber() && 206442bfcecSDan Gohman (!L || !L->contains(Next) || 207442bfcecSDan Gohman L->getHeader()->getNumber() < Next->getNumber())) { 208442bfcecSDan Gohman Ready.push(Next); 209442bfcecSDan Gohman Next = nullptr; 210442bfcecSDan Gohman continue; 211442bfcecSDan Gohman } 212950a13cfSDan Gohman break; 213950a13cfSDan Gohman } 214442bfcecSDan Gohman // If we didn't find a suitable block in the Preferred list, check the 215442bfcecSDan Gohman // general Ready list. 216442bfcecSDan Gohman if (!Next) { 217442bfcecSDan Gohman // If there are no more blocks to process, we're done. 218442bfcecSDan Gohman if (Ready.empty()) { 219442bfcecSDan Gohman MaybeUpdateTerminator(MBB); 220442bfcecSDan Gohman break; 221442bfcecSDan Gohman } 222442bfcecSDan Gohman for (;;) { 223442bfcecSDan Gohman Next = Ready.top(); 224442bfcecSDan Gohman Ready.pop(); 225442bfcecSDan Gohman // If Next isn't dominated by the top active loop header, defer it until 226442bfcecSDan Gohman // that loop is done. 227442bfcecSDan Gohman if (!Loops.empty() && 228442bfcecSDan Gohman !MDT.dominates(Loops.back().Loop->getHeader(), Next)) { 229442bfcecSDan Gohman Loops.back().Deferred.push_back(Next); 230442bfcecSDan Gohman continue; 231442bfcecSDan Gohman } 232442bfcecSDan Gohman break; 233442bfcecSDan Gohman } 234442bfcecSDan Gohman } 235442bfcecSDan Gohman // Move the next block into place and iterate. 236442bfcecSDan Gohman Next->moveAfter(MBB); 237442bfcecSDan Gohman MaybeUpdateTerminator(MBB); 238442bfcecSDan Gohman MBB = Next; 239442bfcecSDan Gohman } 240442bfcecSDan Gohman assert(Loops.empty() && "Active loop list not finished"); 241950a13cfSDan Gohman MF.RenumberBlocks(); 242950a13cfSDan Gohman 243950a13cfSDan Gohman #ifndef NDEBUG 2448fe7e86bSDan Gohman SmallSetVector<MachineLoop *, 8> OnStack; 2458fe7e86bSDan Gohman 2468fe7e86bSDan Gohman // Insert a sentinel representing the degenerate loop that starts at the 2478fe7e86bSDan Gohman // function entry block and includes the entire function as a "loop" that 2488fe7e86bSDan Gohman // executes once. 2498fe7e86bSDan Gohman OnStack.insert(nullptr); 2508fe7e86bSDan Gohman 2518fe7e86bSDan Gohman for (auto &MBB : MF) { 2528fe7e86bSDan Gohman assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative."); 2538fe7e86bSDan Gohman 2548fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 2558fe7e86bSDan Gohman if (Loop && &MBB == Loop->getHeader()) { 2568fe7e86bSDan Gohman // Loop header. The loop predecessor should be sorted above, and the other 2578fe7e86bSDan Gohman // predecessors should be backedges below. 2588fe7e86bSDan Gohman for (auto Pred : MBB.predecessors()) 2598fe7e86bSDan Gohman assert( 2608fe7e86bSDan Gohman (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) && 2618fe7e86bSDan Gohman "Loop header predecessors must be loop predecessors or backedges"); 2628fe7e86bSDan Gohman assert(OnStack.insert(Loop) && "Loops should be declared at most once."); 26332807932SDan Gohman } else { 2648fe7e86bSDan Gohman // Not a loop header. All predecessors should be sorted above. 265950a13cfSDan Gohman for (auto Pred : MBB.predecessors()) 266950a13cfSDan Gohman assert(Pred->getNumber() < MBB.getNumber() && 2678fe7e86bSDan Gohman "Non-loop-header predecessors should be topologically sorted"); 2688fe7e86bSDan Gohman assert(OnStack.count(MLI.getLoopFor(&MBB)) && 2698fe7e86bSDan Gohman "Blocks must be nested in their loops"); 270950a13cfSDan Gohman } 2718fe7e86bSDan Gohman while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back())) 2728fe7e86bSDan Gohman OnStack.pop_back(); 2738fe7e86bSDan Gohman } 2748fe7e86bSDan Gohman assert(OnStack.pop_back_val() == nullptr && 2758fe7e86bSDan Gohman "The function entry block shouldn't actually be a loop header"); 2768fe7e86bSDan Gohman assert(OnStack.empty() && 2778fe7e86bSDan Gohman "Control flow stack pushes and pops should be balanced."); 278950a13cfSDan Gohman #endif 279950a13cfSDan Gohman } 280950a13cfSDan Gohman 281b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as 282b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized 283b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough 284b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any 285b3aa1ecaSDan Gohman /// explicit mentions. 28635e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred, 28735e4a289SDan Gohman MachineBasicBlock *MBB) { 288b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators()) 289b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands()) 290b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB) 291b3aa1ecaSDan Gohman return true; 292b3aa1ecaSDan Gohman return false; 293b3aa1ecaSDan Gohman } 294b3aa1ecaSDan Gohman 295ed0f1138SDan Gohman /// Test whether MI is a child of some other node in an expression tree. 296500d0469SDuncan P. N. Exon Smith static bool IsChild(const MachineInstr &MI, 297ed0f1138SDan Gohman const WebAssemblyFunctionInfo &MFI) { 298500d0469SDuncan P. N. Exon Smith if (MI.getNumOperands() == 0) 299ed0f1138SDan Gohman return false; 300500d0469SDuncan P. N. Exon Smith const MachineOperand &MO = MI.getOperand(0); 301ed0f1138SDan Gohman if (!MO.isReg() || MO.isImplicit() || !MO.isDef()) 302ed0f1138SDan Gohman return false; 303ed0f1138SDan Gohman unsigned Reg = MO.getReg(); 304ed0f1138SDan Gohman return TargetRegisterInfo::isVirtualRegister(Reg) && 305ed0f1138SDan Gohman MFI.isVRegStackified(Reg); 306ed0f1138SDan Gohman } 307ed0f1138SDan Gohman 30832807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed). 309*3a643e8dSDan Gohman static void PlaceBlockMarker( 310*3a643e8dSDan Gohman MachineBasicBlock &MBB, MachineFunction &MF, 3118fe7e86bSDan Gohman SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 312*3a643e8dSDan Gohman DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops, 31332807932SDan Gohman const WebAssemblyInstrInfo &TII, 3148fe7e86bSDan Gohman const MachineLoopInfo &MLI, 315ed0f1138SDan Gohman MachineDominatorTree &MDT, 316ed0f1138SDan Gohman WebAssemblyFunctionInfo &MFI) { 3178fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough 3188fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack, 3198fe7e86bSDan Gohman // which reduces overall stack height. 32032807932SDan Gohman MachineBasicBlock *Header = nullptr; 32132807932SDan Gohman bool IsBranchedTo = false; 32232807932SDan Gohman int MBBNumber = MBB.getNumber(); 32332807932SDan Gohman for (MachineBasicBlock *Pred : MBB.predecessors()) 32432807932SDan Gohman if (Pred->getNumber() < MBBNumber) { 32532807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 326b3aa1ecaSDan Gohman if (ExplicitlyBranchesTo(Pred, &MBB)) 32732807932SDan Gohman IsBranchedTo = true; 32832807932SDan Gohman } 32932807932SDan Gohman if (!Header) 33032807932SDan Gohman return; 33132807932SDan Gohman if (!IsBranchedTo) 33232807932SDan Gohman return; 33332807932SDan Gohman 3348fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 335ef0a45aaSBenjamin Kramer MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB)); 3368fe7e86bSDan Gohman 3378fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context, 3388fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested. 3398fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 3408fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 3418fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) { 3428fe7e86bSDan Gohman // Skip over an intervening scope. 343ef0a45aaSBenjamin Kramer I = std::next(MachineFunction::iterator(ScopeTop)); 3448fe7e86bSDan Gohman } else { 3458fe7e86bSDan Gohman // We found a scope level at an appropriate depth. 3468fe7e86bSDan Gohman Header = ScopeTop; 3478fe7e86bSDan Gohman break; 3488fe7e86bSDan Gohman } 3498fe7e86bSDan Gohman } 3508fe7e86bSDan Gohman } 3518fe7e86bSDan Gohman 3528fe7e86bSDan Gohman // Decide where in Header to put the BLOCK. 35332807932SDan Gohman MachineBasicBlock::iterator InsertPos; 35432807932SDan Gohman MachineLoop *HeaderLoop = MLI.getLoopFor(Header); 3558fe7e86bSDan Gohman if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) { 3568fe7e86bSDan Gohman // Header is the header of a loop that does not lexically contain MBB, so 357a187ab2aSDan Gohman // the BLOCK needs to be above the LOOP, after any END constructs. 35832807932SDan Gohman InsertPos = Header->begin(); 359*3a643e8dSDan Gohman while (InsertPos->getOpcode() == WebAssembly::END_BLOCK || 360*3a643e8dSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP) 361a187ab2aSDan Gohman ++InsertPos; 36232807932SDan Gohman } else { 3638887d1faSDan Gohman // Otherwise, insert the BLOCK as late in Header as we can, but before the 3648887d1faSDan Gohman // beginning of the local expression tree and any nested BLOCKs. 36532807932SDan Gohman InsertPos = Header->getFirstTerminator(); 366ef0a45aaSBenjamin Kramer while (InsertPos != Header->begin() && 367ef0a45aaSBenjamin Kramer IsChild(*std::prev(InsertPos), MFI) && 368ef0a45aaSBenjamin Kramer std::prev(InsertPos)->getOpcode() != WebAssembly::LOOP && 369ef0a45aaSBenjamin Kramer std::prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK && 370ef0a45aaSBenjamin Kramer std::prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP) 37132807932SDan Gohman --InsertPos; 37232807932SDan Gohman } 37332807932SDan Gohman 3748fe7e86bSDan Gohman // Add the BLOCK. 3751d68e80fSDan Gohman BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK)); 3761d68e80fSDan Gohman 3771d68e80fSDan Gohman // Mark the end of the block. 3781d68e80fSDan Gohman InsertPos = MBB.begin(); 3791d68e80fSDan Gohman while (InsertPos != MBB.end() && 380*3a643e8dSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP && 381*3a643e8dSDan Gohman LoopTops[&*InsertPos]->getNumber() >= Header->getNumber()) 3821d68e80fSDan Gohman ++InsertPos; 3831d68e80fSDan Gohman BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK)); 3848fe7e86bSDan Gohman 3858fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3868fe7e86bSDan Gohman int Number = MBB.getNumber(); 3878fe7e86bSDan Gohman if (!ScopeTops[Number] || 3888fe7e86bSDan Gohman ScopeTops[Number]->getNumber() > Header->getNumber()) 3898fe7e86bSDan Gohman ScopeTops[Number] = Header; 390950a13cfSDan Gohman } 391950a13cfSDan Gohman 3928fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 3931d68e80fSDan Gohman static void PlaceLoopMarker( 3941d68e80fSDan Gohman MachineBasicBlock &MBB, MachineFunction &MF, 3958fe7e86bSDan Gohman SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 3961d68e80fSDan Gohman DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops, 3971d68e80fSDan Gohman const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) { 3988fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 3998fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 4008fe7e86bSDan Gohman return; 4018fe7e86bSDan Gohman 4028fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 4038fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 4048fe7e86bSDan Gohman MachineBasicBlock *Bottom = LoopBottom(Loop); 405ef0a45aaSBenjamin Kramer auto Iter = std::next(MachineFunction::iterator(Bottom)); 406e3e4a5ffSDan Gohman if (Iter == MF.end()) { 407f6857223SDan Gohman MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 408f6857223SDan Gohman // Give it a fake predecessor so that AsmPrinter prints its label. 409f6857223SDan Gohman Label->addSuccessor(Label); 410f6857223SDan Gohman MF.push_back(Label); 411ef0a45aaSBenjamin Kramer Iter = std::next(MachineFunction::iterator(Bottom)); 412e3e4a5ffSDan Gohman } 4138fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 414f6857223SDan Gohman 4151d68e80fSDan Gohman // Mark the beginning of the loop (after the end of any existing loop that 4161d68e80fSDan Gohman // ends here). 4171d68e80fSDan Gohman auto InsertPos = MBB.begin(); 4181d68e80fSDan Gohman while (InsertPos != MBB.end() && 4191d68e80fSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP) 4201d68e80fSDan Gohman ++InsertPos; 4211d68e80fSDan Gohman BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP)); 4221d68e80fSDan Gohman 4231d68e80fSDan Gohman // Mark the end of the loop. 4241d68e80fSDan Gohman MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(), 4251d68e80fSDan Gohman TII.get(WebAssembly::END_LOOP)); 4261d68e80fSDan Gohman LoopTops[End] = &MBB; 4278fe7e86bSDan Gohman 4288fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 4298fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 430442bfcecSDan Gohman "With block sorting the outermost loop for a block should be first."); 4318fe7e86bSDan Gohman if (!ScopeTops[AfterLoop->getNumber()]) 4328fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()] = &MBB; 433e3e4a5ffSDan Gohman } 434950a13cfSDan Gohman 4351d68e80fSDan Gohman static unsigned 4361d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 4371d68e80fSDan Gohman const MachineBasicBlock *MBB) { 4381d68e80fSDan Gohman unsigned Depth = 0; 4391d68e80fSDan Gohman for (auto X : reverse(Stack)) { 4401d68e80fSDan Gohman if (X == MBB) 4411d68e80fSDan Gohman break; 4421d68e80fSDan Gohman ++Depth; 4431d68e80fSDan Gohman } 4441d68e80fSDan Gohman assert(Depth < Stack.size() && "Branch destination should be in scope"); 4451d68e80fSDan Gohman return Depth; 4461d68e80fSDan Gohman } 4471d68e80fSDan Gohman 4488fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places. 4498fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI, 4508fe7e86bSDan Gohman const WebAssemblyInstrInfo &TII, 451ed0f1138SDan Gohman MachineDominatorTree &MDT, 452ed0f1138SDan Gohman WebAssemblyFunctionInfo &MFI) { 4538fe7e86bSDan Gohman // For each block whose label represents the end of a scope, record the block 4548fe7e86bSDan Gohman // which holds the beginning of the scope. This will allow us to quickly skip 4558fe7e86bSDan Gohman // over scoped regions when walking blocks. We allocate one more than the 4568fe7e86bSDan Gohman // number of blocks in the function to accommodate for the possible fake block 4578fe7e86bSDan Gohman // we may insert at the end. 4588fe7e86bSDan Gohman SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1); 4598fe7e86bSDan Gohman 4601d68e80fSDan Gohman // For eacn LOOP_END, the corresponding LOOP. 4611d68e80fSDan Gohman DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops; 4621d68e80fSDan Gohman 4638fe7e86bSDan Gohman for (auto &MBB : MF) { 4648fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 4651d68e80fSDan Gohman PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI); 4668fe7e86bSDan Gohman 46732807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 468*3a643e8dSDan Gohman PlaceBlockMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI, MDT, MFI); 469950a13cfSDan Gohman } 470950a13cfSDan Gohman 4711d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 4721d68e80fSDan Gohman SmallVector<const MachineBasicBlock *, 8> Stack; 4731d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 4741d68e80fSDan Gohman for (auto &MI : reverse(MBB)) { 4751d68e80fSDan Gohman switch (MI.getOpcode()) { 4761d68e80fSDan Gohman case WebAssembly::BLOCK: 477*3a643e8dSDan Gohman assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= MBB.getNumber() && 4781d68e80fSDan Gohman "Block should be balanced"); 4791d68e80fSDan Gohman Stack.pop_back(); 4801d68e80fSDan Gohman break; 4811d68e80fSDan Gohman case WebAssembly::LOOP: 4821d68e80fSDan Gohman assert(Stack.back() == &MBB && "Loop top should be balanced"); 4831d68e80fSDan Gohman Stack.pop_back(); 4841d68e80fSDan Gohman break; 4851d68e80fSDan Gohman case WebAssembly::END_BLOCK: 4861d68e80fSDan Gohman Stack.push_back(&MBB); 4871d68e80fSDan Gohman break; 4881d68e80fSDan Gohman case WebAssembly::END_LOOP: 4891d68e80fSDan Gohman Stack.push_back(LoopTops[&MI]); 4901d68e80fSDan Gohman break; 4911d68e80fSDan Gohman default: 4921d68e80fSDan Gohman if (MI.isTerminator()) { 4931d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 4941d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 4951d68e80fSDan Gohman while (MI.getNumOperands() > 0) 4961d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 4971d68e80fSDan Gohman for (auto MO : Ops) { 4981d68e80fSDan Gohman if (MO.isMBB()) 4991d68e80fSDan Gohman MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB())); 5001d68e80fSDan Gohman MI.addOperand(MF, MO); 50132807932SDan Gohman } 5021d68e80fSDan Gohman } 5031d68e80fSDan Gohman break; 5041d68e80fSDan Gohman } 5051d68e80fSDan Gohman } 5061d68e80fSDan Gohman } 5071d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 5081d68e80fSDan Gohman } 50932807932SDan Gohman 510950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 511950a13cfSDan Gohman DEBUG(dbgs() << "********** CFG Stackifying **********\n" 512950a13cfSDan Gohman "********** Function: " 513950a13cfSDan Gohman << MF.getName() << '\n'); 514950a13cfSDan Gohman 515950a13cfSDan Gohman const auto &MLI = getAnalysis<MachineLoopInfo>(); 51632807932SDan Gohman auto &MDT = getAnalysis<MachineDominatorTree>(); 517e040533eSDan Gohman // Liveness is not tracked for VALUE_STACK physreg. 518950a13cfSDan Gohman const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 519ed0f1138SDan Gohman WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 5209c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness(); 521950a13cfSDan Gohman 522442bfcecSDan Gohman // Sort the blocks, with contiguous loops. 523442bfcecSDan Gohman SortBlocks(MF, MLI, MDT); 524950a13cfSDan Gohman 525950a13cfSDan Gohman // Place the BLOCK and LOOP markers to indicate the beginnings of scopes. 526ed0f1138SDan Gohman PlaceMarkers(MF, MLI, TII, MDT, MFI); 52732807932SDan Gohman 528950a13cfSDan Gohman return true; 529950a13cfSDan Gohman } 530