1f52ee17aSDan Gohman //===-- WebAssemblyCFGSort.cpp - CFG Sorting ------------------------------===//
2f52ee17aSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f52ee17aSDan Gohman //
7f52ee17aSDan Gohman //===----------------------------------------------------------------------===//
8f52ee17aSDan Gohman ///
9f52ee17aSDan Gohman /// \file
105f8f34e4SAdrian Prantl /// This file implements a CFG sorting pass.
11f52ee17aSDan Gohman ///
12f52ee17aSDan Gohman /// This pass reorders the blocks in a function to put them into topological
137fb68d26SHeejin Ahn /// order, ignoring loop backedges, and without any loop or exception being
147fb68d26SHeejin Ahn /// interrupted by a block not dominated by the its header, with special care
157fb68d26SHeejin Ahn /// to keep the order as similar as possible to the original order.
16f52ee17aSDan Gohman ///
17f52ee17aSDan Gohman ////===----------------------------------------------------------------------===//
18f52ee17aSDan Gohman
19f52ee17aSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
20*0b2bc69bSHeejin Ahn #include "Utils/WebAssemblyUtilities.h"
216bda14b3SChandler Carruth #include "WebAssembly.h"
227fb68d26SHeejin Ahn #include "WebAssemblyExceptionInfo.h"
23276f9e8cSHeejin Ahn #include "WebAssemblySortRegion.h"
24f52ee17aSDan Gohman #include "WebAssemblySubtarget.h"
25f52ee17aSDan Gohman #include "llvm/ADT/PriorityQueue.h"
26f52ee17aSDan Gohman #include "llvm/ADT/SetVector.h"
27f52ee17aSDan Gohman #include "llvm/CodeGen/MachineDominators.h"
28f52ee17aSDan Gohman #include "llvm/CodeGen/MachineFunction.h"
29f52ee17aSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h"
30f52ee17aSDan Gohman #include "llvm/CodeGen/MachineRegisterInfo.h"
31f52ee17aSDan Gohman #include "llvm/CodeGen/Passes.h"
32ea8c6375SHeejin Ahn #include "llvm/CodeGen/WasmEHFuncInfo.h"
33f52ee17aSDan Gohman #include "llvm/Support/Debug.h"
34f52ee17aSDan Gohman #include "llvm/Support/raw_ostream.h"
35f52ee17aSDan Gohman using namespace llvm;
36276f9e8cSHeejin Ahn using WebAssembly::SortRegion;
37276f9e8cSHeejin Ahn using WebAssembly::SortRegionInfo;
38f52ee17aSDan Gohman
39f52ee17aSDan Gohman #define DEBUG_TYPE "wasm-cfg-sort"
40f52ee17aSDan Gohman
4154551c1dSHeejin Ahn // Option to disable EH pad first sorting. Only for testing unwind destination
4254551c1dSHeejin Ahn // mismatches in CFGStackify.
4354551c1dSHeejin Ahn static cl::opt<bool> WasmDisableEHPadSort(
4454551c1dSHeejin Ahn "wasm-disable-ehpad-sort", cl::ReallyHidden,
4554551c1dSHeejin Ahn cl::desc(
4654551c1dSHeejin Ahn "WebAssembly: Disable EH pad-first sort order. Testing purpose only."),
4754551c1dSHeejin Ahn cl::init(false));
4854551c1dSHeejin Ahn
49f52ee17aSDan Gohman namespace {
507fb68d26SHeejin Ahn
51f52ee17aSDan Gohman class WebAssemblyCFGSort final : public MachineFunctionPass {
getPassName() const52f52ee17aSDan Gohman StringRef getPassName() const override { return "WebAssembly CFG Sort"; }
53f52ee17aSDan Gohman
getAnalysisUsage(AnalysisUsage & AU) const54f52ee17aSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override {
55f52ee17aSDan Gohman AU.setPreservesCFG();
56f52ee17aSDan Gohman AU.addRequired<MachineDominatorTree>();
57f52ee17aSDan Gohman AU.addPreserved<MachineDominatorTree>();
58f52ee17aSDan Gohman AU.addRequired<MachineLoopInfo>();
59f52ee17aSDan Gohman AU.addPreserved<MachineLoopInfo>();
607fb68d26SHeejin Ahn AU.addRequired<WebAssemblyExceptionInfo>();
617fb68d26SHeejin Ahn AU.addPreserved<WebAssemblyExceptionInfo>();
62f52ee17aSDan Gohman MachineFunctionPass::getAnalysisUsage(AU);
63f52ee17aSDan Gohman }
64f52ee17aSDan Gohman
65f52ee17aSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override;
66f52ee17aSDan Gohman
67f52ee17aSDan Gohman public:
68f52ee17aSDan Gohman static char ID; // Pass identification, replacement for typeid
WebAssemblyCFGSort()69f52ee17aSDan Gohman WebAssemblyCFGSort() : MachineFunctionPass(ID) {}
70f52ee17aSDan Gohman };
71f52ee17aSDan Gohman } // end anonymous namespace
72f52ee17aSDan Gohman
73f52ee17aSDan Gohman char WebAssemblyCFGSort::ID = 0;
7440926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGSort, DEBUG_TYPE,
7540926451SJacob Gravelle "Reorders blocks in topological order", false, false)
7640926451SJacob Gravelle
createWebAssemblyCFGSort()77f52ee17aSDan Gohman FunctionPass *llvm::createWebAssemblyCFGSort() {
78f52ee17aSDan Gohman return new WebAssemblyCFGSort();
79f52ee17aSDan Gohman }
80f52ee17aSDan Gohman
maybeUpdateTerminator(MachineBasicBlock * MBB)8118c56a07SHeejin Ahn static void maybeUpdateTerminator(MachineBasicBlock *MBB) {
82f52ee17aSDan Gohman #ifndef NDEBUG
83f52ee17aSDan Gohman bool AnyBarrier = false;
84f52ee17aSDan Gohman #endif
85f52ee17aSDan Gohman bool AllAnalyzable = true;
86f52ee17aSDan Gohman for (const MachineInstr &Term : MBB->terminators()) {
87f52ee17aSDan Gohman #ifndef NDEBUG
88f52ee17aSDan Gohman AnyBarrier |= Term.isBarrier();
89f52ee17aSDan Gohman #endif
90f52ee17aSDan Gohman AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch();
91f52ee17aSDan Gohman }
92f52ee17aSDan Gohman assert((AnyBarrier || AllAnalyzable) &&
93020041d9SKrzysztof Parzyszek "analyzeBranch needs to analyze any block with a fallthrough");
941978309dSJames Y Knight
951978309dSJames Y Knight // Find the layout successor from the original block order.
961978309dSJames Y Knight MachineFunction *MF = MBB->getParent();
971978309dSJames Y Knight MachineBasicBlock *OriginalSuccessor =
981978309dSJames Y Knight unsigned(MBB->getNumber() + 1) < MF->getNumBlockIDs()
991978309dSJames Y Knight ? MF->getBlockNumbered(MBB->getNumber() + 1)
1001978309dSJames Y Knight : nullptr;
1011978309dSJames Y Knight
102f52ee17aSDan Gohman if (AllAnalyzable)
1031978309dSJames Y Knight MBB->updateTerminator(OriginalSuccessor);
104f52ee17aSDan Gohman }
105f52ee17aSDan Gohman
106f52ee17aSDan Gohman namespace {
1077fb68d26SHeejin Ahn // EH pads are selected first regardless of the block comparison order.
1087fb68d26SHeejin Ahn // When only one of the BBs is an EH pad, we give a higher priority to it, to
1097fb68d26SHeejin Ahn // prevent common mismatches between possibly throwing calls and ehpads they
1107fb68d26SHeejin Ahn // unwind to, as in the example below:
1117fb68d26SHeejin Ahn //
1127fb68d26SHeejin Ahn // bb0:
1137fb68d26SHeejin Ahn // call @foo // If this throws, unwind to bb2
1147fb68d26SHeejin Ahn // bb1:
1157fb68d26SHeejin Ahn // call @bar // If this throws, unwind to bb3
1167fb68d26SHeejin Ahn // bb2 (ehpad):
1177fb68d26SHeejin Ahn // handler_bb2
1187fb68d26SHeejin Ahn // bb3 (ehpad):
1197fb68d26SHeejin Ahn // handler_bb3
1207fb68d26SHeejin Ahn // continuing code
1217fb68d26SHeejin Ahn //
1227fb68d26SHeejin Ahn // Because this pass tries to preserve the original BB order, this order will
1237fb68d26SHeejin Ahn // not change. But this will result in this try-catch structure in CFGStackify,
1247fb68d26SHeejin Ahn // resulting in a mismatch:
1257fb68d26SHeejin Ahn // try
1267fb68d26SHeejin Ahn // try
1277fb68d26SHeejin Ahn // call @foo
1287fb68d26SHeejin Ahn // call @bar // This should unwind to bb3, not bb2!
1297fb68d26SHeejin Ahn // catch
1307fb68d26SHeejin Ahn // handler_bb2
1317fb68d26SHeejin Ahn // end
1327fb68d26SHeejin Ahn // catch
1337fb68d26SHeejin Ahn // handler_bb3
1347fb68d26SHeejin Ahn // end
1357fb68d26SHeejin Ahn // continuing code
1367fb68d26SHeejin Ahn //
1377fb68d26SHeejin Ahn // If we give a higher priority to an EH pad whenever it is ready in this
1387fb68d26SHeejin Ahn // example, when both bb1 and bb2 are ready, we would pick up bb2 first.
1397fb68d26SHeejin Ahn
140f52ee17aSDan Gohman /// Sort blocks by their number.
141f52ee17aSDan Gohman struct CompareBlockNumbers {
operator ()__anondaa273d90211::CompareBlockNumbers142f52ee17aSDan Gohman bool operator()(const MachineBasicBlock *A,
143f52ee17aSDan Gohman const MachineBasicBlock *B) const {
14454551c1dSHeejin Ahn if (!WasmDisableEHPadSort) {
1457fb68d26SHeejin Ahn if (A->isEHPad() && !B->isEHPad())
1467fb68d26SHeejin Ahn return false;
1477fb68d26SHeejin Ahn if (!A->isEHPad() && B->isEHPad())
1487fb68d26SHeejin Ahn return true;
14954551c1dSHeejin Ahn }
1507fb68d26SHeejin Ahn
151f52ee17aSDan Gohman return A->getNumber() > B->getNumber();
152f52ee17aSDan Gohman }
153f52ee17aSDan Gohman };
154f52ee17aSDan Gohman /// Sort blocks by their number in the opposite order..
155f52ee17aSDan Gohman struct CompareBlockNumbersBackwards {
operator ()__anondaa273d90211::CompareBlockNumbersBackwards156f52ee17aSDan Gohman bool operator()(const MachineBasicBlock *A,
157f52ee17aSDan Gohman const MachineBasicBlock *B) const {
15854551c1dSHeejin Ahn if (!WasmDisableEHPadSort) {
1597fb68d26SHeejin Ahn if (A->isEHPad() && !B->isEHPad())
1607fb68d26SHeejin Ahn return false;
1617fb68d26SHeejin Ahn if (!A->isEHPad() && B->isEHPad())
1627fb68d26SHeejin Ahn return true;
16354551c1dSHeejin Ahn }
1647fb68d26SHeejin Ahn
165f52ee17aSDan Gohman return A->getNumber() < B->getNumber();
166f52ee17aSDan Gohman }
167f52ee17aSDan Gohman };
1687fb68d26SHeejin Ahn /// Bookkeeping for a region to help ensure that we don't mix blocks not
1697fb68d26SHeejin Ahn /// dominated by the its header among its blocks.
170f52ee17aSDan Gohman struct Entry {
171276f9e8cSHeejin Ahn const SortRegion *TheRegion;
172f52ee17aSDan Gohman unsigned NumBlocksLeft;
173f52ee17aSDan Gohman
174f52ee17aSDan Gohman /// List of blocks not dominated by Loop's header that are deferred until
175f52ee17aSDan Gohman /// after all of Loop's blocks have been seen.
176f52ee17aSDan Gohman std::vector<MachineBasicBlock *> Deferred;
177f52ee17aSDan Gohman
Entry__anondaa273d90211::Entry178276f9e8cSHeejin Ahn explicit Entry(const SortRegion *R)
17941b25c6cSHeejin Ahn : TheRegion(R), NumBlocksLeft(R->getNumBlocks()) {}
180f52ee17aSDan Gohman };
181f52ee17aSDan Gohman } // end anonymous namespace
182f52ee17aSDan Gohman
1837fb68d26SHeejin Ahn /// Sort the blocks, taking special care to make sure that regions are not
184f52ee17aSDan Gohman /// interrupted by blocks not dominated by their header.
185f52ee17aSDan Gohman /// TODO: There are many opportunities for improving the heuristics here.
186f52ee17aSDan Gohman /// Explore them.
sortBlocks(MachineFunction & MF,const MachineLoopInfo & MLI,const WebAssemblyExceptionInfo & WEI,const MachineDominatorTree & MDT)18718c56a07SHeejin Ahn static void sortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI,
1887fb68d26SHeejin Ahn const WebAssemblyExceptionInfo &WEI,
189f52ee17aSDan Gohman const MachineDominatorTree &MDT) {
1901978309dSJames Y Knight // Remember original layout ordering, so we can update terminators after
1911978309dSJames Y Knight // reordering to point to the original layout successor.
1921978309dSJames Y Knight MF.RenumberBlocks();
1931978309dSJames Y Knight
194f52ee17aSDan Gohman // Prepare for a topological sort: Record the number of predecessors each
195f52ee17aSDan Gohman // block has, ignoring loop backedges.
196f52ee17aSDan Gohman SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0);
197f52ee17aSDan Gohman for (MachineBasicBlock &MBB : MF) {
198f52ee17aSDan Gohman unsigned N = MBB.pred_size();
199f52ee17aSDan Gohman if (MachineLoop *L = MLI.getLoopFor(&MBB))
200f52ee17aSDan Gohman if (L->getHeader() == &MBB)
201f52ee17aSDan Gohman for (const MachineBasicBlock *Pred : MBB.predecessors())
202f52ee17aSDan Gohman if (L->contains(Pred))
203f52ee17aSDan Gohman --N;
204f52ee17aSDan Gohman NumPredsLeft[MBB.getNumber()] = N;
205f52ee17aSDan Gohman }
206f52ee17aSDan Gohman
207f52ee17aSDan Gohman // Topological sort the CFG, with additional constraints:
2087fb68d26SHeejin Ahn // - Between a region header and the last block in the region, there can be
2097fb68d26SHeejin Ahn // no blocks not dominated by its header.
210f52ee17aSDan Gohman // - It's desirable to preserve the original block order when possible.
211f52ee17aSDan Gohman // We use two ready lists; Preferred and Ready. Preferred has recently
212713b5ba2SHiroshi Inoue // processed successors, to help preserve block sequences from the original
2137fb68d26SHeejin Ahn // order. Ready has the remaining ready blocks. EH blocks are picked first
2147fb68d26SHeejin Ahn // from both queues.
215f52ee17aSDan Gohman PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
216f52ee17aSDan Gohman CompareBlockNumbers>
217f52ee17aSDan Gohman Preferred;
218f52ee17aSDan Gohman PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
219f52ee17aSDan Gohman CompareBlockNumbersBackwards>
220f52ee17aSDan Gohman Ready;
2217fb68d26SHeejin Ahn
222ea8c6375SHeejin Ahn const auto *EHInfo = MF.getWasmEHFuncInfo();
223276f9e8cSHeejin Ahn SortRegionInfo SRI(MLI, WEI);
2247fb68d26SHeejin Ahn SmallVector<Entry, 4> Entries;
225f52ee17aSDan Gohman for (MachineBasicBlock *MBB = &MF.front();;) {
226276f9e8cSHeejin Ahn const SortRegion *R = SRI.getRegionFor(MBB);
2277fb68d26SHeejin Ahn if (R) {
2287fb68d26SHeejin Ahn // If MBB is a region header, add it to the active region list. We can't
2297fb68d26SHeejin Ahn // put any blocks that it doesn't dominate until we see the end of the
2307fb68d26SHeejin Ahn // region.
2317fb68d26SHeejin Ahn if (R->getHeader() == MBB)
2327fb68d26SHeejin Ahn Entries.push_back(Entry(R));
2337fb68d26SHeejin Ahn // For each active region the block is in, decrement the count. If MBB is
2347fb68d26SHeejin Ahn // the last block in an active region, take it off the list and pick up
2357fb68d26SHeejin Ahn // any blocks deferred because the header didn't dominate them.
2367fb68d26SHeejin Ahn for (Entry &E : Entries)
23741b25c6cSHeejin Ahn if (E.TheRegion->contains(MBB) && --E.NumBlocksLeft == 0)
238f52ee17aSDan Gohman for (auto DeferredBlock : E.Deferred)
239f52ee17aSDan Gohman Ready.push(DeferredBlock);
2407fb68d26SHeejin Ahn while (!Entries.empty() && Entries.back().NumBlocksLeft == 0)
2417fb68d26SHeejin Ahn Entries.pop_back();
242f52ee17aSDan Gohman }
243f52ee17aSDan Gohman // The main topological sort logic.
244f52ee17aSDan Gohman for (MachineBasicBlock *Succ : MBB->successors()) {
245f52ee17aSDan Gohman // Ignore backedges.
246f52ee17aSDan Gohman if (MachineLoop *SuccL = MLI.getLoopFor(Succ))
247f52ee17aSDan Gohman if (SuccL->getHeader() == Succ && SuccL->contains(MBB))
248f52ee17aSDan Gohman continue;
249f52ee17aSDan Gohman // Decrement the predecessor count. If it's now zero, it's ready.
250ea8c6375SHeejin Ahn if (--NumPredsLeft[Succ->getNumber()] == 0) {
251ea8c6375SHeejin Ahn // When we are in a SortRegion, we allow sorting of not only BBs that
252ea8c6375SHeejin Ahn // belong to the current (innermost) region but also BBs that are
253ea8c6375SHeejin Ahn // dominated by the current region header. But we should not do this for
254ea8c6375SHeejin Ahn // exceptions because there can be cases in which, for example:
255ea8c6375SHeejin Ahn // EHPad A's unwind destination (where the exception lands when it is
256ea8c6375SHeejin Ahn // not caught by EHPad A) is EHPad B, so EHPad B does not belong to the
257ea8c6375SHeejin Ahn // exception dominated by EHPad A. But EHPad B is dominated by EHPad A,
258ea8c6375SHeejin Ahn // so EHPad B can be sorted within EHPad A's exception. This is
259ea8c6375SHeejin Ahn // incorrect because we may end up delegating/rethrowing to an inner
260ea8c6375SHeejin Ahn // scope in CFGStackify. So here we make sure those unwind destinations
261ea8c6375SHeejin Ahn // are deferred until their unwind source's exception is sorted.
262aa097ef8SHeejin Ahn if (EHInfo && EHInfo->hasUnwindSrcs(Succ)) {
263aa097ef8SHeejin Ahn SmallPtrSet<MachineBasicBlock *, 4> UnwindSrcs =
264aa097ef8SHeejin Ahn EHInfo->getUnwindSrcs(Succ);
265ea8c6375SHeejin Ahn bool IsDeferred = false;
266aa097ef8SHeejin Ahn for (Entry &E : Entries) {
267aa097ef8SHeejin Ahn if (UnwindSrcs.count(E.TheRegion->getHeader())) {
268ea8c6375SHeejin Ahn E.Deferred.push_back(Succ);
269ea8c6375SHeejin Ahn IsDeferred = true;
270ea8c6375SHeejin Ahn break;
271ea8c6375SHeejin Ahn }
272ea8c6375SHeejin Ahn }
273ea8c6375SHeejin Ahn if (IsDeferred)
274ea8c6375SHeejin Ahn continue;
275ea8c6375SHeejin Ahn }
276f52ee17aSDan Gohman Preferred.push(Succ);
277f52ee17aSDan Gohman }
278ea8c6375SHeejin Ahn }
279f52ee17aSDan Gohman // Determine the block to follow MBB. First try to find a preferred block,
280f52ee17aSDan Gohman // to preserve the original block order when possible.
281f52ee17aSDan Gohman MachineBasicBlock *Next = nullptr;
282f52ee17aSDan Gohman while (!Preferred.empty()) {
283f52ee17aSDan Gohman Next = Preferred.top();
284f52ee17aSDan Gohman Preferred.pop();
2857fb68d26SHeejin Ahn // If X isn't dominated by the top active region header, defer it until
2867fb68d26SHeejin Ahn // that region is done.
2877fb68d26SHeejin Ahn if (!Entries.empty() &&
28841b25c6cSHeejin Ahn !MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
2897fb68d26SHeejin Ahn Entries.back().Deferred.push_back(Next);
290f52ee17aSDan Gohman Next = nullptr;
291f52ee17aSDan Gohman continue;
292f52ee17aSDan Gohman }
293f52ee17aSDan Gohman // If Next was originally ordered before MBB, and it isn't because it was
294f52ee17aSDan Gohman // loop-rotated above the header, it's not preferred.
295f52ee17aSDan Gohman if (Next->getNumber() < MBB->getNumber() &&
296e2bcab61SHeejin Ahn (WasmDisableEHPadSort || !Next->isEHPad()) &&
2977fb68d26SHeejin Ahn (!R || !R->contains(Next) ||
2987fb68d26SHeejin Ahn R->getHeader()->getNumber() < Next->getNumber())) {
299f52ee17aSDan Gohman Ready.push(Next);
300f52ee17aSDan Gohman Next = nullptr;
301f52ee17aSDan Gohman continue;
302f52ee17aSDan Gohman }
303f52ee17aSDan Gohman break;
304f52ee17aSDan Gohman }
305f52ee17aSDan Gohman // If we didn't find a suitable block in the Preferred list, check the
306f52ee17aSDan Gohman // general Ready list.
307f52ee17aSDan Gohman if (!Next) {
308f52ee17aSDan Gohman // If there are no more blocks to process, we're done.
309f52ee17aSDan Gohman if (Ready.empty()) {
31018c56a07SHeejin Ahn maybeUpdateTerminator(MBB);
311f52ee17aSDan Gohman break;
312f52ee17aSDan Gohman }
313f52ee17aSDan Gohman for (;;) {
314f52ee17aSDan Gohman Next = Ready.top();
315f52ee17aSDan Gohman Ready.pop();
3167fb68d26SHeejin Ahn // If Next isn't dominated by the top active region header, defer it
3177fb68d26SHeejin Ahn // until that region is done.
3187fb68d26SHeejin Ahn if (!Entries.empty() &&
31941b25c6cSHeejin Ahn !MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
3207fb68d26SHeejin Ahn Entries.back().Deferred.push_back(Next);
321f52ee17aSDan Gohman continue;
322f52ee17aSDan Gohman }
323f52ee17aSDan Gohman break;
324f52ee17aSDan Gohman }
325f52ee17aSDan Gohman }
326f52ee17aSDan Gohman // Move the next block into place and iterate.
327f52ee17aSDan Gohman Next->moveAfter(MBB);
32818c56a07SHeejin Ahn maybeUpdateTerminator(MBB);
329f52ee17aSDan Gohman MBB = Next;
330f52ee17aSDan Gohman }
3317fb68d26SHeejin Ahn assert(Entries.empty() && "Active sort region list not finished");
332f52ee17aSDan Gohman MF.RenumberBlocks();
333f52ee17aSDan Gohman
334f52ee17aSDan Gohman #ifndef NDEBUG
335276f9e8cSHeejin Ahn SmallSetVector<const SortRegion *, 8> OnStack;
336f52ee17aSDan Gohman
337f52ee17aSDan Gohman // Insert a sentinel representing the degenerate loop that starts at the
338f52ee17aSDan Gohman // function entry block and includes the entire function as a "loop" that
339f52ee17aSDan Gohman // executes once.
340f52ee17aSDan Gohman OnStack.insert(nullptr);
341f52ee17aSDan Gohman
342f52ee17aSDan Gohman for (auto &MBB : MF) {
343f52ee17aSDan Gohman assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
344276f9e8cSHeejin Ahn const SortRegion *Region = SRI.getRegionFor(&MBB);
345f52ee17aSDan Gohman
3467fb68d26SHeejin Ahn if (Region && &MBB == Region->getHeader()) {
347c87b5e7eSHeejin Ahn // Region header.
3487fb68d26SHeejin Ahn if (Region->isLoop()) {
3497fb68d26SHeejin Ahn // Loop header. The loop predecessor should be sorted above, and the
3507fb68d26SHeejin Ahn // other predecessors should be backedges below.
351f52ee17aSDan Gohman for (auto Pred : MBB.predecessors())
352f52ee17aSDan Gohman assert(
3537fb68d26SHeejin Ahn (Pred->getNumber() < MBB.getNumber() || Region->contains(Pred)) &&
3547fb68d26SHeejin Ahn "Loop header predecessors must be loop predecessors or "
3557fb68d26SHeejin Ahn "backedges");
356f52ee17aSDan Gohman } else {
357c87b5e7eSHeejin Ahn // Exception header. All predecessors should be sorted above.
358f52ee17aSDan Gohman for (auto Pred : MBB.predecessors())
359f52ee17aSDan Gohman assert(Pred->getNumber() < MBB.getNumber() &&
360f52ee17aSDan Gohman "Non-loop-header predecessors should be topologically sorted");
3617fb68d26SHeejin Ahn }
3627fb68d26SHeejin Ahn assert(OnStack.insert(Region) &&
3637fb68d26SHeejin Ahn "Regions should be declared at most once.");
3647fb68d26SHeejin Ahn
3657fb68d26SHeejin Ahn } else {
366c87b5e7eSHeejin Ahn // Not a region header. All predecessors should be sorted above.
3677fb68d26SHeejin Ahn for (auto Pred : MBB.predecessors())
3687fb68d26SHeejin Ahn assert(Pred->getNumber() < MBB.getNumber() &&
3697fb68d26SHeejin Ahn "Non-loop-header predecessors should be topologically sorted");
370276f9e8cSHeejin Ahn assert(OnStack.count(SRI.getRegionFor(&MBB)) &&
3717fb68d26SHeejin Ahn "Blocks must be nested in their regions");
372f52ee17aSDan Gohman }
373276f9e8cSHeejin Ahn while (OnStack.size() > 1 && &MBB == SRI.getBottom(OnStack.back()))
374f52ee17aSDan Gohman OnStack.pop_back();
375f52ee17aSDan Gohman }
376f52ee17aSDan Gohman assert(OnStack.pop_back_val() == nullptr &&
3777fb68d26SHeejin Ahn "The function entry block shouldn't actually be a region header");
378f52ee17aSDan Gohman assert(OnStack.empty() &&
379f52ee17aSDan Gohman "Control flow stack pushes and pops should be balanced.");
380f52ee17aSDan Gohman #endif
381f52ee17aSDan Gohman }
382f52ee17aSDan Gohman
runOnMachineFunction(MachineFunction & MF)383f52ee17aSDan Gohman bool WebAssemblyCFGSort::runOnMachineFunction(MachineFunction &MF) {
384d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** CFG Sorting **********\n"
385f52ee17aSDan Gohman "********** Function: "
386f52ee17aSDan Gohman << MF.getName() << '\n');
387f52ee17aSDan Gohman
388f52ee17aSDan Gohman const auto &MLI = getAnalysis<MachineLoopInfo>();
3897fb68d26SHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
390f52ee17aSDan Gohman auto &MDT = getAnalysis<MachineDominatorTree>();
391f52ee17aSDan Gohman // Liveness is not tracked for VALUE_STACK physreg.
392f52ee17aSDan Gohman MF.getRegInfo().invalidateLiveness();
393f52ee17aSDan Gohman
3947fb68d26SHeejin Ahn // Sort the blocks, with contiguous sort regions.
39518c56a07SHeejin Ahn sortBlocks(MF, MLI, WEI, MDT);
396f52ee17aSDan Gohman
397f52ee17aSDan Gohman return true;
398f52ee17aSDan Gohman }
399