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" 30*4fc4e42dSDan Gohman #include "WebAssemblyUtilities.h" 31442bfcecSDan Gohman #include "llvm/ADT/PriorityQueue.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" 379c3bf318SDerek 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 { 47117296c0SMehdi Amini StringRef getPassName() const override { return "WebAssembly CFG Stackify"; } 48950a13cfSDan Gohman 49950a13cfSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override { 50950a13cfSDan Gohman AU.setPreservesCFG(); 5132807932SDan Gohman AU.addRequired<MachineDominatorTree>(); 5232807932SDan Gohman AU.addPreserved<MachineDominatorTree>(); 53950a13cfSDan Gohman AU.addRequired<MachineLoopInfo>(); 54950a13cfSDan Gohman AU.addPreserved<MachineLoopInfo>(); 55950a13cfSDan Gohman MachineFunctionPass::getAnalysisUsage(AU); 56950a13cfSDan Gohman } 57950a13cfSDan Gohman 58950a13cfSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override; 59950a13cfSDan Gohman 60950a13cfSDan Gohman public: 61950a13cfSDan Gohman static char ID; // Pass identification, replacement for typeid 62950a13cfSDan Gohman WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 63950a13cfSDan Gohman }; 64950a13cfSDan Gohman } // end anonymous namespace 65950a13cfSDan Gohman 66950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0; 67950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() { 68950a13cfSDan Gohman return new WebAssemblyCFGStackify(); 69950a13cfSDan Gohman } 70950a13cfSDan Gohman 718fe7e86bSDan Gohman /// Return the "bottom" block of a loop. This differs from 728fe7e86bSDan Gohman /// MachineLoop::getBottomBlock in that it works even if the loop is 738fe7e86bSDan Gohman /// discontiguous. 748fe7e86bSDan Gohman static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) { 758fe7e86bSDan Gohman MachineBasicBlock *Bottom = Loop->getHeader(); 768fe7e86bSDan Gohman for (MachineBasicBlock *MBB : Loop->blocks()) 778fe7e86bSDan Gohman if (MBB->getNumber() > Bottom->getNumber()) 788fe7e86bSDan Gohman Bottom = MBB; 798fe7e86bSDan Gohman return Bottom; 808fe7e86bSDan Gohman } 818fe7e86bSDan Gohman 82442bfcecSDan Gohman static void MaybeUpdateTerminator(MachineBasicBlock *MBB) { 83442bfcecSDan Gohman #ifndef NDEBUG 84442bfcecSDan Gohman bool AnyBarrier = false; 85442bfcecSDan Gohman #endif 86442bfcecSDan Gohman bool AllAnalyzable = true; 87442bfcecSDan Gohman for (const MachineInstr &Term : MBB->terminators()) { 88442bfcecSDan Gohman #ifndef NDEBUG 89442bfcecSDan Gohman AnyBarrier |= Term.isBarrier(); 90442bfcecSDan Gohman #endif 91442bfcecSDan Gohman AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch(); 92442bfcecSDan Gohman } 93442bfcecSDan Gohman assert((AnyBarrier || AllAnalyzable) && 94442bfcecSDan Gohman "AnalyzeBranch needs to analyze any block with a fallthrough"); 95442bfcecSDan Gohman if (AllAnalyzable) 96442bfcecSDan Gohman MBB->updateTerminator(); 97442bfcecSDan Gohman } 98950a13cfSDan Gohman 99442bfcecSDan Gohman namespace { 100442bfcecSDan Gohman /// Sort blocks by their number. 101442bfcecSDan Gohman struct CompareBlockNumbers { 102442bfcecSDan Gohman bool operator()(const MachineBasicBlock *A, 103442bfcecSDan Gohman const MachineBasicBlock *B) const { 104442bfcecSDan Gohman return A->getNumber() > B->getNumber(); 105442bfcecSDan Gohman } 106442bfcecSDan Gohman }; 107442bfcecSDan Gohman /// Sort blocks by their number in the opposite order.. 108442bfcecSDan Gohman struct CompareBlockNumbersBackwards { 109442bfcecSDan Gohman bool operator()(const MachineBasicBlock *A, 110442bfcecSDan Gohman const MachineBasicBlock *B) const { 111442bfcecSDan Gohman return A->getNumber() < B->getNumber(); 112442bfcecSDan Gohman } 113442bfcecSDan Gohman }; 114442bfcecSDan Gohman /// Bookkeeping for a loop to help ensure that we don't mix blocks not dominated 115442bfcecSDan Gohman /// by the loop header among the loop's blocks. 116442bfcecSDan Gohman struct Entry { 117442bfcecSDan Gohman const MachineLoop *Loop; 118442bfcecSDan Gohman unsigned NumBlocksLeft; 119950a13cfSDan Gohman 120442bfcecSDan Gohman /// List of blocks not dominated by Loop's header that are deferred until 121442bfcecSDan Gohman /// after all of Loop's blocks have been seen. 122442bfcecSDan Gohman std::vector<MachineBasicBlock *> Deferred; 123442bfcecSDan Gohman 124442bfcecSDan Gohman explicit Entry(const MachineLoop *L) 125442bfcecSDan Gohman : Loop(L), NumBlocksLeft(L->getNumBlocks()) {} 126442bfcecSDan Gohman }; 127442bfcecSDan Gohman } 128442bfcecSDan Gohman 129442bfcecSDan Gohman /// Sort the blocks, taking special care to make sure that loops are not 130442bfcecSDan Gohman /// interrupted by blocks not dominated by their header. 131442bfcecSDan Gohman /// TODO: There are many opportunities for improving the heuristics here. 132442bfcecSDan Gohman /// Explore them. 133442bfcecSDan Gohman static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI, 134442bfcecSDan Gohman const MachineDominatorTree &MDT) { 135442bfcecSDan Gohman // Prepare for a topological sort: Record the number of predecessors each 136442bfcecSDan Gohman // block has, ignoring loop backedges. 137442bfcecSDan Gohman MF.RenumberBlocks(); 138442bfcecSDan Gohman SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0); 139442bfcecSDan Gohman for (MachineBasicBlock &MBB : MF) { 140442bfcecSDan Gohman unsigned N = MBB.pred_size(); 141442bfcecSDan Gohman if (MachineLoop *L = MLI.getLoopFor(&MBB)) 142442bfcecSDan Gohman if (L->getHeader() == &MBB) 143442bfcecSDan Gohman for (const MachineBasicBlock *Pred : MBB.predecessors()) 144442bfcecSDan Gohman if (L->contains(Pred)) 145442bfcecSDan Gohman --N; 146442bfcecSDan Gohman NumPredsLeft[MBB.getNumber()] = N; 147442bfcecSDan Gohman } 148442bfcecSDan Gohman 149442bfcecSDan Gohman // Topological sort the CFG, with additional constraints: 150442bfcecSDan Gohman // - Between a loop header and the last block in the loop, there can be 151442bfcecSDan Gohman // no blocks not dominated by the loop header. 152442bfcecSDan Gohman // - It's desirable to preserve the original block order when possible. 153442bfcecSDan Gohman // We use two ready lists; Preferred and Ready. Preferred has recently 154442bfcecSDan Gohman // processed sucessors, to help preserve block sequences from the original 155442bfcecSDan Gohman // order. Ready has the remaining ready blocks. 156442bfcecSDan Gohman PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>, 157442bfcecSDan Gohman CompareBlockNumbers> 158442bfcecSDan Gohman Preferred; 159442bfcecSDan Gohman PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>, 160442bfcecSDan Gohman CompareBlockNumbersBackwards> 161442bfcecSDan Gohman Ready; 162442bfcecSDan Gohman SmallVector<Entry, 4> Loops; 163442bfcecSDan Gohman for (MachineBasicBlock *MBB = &MF.front();;) { 164442bfcecSDan Gohman const MachineLoop *L = MLI.getLoopFor(MBB); 165442bfcecSDan Gohman if (L) { 166442bfcecSDan Gohman // If MBB is a loop header, add it to the active loop list. We can't put 167442bfcecSDan Gohman // any blocks that it doesn't dominate until we see the end of the loop. 168442bfcecSDan Gohman if (L->getHeader() == MBB) 169442bfcecSDan Gohman Loops.push_back(Entry(L)); 170442bfcecSDan Gohman // For each active loop the block is in, decrement the count. If MBB is 171442bfcecSDan Gohman // the last block in an active loop, take it off the list and pick up any 172442bfcecSDan Gohman // blocks deferred because the header didn't dominate them. 173442bfcecSDan Gohman for (Entry &E : Loops) 174442bfcecSDan Gohman if (E.Loop->contains(MBB) && --E.NumBlocksLeft == 0) 175442bfcecSDan Gohman for (auto DeferredBlock : E.Deferred) 176442bfcecSDan Gohman Ready.push(DeferredBlock); 177442bfcecSDan Gohman while (!Loops.empty() && Loops.back().NumBlocksLeft == 0) 178442bfcecSDan Gohman Loops.pop_back(); 179442bfcecSDan Gohman } 180442bfcecSDan Gohman // The main topological sort logic. 181442bfcecSDan Gohman for (MachineBasicBlock *Succ : MBB->successors()) { 182442bfcecSDan Gohman // Ignore backedges. 183442bfcecSDan Gohman if (MachineLoop *SuccL = MLI.getLoopFor(Succ)) 184442bfcecSDan Gohman if (SuccL->getHeader() == Succ && SuccL->contains(MBB)) 185442bfcecSDan Gohman continue; 186442bfcecSDan Gohman // Decrement the predecessor count. If it's now zero, it's ready. 187442bfcecSDan Gohman if (--NumPredsLeft[Succ->getNumber()] == 0) 188442bfcecSDan Gohman Preferred.push(Succ); 189442bfcecSDan Gohman } 190442bfcecSDan Gohman // Determine the block to follow MBB. First try to find a preferred block, 191442bfcecSDan Gohman // to preserve the original block order when possible. 192442bfcecSDan Gohman MachineBasicBlock *Next = nullptr; 193442bfcecSDan Gohman while (!Preferred.empty()) { 194442bfcecSDan Gohman Next = Preferred.top(); 195442bfcecSDan Gohman Preferred.pop(); 196442bfcecSDan Gohman // If X isn't dominated by the top active loop header, defer it until that 197442bfcecSDan Gohman // loop is done. 198442bfcecSDan Gohman if (!Loops.empty() && 199442bfcecSDan Gohman !MDT.dominates(Loops.back().Loop->getHeader(), Next)) { 200442bfcecSDan Gohman Loops.back().Deferred.push_back(Next); 201442bfcecSDan Gohman Next = nullptr; 202950a13cfSDan Gohman continue; 203950a13cfSDan Gohman } 204442bfcecSDan Gohman // If Next was originally ordered before MBB, and it isn't because it was 205442bfcecSDan Gohman // loop-rotated above the header, it's not preferred. 206442bfcecSDan Gohman if (Next->getNumber() < MBB->getNumber() && 207442bfcecSDan Gohman (!L || !L->contains(Next) || 208442bfcecSDan Gohman L->getHeader()->getNumber() < Next->getNumber())) { 209442bfcecSDan Gohman Ready.push(Next); 210442bfcecSDan Gohman Next = nullptr; 211442bfcecSDan Gohman continue; 212442bfcecSDan Gohman } 213950a13cfSDan Gohman break; 214950a13cfSDan Gohman } 215442bfcecSDan Gohman // If we didn't find a suitable block in the Preferred list, check the 216442bfcecSDan Gohman // general Ready list. 217442bfcecSDan Gohman if (!Next) { 218442bfcecSDan Gohman // If there are no more blocks to process, we're done. 219442bfcecSDan Gohman if (Ready.empty()) { 220442bfcecSDan Gohman MaybeUpdateTerminator(MBB); 221442bfcecSDan Gohman break; 222442bfcecSDan Gohman } 223442bfcecSDan Gohman for (;;) { 224442bfcecSDan Gohman Next = Ready.top(); 225442bfcecSDan Gohman Ready.pop(); 226442bfcecSDan Gohman // If Next isn't dominated by the top active loop header, defer it until 227442bfcecSDan Gohman // that loop is done. 228442bfcecSDan Gohman if (!Loops.empty() && 229442bfcecSDan Gohman !MDT.dominates(Loops.back().Loop->getHeader(), Next)) { 230442bfcecSDan Gohman Loops.back().Deferred.push_back(Next); 231442bfcecSDan Gohman continue; 232442bfcecSDan Gohman } 233442bfcecSDan Gohman break; 234442bfcecSDan Gohman } 235442bfcecSDan Gohman } 236442bfcecSDan Gohman // Move the next block into place and iterate. 237442bfcecSDan Gohman Next->moveAfter(MBB); 238442bfcecSDan Gohman MaybeUpdateTerminator(MBB); 239442bfcecSDan Gohman MBB = Next; 240442bfcecSDan Gohman } 241442bfcecSDan Gohman assert(Loops.empty() && "Active loop list not finished"); 242950a13cfSDan Gohman MF.RenumberBlocks(); 243950a13cfSDan Gohman 244950a13cfSDan Gohman #ifndef NDEBUG 2458fe7e86bSDan Gohman SmallSetVector<MachineLoop *, 8> OnStack; 2468fe7e86bSDan Gohman 2478fe7e86bSDan Gohman // Insert a sentinel representing the degenerate loop that starts at the 2488fe7e86bSDan Gohman // function entry block and includes the entire function as a "loop" that 2498fe7e86bSDan Gohman // executes once. 2508fe7e86bSDan Gohman OnStack.insert(nullptr); 2518fe7e86bSDan Gohman 2528fe7e86bSDan Gohman for (auto &MBB : MF) { 2538fe7e86bSDan Gohman assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative."); 2548fe7e86bSDan Gohman 2558fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 2568fe7e86bSDan Gohman if (Loop && &MBB == Loop->getHeader()) { 2578fe7e86bSDan Gohman // Loop header. The loop predecessor should be sorted above, and the other 2588fe7e86bSDan Gohman // predecessors should be backedges below. 2598fe7e86bSDan Gohman for (auto Pred : MBB.predecessors()) 2608fe7e86bSDan Gohman assert( 2618fe7e86bSDan Gohman (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) && 2628fe7e86bSDan Gohman "Loop header predecessors must be loop predecessors or backedges"); 2638fe7e86bSDan Gohman assert(OnStack.insert(Loop) && "Loops should be declared at most once."); 26432807932SDan Gohman } else { 2658fe7e86bSDan Gohman // Not a loop header. All predecessors should be sorted above. 266950a13cfSDan Gohman for (auto Pred : MBB.predecessors()) 267950a13cfSDan Gohman assert(Pred->getNumber() < MBB.getNumber() && 2688fe7e86bSDan Gohman "Non-loop-header predecessors should be topologically sorted"); 2698fe7e86bSDan Gohman assert(OnStack.count(MLI.getLoopFor(&MBB)) && 2708fe7e86bSDan Gohman "Blocks must be nested in their loops"); 271950a13cfSDan Gohman } 2728fe7e86bSDan Gohman while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back())) 2738fe7e86bSDan Gohman OnStack.pop_back(); 2748fe7e86bSDan Gohman } 2758fe7e86bSDan Gohman assert(OnStack.pop_back_val() == nullptr && 2768fe7e86bSDan Gohman "The function entry block shouldn't actually be a loop header"); 2778fe7e86bSDan Gohman assert(OnStack.empty() && 2788fe7e86bSDan Gohman "Control flow stack pushes and pops should be balanced."); 279950a13cfSDan Gohman #endif 280950a13cfSDan Gohman } 281950a13cfSDan Gohman 282b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as 283b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized 284b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough 285b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any 286b3aa1ecaSDan Gohman /// explicit mentions. 28735e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred, 28835e4a289SDan Gohman MachineBasicBlock *MBB) { 289b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators()) 290b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands()) 291b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB) 292b3aa1ecaSDan Gohman return true; 293b3aa1ecaSDan Gohman return false; 294b3aa1ecaSDan Gohman } 295b3aa1ecaSDan Gohman 29632807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed). 2973a643e8dSDan Gohman static void PlaceBlockMarker( 2983a643e8dSDan Gohman MachineBasicBlock &MBB, MachineFunction &MF, 2998fe7e86bSDan Gohman SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 3002726b88cSDan Gohman DenseMap<const MachineInstr *, MachineInstr *> &BlockTops, 3012726b88cSDan Gohman DenseMap<const MachineInstr *, MachineInstr *> &LoopTops, 30232807932SDan Gohman const WebAssemblyInstrInfo &TII, 3038fe7e86bSDan Gohman const MachineLoopInfo &MLI, 304ed0f1138SDan Gohman MachineDominatorTree &MDT, 305ed0f1138SDan Gohman WebAssemblyFunctionInfo &MFI) { 3068fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough 3078fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack, 3088fe7e86bSDan Gohman // which reduces overall stack height. 30932807932SDan Gohman MachineBasicBlock *Header = nullptr; 31032807932SDan Gohman bool IsBranchedTo = false; 31132807932SDan Gohman int MBBNumber = MBB.getNumber(); 31232807932SDan Gohman for (MachineBasicBlock *Pred : MBB.predecessors()) 31332807932SDan Gohman if (Pred->getNumber() < MBBNumber) { 31432807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 315b3aa1ecaSDan Gohman if (ExplicitlyBranchesTo(Pred, &MBB)) 31632807932SDan Gohman IsBranchedTo = true; 31732807932SDan Gohman } 31832807932SDan Gohman if (!Header) 31932807932SDan Gohman return; 32032807932SDan Gohman if (!IsBranchedTo) 32132807932SDan Gohman return; 32232807932SDan Gohman 3238fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 324ef0a45aaSBenjamin Kramer MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB)); 3258fe7e86bSDan Gohman 3268fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context, 3278fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested. 3288fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 3298fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 3308fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) { 3318fe7e86bSDan Gohman // Skip over an intervening scope. 332ef0a45aaSBenjamin Kramer I = std::next(MachineFunction::iterator(ScopeTop)); 3338fe7e86bSDan Gohman } else { 3348fe7e86bSDan Gohman // We found a scope level at an appropriate depth. 3358fe7e86bSDan Gohman Header = ScopeTop; 3368fe7e86bSDan Gohman break; 3378fe7e86bSDan Gohman } 3388fe7e86bSDan Gohman } 3398fe7e86bSDan Gohman } 3408fe7e86bSDan Gohman 3418fe7e86bSDan Gohman // Decide where in Header to put the BLOCK. 34232807932SDan Gohman MachineBasicBlock::iterator InsertPos; 34332807932SDan Gohman MachineLoop *HeaderLoop = MLI.getLoopFor(Header); 3448fe7e86bSDan Gohman if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) { 3458fe7e86bSDan Gohman // Header is the header of a loop that does not lexically contain MBB, so 346a187ab2aSDan Gohman // the BLOCK needs to be above the LOOP, after any END constructs. 34732807932SDan Gohman InsertPos = Header->begin(); 3483a643e8dSDan Gohman while (InsertPos->getOpcode() == WebAssembly::END_BLOCK || 3493a643e8dSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP) 350a187ab2aSDan Gohman ++InsertPos; 35132807932SDan Gohman } else { 3528887d1faSDan Gohman // Otherwise, insert the BLOCK as late in Header as we can, but before the 3538887d1faSDan Gohman // beginning of the local expression tree and any nested BLOCKs. 35432807932SDan Gohman InsertPos = Header->getFirstTerminator(); 355ef0a45aaSBenjamin Kramer while (InsertPos != Header->begin() && 356*4fc4e42dSDan Gohman WebAssembly::isChild(*std::prev(InsertPos), MFI) && 357ef0a45aaSBenjamin Kramer std::prev(InsertPos)->getOpcode() != WebAssembly::LOOP && 358ef0a45aaSBenjamin Kramer std::prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK && 359ef0a45aaSBenjamin Kramer std::prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP) 36032807932SDan Gohman --InsertPos; 36132807932SDan Gohman } 36232807932SDan Gohman 3638fe7e86bSDan Gohman // Add the BLOCK. 3642726b88cSDan Gohman MachineInstr *Begin = BuildMI(*Header, InsertPos, DebugLoc(), 3652726b88cSDan Gohman TII.get(WebAssembly::BLOCK)) 366*4fc4e42dSDan Gohman .addImm(int64_t(WebAssembly::ExprType::Void)); 3671d68e80fSDan Gohman 3681d68e80fSDan Gohman // Mark the end of the block. 3691d68e80fSDan Gohman InsertPos = MBB.begin(); 3701d68e80fSDan Gohman while (InsertPos != MBB.end() && 3713a643e8dSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP && 3722726b88cSDan Gohman LoopTops[&*InsertPos]->getParent()->getNumber() >= Header->getNumber()) 3731d68e80fSDan Gohman ++InsertPos; 3742726b88cSDan Gohman MachineInstr *End = BuildMI(MBB, InsertPos, DebugLoc(), 3752726b88cSDan Gohman TII.get(WebAssembly::END_BLOCK)); 3762726b88cSDan Gohman BlockTops[End] = Begin; 3778fe7e86bSDan Gohman 3788fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3798fe7e86bSDan Gohman int Number = MBB.getNumber(); 3808fe7e86bSDan Gohman if (!ScopeTops[Number] || 3818fe7e86bSDan Gohman ScopeTops[Number]->getNumber() > Header->getNumber()) 3828fe7e86bSDan Gohman ScopeTops[Number] = Header; 383950a13cfSDan Gohman } 384950a13cfSDan Gohman 3858fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 3861d68e80fSDan Gohman static void PlaceLoopMarker( 3871d68e80fSDan Gohman MachineBasicBlock &MBB, MachineFunction &MF, 3888fe7e86bSDan Gohman SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 3892726b88cSDan Gohman DenseMap<const MachineInstr *, MachineInstr *> &LoopTops, 3901d68e80fSDan Gohman const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) { 3918fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 3928fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 3938fe7e86bSDan Gohman return; 3948fe7e86bSDan Gohman 3958fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 3968fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 3978fe7e86bSDan Gohman MachineBasicBlock *Bottom = LoopBottom(Loop); 398ef0a45aaSBenjamin Kramer auto Iter = std::next(MachineFunction::iterator(Bottom)); 399e3e4a5ffSDan Gohman if (Iter == MF.end()) { 400f6857223SDan Gohman MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 401f6857223SDan Gohman // Give it a fake predecessor so that AsmPrinter prints its label. 402f6857223SDan Gohman Label->addSuccessor(Label); 403f6857223SDan Gohman MF.push_back(Label); 404ef0a45aaSBenjamin Kramer Iter = std::next(MachineFunction::iterator(Bottom)); 405e3e4a5ffSDan Gohman } 4068fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 407f6857223SDan Gohman 4081d68e80fSDan Gohman // Mark the beginning of the loop (after the end of any existing loop that 4091d68e80fSDan Gohman // ends here). 4101d68e80fSDan Gohman auto InsertPos = MBB.begin(); 4111d68e80fSDan Gohman while (InsertPos != MBB.end() && 4121d68e80fSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP) 4131d68e80fSDan Gohman ++InsertPos; 4142726b88cSDan Gohman MachineInstr *Begin = BuildMI(MBB, InsertPos, DebugLoc(), 4152726b88cSDan Gohman TII.get(WebAssembly::LOOP)) 416*4fc4e42dSDan Gohman .addImm(int64_t(WebAssembly::ExprType::Void)); 4171d68e80fSDan Gohman 4181d68e80fSDan Gohman // Mark the end of the loop. 4191d68e80fSDan Gohman MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(), 4201d68e80fSDan Gohman TII.get(WebAssembly::END_LOOP)); 4212726b88cSDan Gohman LoopTops[End] = Begin; 4228fe7e86bSDan Gohman 4238fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 4248fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 425442bfcecSDan Gohman "With block sorting the outermost loop for a block should be first."); 4268fe7e86bSDan Gohman if (!ScopeTops[AfterLoop->getNumber()]) 4278fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()] = &MBB; 428e3e4a5ffSDan Gohman } 429950a13cfSDan Gohman 4301d68e80fSDan Gohman static unsigned 4311d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 4321d68e80fSDan Gohman const MachineBasicBlock *MBB) { 4331d68e80fSDan Gohman unsigned Depth = 0; 4341d68e80fSDan Gohman for (auto X : reverse(Stack)) { 4351d68e80fSDan Gohman if (X == MBB) 4361d68e80fSDan Gohman break; 4371d68e80fSDan Gohman ++Depth; 4381d68e80fSDan Gohman } 4391d68e80fSDan Gohman assert(Depth < Stack.size() && "Branch destination should be in scope"); 4401d68e80fSDan Gohman return Depth; 4411d68e80fSDan Gohman } 4421d68e80fSDan Gohman 4432726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable, 4442726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar, 4452726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of 4462726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks 4472726b88cSDan Gohman /// that end at the function end need to have a return type signature that 4482726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function 4492726b88cSDan Gohman /// checks for such cases and fixes up the signatures. 4502726b88cSDan Gohman static void FixEndsAtEndOfFunction( 4512726b88cSDan Gohman MachineFunction &MF, 4522726b88cSDan Gohman const WebAssemblyFunctionInfo &MFI, 4532726b88cSDan Gohman DenseMap<const MachineInstr *, MachineInstr *> &BlockTops, 4542726b88cSDan Gohman DenseMap<const MachineInstr *, MachineInstr *> &LoopTops) { 4552726b88cSDan Gohman assert(MFI.getResults().size() <= 1); 4562726b88cSDan Gohman 4572726b88cSDan Gohman if (MFI.getResults().empty()) 4582726b88cSDan Gohman return; 4592726b88cSDan Gohman 4602726b88cSDan Gohman WebAssembly::ExprType retType; 4612726b88cSDan Gohman switch (MFI.getResults().front().SimpleTy) { 462*4fc4e42dSDan Gohman case MVT::i32: retType = WebAssembly::ExprType::I32; break; 463*4fc4e42dSDan Gohman case MVT::i64: retType = WebAssembly::ExprType::I64; break; 464*4fc4e42dSDan Gohman case MVT::f32: retType = WebAssembly::ExprType::F32; break; 465*4fc4e42dSDan Gohman case MVT::f64: retType = WebAssembly::ExprType::F64; break; 466*4fc4e42dSDan Gohman case MVT::v16i8: retType = WebAssembly::ExprType::I8x16; break; 467*4fc4e42dSDan Gohman case MVT::v8i16: retType = WebAssembly::ExprType::I16x8; break; 468*4fc4e42dSDan Gohman case MVT::v4i32: retType = WebAssembly::ExprType::I32x4; break; 469*4fc4e42dSDan Gohman case MVT::v2i64: retType = WebAssembly::ExprType::I64x2; break; 470*4fc4e42dSDan Gohman case MVT::v4f32: retType = WebAssembly::ExprType::F32x4; break; 471*4fc4e42dSDan Gohman case MVT::v2f64: retType = WebAssembly::ExprType::F64x2; break; 4722726b88cSDan Gohman default: llvm_unreachable("unexpected return type"); 4732726b88cSDan Gohman } 4742726b88cSDan Gohman 4752726b88cSDan Gohman for (MachineBasicBlock &MBB : reverse(MF)) { 4762726b88cSDan Gohman for (MachineInstr &MI : reverse(MBB)) { 4772726b88cSDan Gohman if (MI.isPosition() || MI.isDebugValue()) 4782726b88cSDan Gohman continue; 4792726b88cSDan Gohman if (MI.getOpcode() == WebAssembly::END_BLOCK) { 4802726b88cSDan Gohman BlockTops[&MI]->getOperand(0).setImm(int32_t(retType)); 4812726b88cSDan Gohman continue; 4822726b88cSDan Gohman } 4832726b88cSDan Gohman if (MI.getOpcode() == WebAssembly::END_LOOP) { 4842726b88cSDan Gohman LoopTops[&MI]->getOperand(0).setImm(int32_t(retType)); 4852726b88cSDan Gohman continue; 4862726b88cSDan Gohman } 4872726b88cSDan Gohman // Something other than an `end`. We're done. 4882726b88cSDan Gohman return; 4892726b88cSDan Gohman } 4902726b88cSDan Gohman } 4912726b88cSDan Gohman } 4922726b88cSDan Gohman 4938fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places. 4948fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI, 4958fe7e86bSDan Gohman const WebAssemblyInstrInfo &TII, 496ed0f1138SDan Gohman MachineDominatorTree &MDT, 497ed0f1138SDan Gohman WebAssemblyFunctionInfo &MFI) { 4988fe7e86bSDan Gohman // For each block whose label represents the end of a scope, record the block 4998fe7e86bSDan Gohman // which holds the beginning of the scope. This will allow us to quickly skip 5008fe7e86bSDan Gohman // over scoped regions when walking blocks. We allocate one more than the 5018fe7e86bSDan Gohman // number of blocks in the function to accommodate for the possible fake block 5028fe7e86bSDan Gohman // we may insert at the end. 5038fe7e86bSDan Gohman SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1); 5048fe7e86bSDan Gohman 5052726b88cSDan Gohman // For each LOOP_END, the corresponding LOOP. 5062726b88cSDan Gohman DenseMap<const MachineInstr *, MachineInstr *> LoopTops; 5072726b88cSDan Gohman 5082726b88cSDan Gohman // For each END_BLOCK, the corresponding BLOCK. 5092726b88cSDan Gohman DenseMap<const MachineInstr *, MachineInstr *> BlockTops; 5101d68e80fSDan Gohman 5118fe7e86bSDan Gohman for (auto &MBB : MF) { 5128fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 5131d68e80fSDan Gohman PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI); 5148fe7e86bSDan Gohman 51532807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 5162726b88cSDan Gohman PlaceBlockMarker(MBB, MF, ScopeTops, BlockTops, LoopTops, TII, MLI, MDT, MFI); 517950a13cfSDan Gohman } 518950a13cfSDan Gohman 5191d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 5201d68e80fSDan Gohman SmallVector<const MachineBasicBlock *, 8> Stack; 5211d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 5221d68e80fSDan Gohman for (auto &MI : reverse(MBB)) { 5231d68e80fSDan Gohman switch (MI.getOpcode()) { 5241d68e80fSDan Gohman case WebAssembly::BLOCK: 5253a643e8dSDan Gohman assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= MBB.getNumber() && 5261d68e80fSDan Gohman "Block should be balanced"); 5271d68e80fSDan Gohman Stack.pop_back(); 5281d68e80fSDan Gohman break; 5291d68e80fSDan Gohman case WebAssembly::LOOP: 5301d68e80fSDan Gohman assert(Stack.back() == &MBB && "Loop top should be balanced"); 5311d68e80fSDan Gohman Stack.pop_back(); 5321d68e80fSDan Gohman break; 5331d68e80fSDan Gohman case WebAssembly::END_BLOCK: 5341d68e80fSDan Gohman Stack.push_back(&MBB); 5351d68e80fSDan Gohman break; 5361d68e80fSDan Gohman case WebAssembly::END_LOOP: 5372726b88cSDan Gohman Stack.push_back(LoopTops[&MI]->getParent()); 5381d68e80fSDan Gohman break; 5391d68e80fSDan Gohman default: 5401d68e80fSDan Gohman if (MI.isTerminator()) { 5411d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 5421d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 5431d68e80fSDan Gohman while (MI.getNumOperands() > 0) 5441d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 5451d68e80fSDan Gohman for (auto MO : Ops) { 5461d68e80fSDan Gohman if (MO.isMBB()) 5471d68e80fSDan Gohman MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB())); 5481d68e80fSDan Gohman MI.addOperand(MF, MO); 54932807932SDan Gohman } 5501d68e80fSDan Gohman } 5511d68e80fSDan Gohman break; 5521d68e80fSDan Gohman } 5531d68e80fSDan Gohman } 5541d68e80fSDan Gohman } 5551d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 5562726b88cSDan Gohman 5572726b88cSDan Gohman // Fix up block/loop signatures at the end of the function to conform to 5582726b88cSDan Gohman // WebAssembly's rules. 5592726b88cSDan Gohman FixEndsAtEndOfFunction(MF, MFI, BlockTops, LoopTops); 5601d68e80fSDan Gohman } 56132807932SDan Gohman 562950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 563950a13cfSDan Gohman DEBUG(dbgs() << "********** CFG Stackifying **********\n" 564950a13cfSDan Gohman "********** Function: " 565950a13cfSDan Gohman << MF.getName() << '\n'); 566950a13cfSDan Gohman 567950a13cfSDan Gohman const auto &MLI = getAnalysis<MachineLoopInfo>(); 56832807932SDan Gohman auto &MDT = getAnalysis<MachineDominatorTree>(); 569e040533eSDan Gohman // Liveness is not tracked for VALUE_STACK physreg. 570950a13cfSDan Gohman const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 571ed0f1138SDan Gohman WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 5729c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness(); 573950a13cfSDan Gohman 574442bfcecSDan Gohman // Sort the blocks, with contiguous loops. 575442bfcecSDan Gohman SortBlocks(MF, MLI, MDT); 576950a13cfSDan Gohman 577950a13cfSDan Gohman // Place the BLOCK and LOOP markers to indicate the beginnings of scopes. 578ed0f1138SDan Gohman PlaceMarkers(MF, MLI, TII, MDT, MFI); 57932807932SDan Gohman 580950a13cfSDan Gohman return true; 581950a13cfSDan Gohman } 582