10b57cec5SDimitry Andric //===-- WebAssemblyCFGSort.cpp - CFG Sorting ------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric ///
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// This file implements a CFG sorting pass.
110b57cec5SDimitry Andric ///
120b57cec5SDimitry Andric /// This pass reorders the blocks in a function to put them into topological
130b57cec5SDimitry Andric /// order, ignoring loop backedges, and without any loop or exception being
140b57cec5SDimitry Andric /// interrupted by a block not dominated by the its header, with special care
150b57cec5SDimitry Andric /// to keep the order as similar as possible to the original order.
160b57cec5SDimitry Andric ///
170b57cec5SDimitry Andric ////===----------------------------------------------------------------------===//
180b57cec5SDimitry Andric 
190b57cec5SDimitry Andric #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
200b57cec5SDimitry Andric #include "WebAssembly.h"
210b57cec5SDimitry Andric #include "WebAssemblyExceptionInfo.h"
22e8d8bef9SDimitry Andric #include "WebAssemblySortRegion.h"
230b57cec5SDimitry Andric #include "WebAssemblySubtarget.h"
24*c9157d92SDimitry Andric #include "WebAssemblyUtilities.h"
250b57cec5SDimitry Andric #include "llvm/ADT/PriorityQueue.h"
260b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
32fe6060f1SDimitry Andric #include "llvm/CodeGen/WasmEHFuncInfo.h"
330b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
340b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
350b57cec5SDimitry Andric using namespace llvm;
36e8d8bef9SDimitry Andric using WebAssembly::SortRegion;
37e8d8bef9SDimitry Andric using WebAssembly::SortRegionInfo;
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric #define DEBUG_TYPE "wasm-cfg-sort"
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric // Option to disable EH pad first sorting. Only for testing unwind destination
420b57cec5SDimitry Andric // mismatches in CFGStackify.
430b57cec5SDimitry Andric static cl::opt<bool> WasmDisableEHPadSort(
440b57cec5SDimitry Andric     "wasm-disable-ehpad-sort", cl::ReallyHidden,
450b57cec5SDimitry Andric     cl::desc(
460b57cec5SDimitry Andric         "WebAssembly: Disable EH pad-first sort order. Testing purpose only."),
470b57cec5SDimitry Andric     cl::init(false));
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric namespace {
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric class WebAssemblyCFGSort final : public MachineFunctionPass {
getPassName() const520b57cec5SDimitry Andric   StringRef getPassName() const override { return "WebAssembly CFG Sort"; }
530b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const540b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
550b57cec5SDimitry Andric     AU.setPreservesCFG();
560b57cec5SDimitry Andric     AU.addRequired<MachineDominatorTree>();
570b57cec5SDimitry Andric     AU.addPreserved<MachineDominatorTree>();
580b57cec5SDimitry Andric     AU.addRequired<MachineLoopInfo>();
590b57cec5SDimitry Andric     AU.addPreserved<MachineLoopInfo>();
600b57cec5SDimitry Andric     AU.addRequired<WebAssemblyExceptionInfo>();
610b57cec5SDimitry Andric     AU.addPreserved<WebAssemblyExceptionInfo>();
620b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
630b57cec5SDimitry Andric   }
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric public:
680b57cec5SDimitry Andric   static char ID; // Pass identification, replacement for typeid
WebAssemblyCFGSort()690b57cec5SDimitry Andric   WebAssemblyCFGSort() : MachineFunctionPass(ID) {}
700b57cec5SDimitry Andric };
710b57cec5SDimitry Andric } // end anonymous namespace
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric char WebAssemblyCFGSort::ID = 0;
740b57cec5SDimitry Andric INITIALIZE_PASS(WebAssemblyCFGSort, DEBUG_TYPE,
750b57cec5SDimitry Andric                 "Reorders blocks in topological order", false, false)
760b57cec5SDimitry Andric 
createWebAssemblyCFGSort()770b57cec5SDimitry Andric FunctionPass *llvm::createWebAssemblyCFGSort() {
780b57cec5SDimitry Andric   return new WebAssemblyCFGSort();
790b57cec5SDimitry Andric }
800b57cec5SDimitry Andric 
maybeUpdateTerminator(MachineBasicBlock * MBB)810b57cec5SDimitry Andric static void maybeUpdateTerminator(MachineBasicBlock *MBB) {
820b57cec5SDimitry Andric #ifndef NDEBUG
830b57cec5SDimitry Andric   bool AnyBarrier = false;
840b57cec5SDimitry Andric #endif
850b57cec5SDimitry Andric   bool AllAnalyzable = true;
860b57cec5SDimitry Andric   for (const MachineInstr &Term : MBB->terminators()) {
870b57cec5SDimitry Andric #ifndef NDEBUG
880b57cec5SDimitry Andric     AnyBarrier |= Term.isBarrier();
890b57cec5SDimitry Andric #endif
900b57cec5SDimitry Andric     AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch();
910b57cec5SDimitry Andric   }
920b57cec5SDimitry Andric   assert((AnyBarrier || AllAnalyzable) &&
935ffd83dbSDimitry Andric          "analyzeBranch needs to analyze any block with a fallthrough");
945ffd83dbSDimitry Andric 
955ffd83dbSDimitry Andric   // Find the layout successor from the original block order.
965ffd83dbSDimitry Andric   MachineFunction *MF = MBB->getParent();
975ffd83dbSDimitry Andric   MachineBasicBlock *OriginalSuccessor =
985ffd83dbSDimitry Andric       unsigned(MBB->getNumber() + 1) < MF->getNumBlockIDs()
995ffd83dbSDimitry Andric           ? MF->getBlockNumbered(MBB->getNumber() + 1)
1005ffd83dbSDimitry Andric           : nullptr;
1015ffd83dbSDimitry Andric 
1020b57cec5SDimitry Andric   if (AllAnalyzable)
1035ffd83dbSDimitry Andric     MBB->updateTerminator(OriginalSuccessor);
1040b57cec5SDimitry Andric }
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric namespace {
1070b57cec5SDimitry Andric // EH pads are selected first regardless of the block comparison order.
1080b57cec5SDimitry Andric // When only one of the BBs is an EH pad, we give a higher priority to it, to
1090b57cec5SDimitry Andric // prevent common mismatches between possibly throwing calls and ehpads they
1100b57cec5SDimitry Andric // unwind to, as in the example below:
1110b57cec5SDimitry Andric //
1120b57cec5SDimitry Andric // bb0:
1130b57cec5SDimitry Andric //   call @foo      // If this throws, unwind to bb2
1140b57cec5SDimitry Andric // bb1:
1150b57cec5SDimitry Andric //   call @bar      // If this throws, unwind to bb3
1160b57cec5SDimitry Andric // bb2 (ehpad):
1170b57cec5SDimitry Andric //   handler_bb2
1180b57cec5SDimitry Andric // bb3 (ehpad):
1190b57cec5SDimitry Andric //   handler_bb3
1200b57cec5SDimitry Andric // continuing code
1210b57cec5SDimitry Andric //
1220b57cec5SDimitry Andric // Because this pass tries to preserve the original BB order, this order will
1230b57cec5SDimitry Andric // not change. But this will result in this try-catch structure in CFGStackify,
1240b57cec5SDimitry Andric // resulting in a mismatch:
1250b57cec5SDimitry Andric // try
1260b57cec5SDimitry Andric //   try
1270b57cec5SDimitry Andric //     call @foo
1280b57cec5SDimitry Andric //     call @bar    // This should unwind to bb3, not bb2!
1290b57cec5SDimitry Andric //   catch
1300b57cec5SDimitry Andric //     handler_bb2
1310b57cec5SDimitry Andric //   end
1320b57cec5SDimitry Andric // catch
1330b57cec5SDimitry Andric //   handler_bb3
1340b57cec5SDimitry Andric // end
1350b57cec5SDimitry Andric // continuing code
1360b57cec5SDimitry Andric //
1370b57cec5SDimitry Andric // If we give a higher priority to an EH pad whenever it is ready in this
1380b57cec5SDimitry Andric // example, when both bb1 and bb2 are ready, we would pick up bb2 first.
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric /// Sort blocks by their number.
1410b57cec5SDimitry Andric struct CompareBlockNumbers {
operator ()__anon9a19771f0211::CompareBlockNumbers1420b57cec5SDimitry Andric   bool operator()(const MachineBasicBlock *A,
1430b57cec5SDimitry Andric                   const MachineBasicBlock *B) const {
1440b57cec5SDimitry Andric     if (!WasmDisableEHPadSort) {
1450b57cec5SDimitry Andric       if (A->isEHPad() && !B->isEHPad())
1460b57cec5SDimitry Andric         return false;
1470b57cec5SDimitry Andric       if (!A->isEHPad() && B->isEHPad())
1480b57cec5SDimitry Andric         return true;
1490b57cec5SDimitry Andric     }
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric     return A->getNumber() > B->getNumber();
1520b57cec5SDimitry Andric   }
1530b57cec5SDimitry Andric };
1540b57cec5SDimitry Andric /// Sort blocks by their number in the opposite order..
1550b57cec5SDimitry Andric struct CompareBlockNumbersBackwards {
operator ()__anon9a19771f0211::CompareBlockNumbersBackwards1560b57cec5SDimitry Andric   bool operator()(const MachineBasicBlock *A,
1570b57cec5SDimitry Andric                   const MachineBasicBlock *B) const {
1580b57cec5SDimitry Andric     if (!WasmDisableEHPadSort) {
1590b57cec5SDimitry Andric       if (A->isEHPad() && !B->isEHPad())
1600b57cec5SDimitry Andric         return false;
1610b57cec5SDimitry Andric       if (!A->isEHPad() && B->isEHPad())
1620b57cec5SDimitry Andric         return true;
1630b57cec5SDimitry Andric     }
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric     return A->getNumber() < B->getNumber();
1660b57cec5SDimitry Andric   }
1670b57cec5SDimitry Andric };
1680b57cec5SDimitry Andric /// Bookkeeping for a region to help ensure that we don't mix blocks not
1690b57cec5SDimitry Andric /// dominated by the its header among its blocks.
1700b57cec5SDimitry Andric struct Entry {
171e8d8bef9SDimitry Andric   const SortRegion *TheRegion;
1720b57cec5SDimitry Andric   unsigned NumBlocksLeft;
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   /// List of blocks not dominated by Loop's header that are deferred until
1750b57cec5SDimitry Andric   /// after all of Loop's blocks have been seen.
1760b57cec5SDimitry Andric   std::vector<MachineBasicBlock *> Deferred;
1770b57cec5SDimitry Andric 
Entry__anon9a19771f0211::Entry178e8d8bef9SDimitry Andric   explicit Entry(const SortRegion *R)
1790b57cec5SDimitry Andric       : TheRegion(R), NumBlocksLeft(R->getNumBlocks()) {}
1800b57cec5SDimitry Andric };
1810b57cec5SDimitry Andric } // end anonymous namespace
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric /// Sort the blocks, taking special care to make sure that regions are not
1840b57cec5SDimitry Andric /// interrupted by blocks not dominated by their header.
1850b57cec5SDimitry Andric /// TODO: There are many opportunities for improving the heuristics here.
1860b57cec5SDimitry Andric /// Explore them.
sortBlocks(MachineFunction & MF,const MachineLoopInfo & MLI,const WebAssemblyExceptionInfo & WEI,const MachineDominatorTree & MDT)1870b57cec5SDimitry Andric static void sortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI,
1880b57cec5SDimitry Andric                        const WebAssemblyExceptionInfo &WEI,
1890b57cec5SDimitry Andric                        const MachineDominatorTree &MDT) {
1905ffd83dbSDimitry Andric   // Remember original layout ordering, so we can update terminators after
1915ffd83dbSDimitry Andric   // reordering to point to the original layout successor.
1925ffd83dbSDimitry Andric   MF.RenumberBlocks();
1935ffd83dbSDimitry Andric 
1940b57cec5SDimitry Andric   // Prepare for a topological sort: Record the number of predecessors each
1950b57cec5SDimitry Andric   // block has, ignoring loop backedges.
1960b57cec5SDimitry Andric   SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0);
1970b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
1980b57cec5SDimitry Andric     unsigned N = MBB.pred_size();
1990b57cec5SDimitry Andric     if (MachineLoop *L = MLI.getLoopFor(&MBB))
2000b57cec5SDimitry Andric       if (L->getHeader() == &MBB)
2010b57cec5SDimitry Andric         for (const MachineBasicBlock *Pred : MBB.predecessors())
2020b57cec5SDimitry Andric           if (L->contains(Pred))
2030b57cec5SDimitry Andric             --N;
2040b57cec5SDimitry Andric     NumPredsLeft[MBB.getNumber()] = N;
2050b57cec5SDimitry Andric   }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   // Topological sort the CFG, with additional constraints:
2080b57cec5SDimitry Andric   //  - Between a region header and the last block in the region, there can be
2090b57cec5SDimitry Andric   //    no blocks not dominated by its header.
2100b57cec5SDimitry Andric   //  - It's desirable to preserve the original block order when possible.
2110b57cec5SDimitry Andric   // We use two ready lists; Preferred and Ready. Preferred has recently
2120b57cec5SDimitry Andric   // processed successors, to help preserve block sequences from the original
2130b57cec5SDimitry Andric   // order. Ready has the remaining ready blocks. EH blocks are picked first
2140b57cec5SDimitry Andric   // from both queues.
2150b57cec5SDimitry Andric   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
2160b57cec5SDimitry Andric                 CompareBlockNumbers>
2170b57cec5SDimitry Andric       Preferred;
2180b57cec5SDimitry Andric   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
2190b57cec5SDimitry Andric                 CompareBlockNumbersBackwards>
2200b57cec5SDimitry Andric       Ready;
2210b57cec5SDimitry Andric 
222fe6060f1SDimitry Andric   const auto *EHInfo = MF.getWasmEHFuncInfo();
223e8d8bef9SDimitry Andric   SortRegionInfo SRI(MLI, WEI);
2240b57cec5SDimitry Andric   SmallVector<Entry, 4> Entries;
2250b57cec5SDimitry Andric   for (MachineBasicBlock *MBB = &MF.front();;) {
226e8d8bef9SDimitry Andric     const SortRegion *R = SRI.getRegionFor(MBB);
2270b57cec5SDimitry Andric     if (R) {
2280b57cec5SDimitry Andric       // If MBB is a region header, add it to the active region list. We can't
2290b57cec5SDimitry Andric       // put any blocks that it doesn't dominate until we see the end of the
2300b57cec5SDimitry Andric       // region.
2310b57cec5SDimitry Andric       if (R->getHeader() == MBB)
2320b57cec5SDimitry Andric         Entries.push_back(Entry(R));
2330b57cec5SDimitry Andric       // For each active region the block is in, decrement the count. If MBB is
2340b57cec5SDimitry Andric       // the last block in an active region, take it off the list and pick up
2350b57cec5SDimitry Andric       // any blocks deferred because the header didn't dominate them.
2360b57cec5SDimitry Andric       for (Entry &E : Entries)
2370b57cec5SDimitry Andric         if (E.TheRegion->contains(MBB) && --E.NumBlocksLeft == 0)
238bdd1243dSDimitry Andric           for (auto *DeferredBlock : E.Deferred)
2390b57cec5SDimitry Andric             Ready.push(DeferredBlock);
2400b57cec5SDimitry Andric       while (!Entries.empty() && Entries.back().NumBlocksLeft == 0)
2410b57cec5SDimitry Andric         Entries.pop_back();
2420b57cec5SDimitry Andric     }
2430b57cec5SDimitry Andric     // The main topological sort logic.
2440b57cec5SDimitry Andric     for (MachineBasicBlock *Succ : MBB->successors()) {
2450b57cec5SDimitry Andric       // Ignore backedges.
2460b57cec5SDimitry Andric       if (MachineLoop *SuccL = MLI.getLoopFor(Succ))
2470b57cec5SDimitry Andric         if (SuccL->getHeader() == Succ && SuccL->contains(MBB))
2480b57cec5SDimitry Andric           continue;
2490b57cec5SDimitry Andric       // Decrement the predecessor count. If it's now zero, it's ready.
250fe6060f1SDimitry Andric       if (--NumPredsLeft[Succ->getNumber()] == 0) {
251fe6060f1SDimitry Andric         // When we are in a SortRegion, we allow sorting of not only BBs that
252fe6060f1SDimitry Andric         // belong to the current (innermost) region but also BBs that are
253fe6060f1SDimitry Andric         // dominated by the current region header. But we should not do this for
254fe6060f1SDimitry Andric         // exceptions because there can be cases in which, for example:
255fe6060f1SDimitry Andric         // EHPad A's unwind destination (where the exception lands when it is
256fe6060f1SDimitry Andric         // not caught by EHPad A) is EHPad B, so EHPad B does not belong to the
257fe6060f1SDimitry Andric         // exception dominated by EHPad A. But EHPad B is dominated by EHPad A,
258fe6060f1SDimitry Andric         // so EHPad B can be sorted within EHPad A's exception. This is
259fe6060f1SDimitry Andric         // incorrect because we may end up delegating/rethrowing to an inner
260fe6060f1SDimitry Andric         // scope in CFGStackify. So here we make sure those unwind destinations
261fe6060f1SDimitry Andric         // are deferred until their unwind source's exception is sorted.
262fe6060f1SDimitry Andric         if (EHInfo && EHInfo->hasUnwindSrcs(Succ)) {
263fe6060f1SDimitry Andric           SmallPtrSet<MachineBasicBlock *, 4> UnwindSrcs =
264fe6060f1SDimitry Andric               EHInfo->getUnwindSrcs(Succ);
265fe6060f1SDimitry Andric           bool IsDeferred = false;
266fe6060f1SDimitry Andric           for (Entry &E : Entries) {
267fe6060f1SDimitry Andric             if (UnwindSrcs.count(E.TheRegion->getHeader())) {
268fe6060f1SDimitry Andric               E.Deferred.push_back(Succ);
269fe6060f1SDimitry Andric               IsDeferred = true;
270fe6060f1SDimitry Andric               break;
271fe6060f1SDimitry Andric             }
272fe6060f1SDimitry Andric           }
273fe6060f1SDimitry Andric           if (IsDeferred)
274fe6060f1SDimitry Andric             continue;
275fe6060f1SDimitry Andric         }
2760b57cec5SDimitry Andric         Preferred.push(Succ);
2770b57cec5SDimitry Andric       }
278fe6060f1SDimitry Andric     }
2790b57cec5SDimitry Andric     // Determine the block to follow MBB. First try to find a preferred block,
2800b57cec5SDimitry Andric     // to preserve the original block order when possible.
2810b57cec5SDimitry Andric     MachineBasicBlock *Next = nullptr;
2820b57cec5SDimitry Andric     while (!Preferred.empty()) {
2830b57cec5SDimitry Andric       Next = Preferred.top();
2840b57cec5SDimitry Andric       Preferred.pop();
2850b57cec5SDimitry Andric       // If X isn't dominated by the top active region header, defer it until
2860b57cec5SDimitry Andric       // that region is done.
2870b57cec5SDimitry Andric       if (!Entries.empty() &&
2880b57cec5SDimitry Andric           !MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
2890b57cec5SDimitry Andric         Entries.back().Deferred.push_back(Next);
2900b57cec5SDimitry Andric         Next = nullptr;
2910b57cec5SDimitry Andric         continue;
2920b57cec5SDimitry Andric       }
2930b57cec5SDimitry Andric       // If Next was originally ordered before MBB, and it isn't because it was
2940b57cec5SDimitry Andric       // loop-rotated above the header, it's not preferred.
2950b57cec5SDimitry Andric       if (Next->getNumber() < MBB->getNumber() &&
2968bcb0991SDimitry Andric           (WasmDisableEHPadSort || !Next->isEHPad()) &&
2970b57cec5SDimitry Andric           (!R || !R->contains(Next) ||
2980b57cec5SDimitry Andric            R->getHeader()->getNumber() < Next->getNumber())) {
2990b57cec5SDimitry Andric         Ready.push(Next);
3000b57cec5SDimitry Andric         Next = nullptr;
3010b57cec5SDimitry Andric         continue;
3020b57cec5SDimitry Andric       }
3030b57cec5SDimitry Andric       break;
3040b57cec5SDimitry Andric     }
3050b57cec5SDimitry Andric     // If we didn't find a suitable block in the Preferred list, check the
3060b57cec5SDimitry Andric     // general Ready list.
3070b57cec5SDimitry Andric     if (!Next) {
3080b57cec5SDimitry Andric       // If there are no more blocks to process, we're done.
3090b57cec5SDimitry Andric       if (Ready.empty()) {
3100b57cec5SDimitry Andric         maybeUpdateTerminator(MBB);
3110b57cec5SDimitry Andric         break;
3120b57cec5SDimitry Andric       }
3130b57cec5SDimitry Andric       for (;;) {
3140b57cec5SDimitry Andric         Next = Ready.top();
3150b57cec5SDimitry Andric         Ready.pop();
3160b57cec5SDimitry Andric         // If Next isn't dominated by the top active region header, defer it
3170b57cec5SDimitry Andric         // until that region is done.
3180b57cec5SDimitry Andric         if (!Entries.empty() &&
3190b57cec5SDimitry Andric             !MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
3200b57cec5SDimitry Andric           Entries.back().Deferred.push_back(Next);
3210b57cec5SDimitry Andric           continue;
3220b57cec5SDimitry Andric         }
3230b57cec5SDimitry Andric         break;
3240b57cec5SDimitry Andric       }
3250b57cec5SDimitry Andric     }
3260b57cec5SDimitry Andric     // Move the next block into place and iterate.
3270b57cec5SDimitry Andric     Next->moveAfter(MBB);
3280b57cec5SDimitry Andric     maybeUpdateTerminator(MBB);
3290b57cec5SDimitry Andric     MBB = Next;
3300b57cec5SDimitry Andric   }
3310b57cec5SDimitry Andric   assert(Entries.empty() && "Active sort region list not finished");
3320b57cec5SDimitry Andric   MF.RenumberBlocks();
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric #ifndef NDEBUG
335e8d8bef9SDimitry Andric   SmallSetVector<const SortRegion *, 8> OnStack;
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric   // Insert a sentinel representing the degenerate loop that starts at the
3380b57cec5SDimitry Andric   // function entry block and includes the entire function as a "loop" that
3390b57cec5SDimitry Andric   // executes once.
3400b57cec5SDimitry Andric   OnStack.insert(nullptr);
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   for (auto &MBB : MF) {
3430b57cec5SDimitry Andric     assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
344e8d8bef9SDimitry Andric     const SortRegion *Region = SRI.getRegionFor(&MBB);
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric     if (Region && &MBB == Region->getHeader()) {
3475ffd83dbSDimitry Andric       // Region header.
3480b57cec5SDimitry Andric       if (Region->isLoop()) {
3490b57cec5SDimitry Andric         // Loop header. The loop predecessor should be sorted above, and the
3500b57cec5SDimitry Andric         // other predecessors should be backedges below.
351bdd1243dSDimitry Andric         for (auto *Pred : MBB.predecessors())
3520b57cec5SDimitry Andric           assert(
3530b57cec5SDimitry Andric               (Pred->getNumber() < MBB.getNumber() || Region->contains(Pred)) &&
3540b57cec5SDimitry Andric               "Loop header predecessors must be loop predecessors or "
3550b57cec5SDimitry Andric               "backedges");
3560b57cec5SDimitry Andric       } else {
3575ffd83dbSDimitry Andric         // Exception header. All predecessors should be sorted above.
358bdd1243dSDimitry Andric         for (auto *Pred : MBB.predecessors())
3590b57cec5SDimitry Andric           assert(Pred->getNumber() < MBB.getNumber() &&
3600b57cec5SDimitry Andric                  "Non-loop-header predecessors should be topologically sorted");
3610b57cec5SDimitry Andric       }
3620b57cec5SDimitry Andric       assert(OnStack.insert(Region) &&
3630b57cec5SDimitry Andric              "Regions should be declared at most once.");
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric     } else {
3665ffd83dbSDimitry Andric       // Not a region header. All predecessors should be sorted above.
367bdd1243dSDimitry Andric       for (auto *Pred : MBB.predecessors())
3680b57cec5SDimitry Andric         assert(Pred->getNumber() < MBB.getNumber() &&
3690b57cec5SDimitry Andric                "Non-loop-header predecessors should be topologically sorted");
370e8d8bef9SDimitry Andric       assert(OnStack.count(SRI.getRegionFor(&MBB)) &&
3710b57cec5SDimitry Andric              "Blocks must be nested in their regions");
3720b57cec5SDimitry Andric     }
373e8d8bef9SDimitry Andric     while (OnStack.size() > 1 && &MBB == SRI.getBottom(OnStack.back()))
3740b57cec5SDimitry Andric       OnStack.pop_back();
3750b57cec5SDimitry Andric   }
3760b57cec5SDimitry Andric   assert(OnStack.pop_back_val() == nullptr &&
3770b57cec5SDimitry Andric          "The function entry block shouldn't actually be a region header");
3780b57cec5SDimitry Andric   assert(OnStack.empty() &&
3790b57cec5SDimitry Andric          "Control flow stack pushes and pops should be balanced.");
3800b57cec5SDimitry Andric #endif
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)3830b57cec5SDimitry Andric bool WebAssemblyCFGSort::runOnMachineFunction(MachineFunction &MF) {
3840b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** CFG Sorting **********\n"
3850b57cec5SDimitry Andric                        "********** Function: "
3860b57cec5SDimitry Andric                     << MF.getName() << '\n');
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   const auto &MLI = getAnalysis<MachineLoopInfo>();
3890b57cec5SDimitry Andric   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
3900b57cec5SDimitry Andric   auto &MDT = getAnalysis<MachineDominatorTree>();
3910b57cec5SDimitry Andric   // Liveness is not tracked for VALUE_STACK physreg.
3920b57cec5SDimitry Andric   MF.getRegInfo().invalidateLiveness();
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   // Sort the blocks, with contiguous sort regions.
3950b57cec5SDimitry Andric   sortBlocks(MF, MLI, WEI, MDT);
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric   return true;
3980b57cec5SDimitry Andric }
399