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 ///
13*442bfcecSDan Gohman /// This pass reorders the blocks in a function to put them into topological
14*442bfcecSDan Gohman /// order, ignoring loop backedges, and without any loop being interrupted
15*442bfcecSDan Gohman /// by a block not dominated by the loop header, with special care to keep the
16*442bfcecSDan 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*442bfcecSDan Gohman #include "llvm/ADT/PriorityQueue.h"
31950a13cfSDan Gohman #include "llvm/ADT/SCCIterator.h"
328fe7e86bSDan Gohman #include "llvm/ADT/SetVector.h"
3332807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
34950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h"
35950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
36950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h"
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 {
47950a13cfSDan Gohman   const char *getPassName() const override {
48950a13cfSDan Gohman     return "WebAssembly CFG Stackify";
49950a13cfSDan Gohman   }
50950a13cfSDan Gohman 
51950a13cfSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
52950a13cfSDan Gohman     AU.setPreservesCFG();
5332807932SDan Gohman     AU.addRequired<MachineDominatorTree>();
5432807932SDan Gohman     AU.addPreserved<MachineDominatorTree>();
55950a13cfSDan Gohman     AU.addRequired<MachineLoopInfo>();
56950a13cfSDan Gohman     AU.addPreserved<MachineLoopInfo>();
57950a13cfSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
58950a13cfSDan Gohman   }
59950a13cfSDan Gohman 
60950a13cfSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
61950a13cfSDan Gohman 
62950a13cfSDan Gohman public:
63950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
64950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
65950a13cfSDan Gohman };
66950a13cfSDan Gohman } // end anonymous namespace
67950a13cfSDan Gohman 
68950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
69950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
70950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
71950a13cfSDan Gohman }
72950a13cfSDan Gohman 
73950a13cfSDan Gohman static void EliminateMultipleEntryLoops(MachineFunction &MF,
74950a13cfSDan Gohman                                         const MachineLoopInfo &MLI) {
75950a13cfSDan Gohman   SmallPtrSet<MachineBasicBlock *, 8> InSet;
76950a13cfSDan Gohman   for (scc_iterator<MachineFunction *> I = scc_begin(&MF), E = scc_end(&MF);
77950a13cfSDan Gohman        I != E; ++I) {
78950a13cfSDan Gohman     const std::vector<MachineBasicBlock *> &CurrentSCC = *I;
79950a13cfSDan Gohman 
80950a13cfSDan Gohman     // Skip trivial SCCs.
81950a13cfSDan Gohman     if (CurrentSCC.size() == 1)
82950a13cfSDan Gohman       continue;
83950a13cfSDan Gohman 
84950a13cfSDan Gohman     InSet.insert(CurrentSCC.begin(), CurrentSCC.end());
85950a13cfSDan Gohman     MachineBasicBlock *Header = nullptr;
86950a13cfSDan Gohman     for (MachineBasicBlock *MBB : CurrentSCC) {
87950a13cfSDan Gohman       for (MachineBasicBlock *Pred : MBB->predecessors()) {
88950a13cfSDan Gohman         if (InSet.count(Pred))
89950a13cfSDan Gohman           continue;
90950a13cfSDan Gohman         if (!Header) {
91950a13cfSDan Gohman           Header = MBB;
92950a13cfSDan Gohman           break;
93950a13cfSDan Gohman         }
94950a13cfSDan Gohman         // TODO: Implement multiple-entry loops.
95950a13cfSDan Gohman         report_fatal_error("multiple-entry loops are not supported yet");
96950a13cfSDan Gohman       }
97950a13cfSDan Gohman     }
98950a13cfSDan Gohman     assert(MLI.isLoopHeader(Header));
99950a13cfSDan Gohman 
100950a13cfSDan Gohman     InSet.clear();
101950a13cfSDan Gohman   }
102950a13cfSDan Gohman }
103950a13cfSDan Gohman 
1048fe7e86bSDan Gohman /// Return the "bottom" block of a loop. This differs from
1058fe7e86bSDan Gohman /// MachineLoop::getBottomBlock in that it works even if the loop is
1068fe7e86bSDan Gohman /// discontiguous.
1078fe7e86bSDan Gohman static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) {
1088fe7e86bSDan Gohman   MachineBasicBlock *Bottom = Loop->getHeader();
1098fe7e86bSDan Gohman   for (MachineBasicBlock *MBB : Loop->blocks())
1108fe7e86bSDan Gohman     if (MBB->getNumber() > Bottom->getNumber())
1118fe7e86bSDan Gohman       Bottom = MBB;
1128fe7e86bSDan Gohman   return Bottom;
1138fe7e86bSDan Gohman }
1148fe7e86bSDan Gohman 
115*442bfcecSDan Gohman static void MaybeUpdateTerminator(MachineBasicBlock *MBB) {
116*442bfcecSDan Gohman #ifndef NDEBUG
117*442bfcecSDan Gohman   bool AnyBarrier = false;
118*442bfcecSDan Gohman #endif
119*442bfcecSDan Gohman   bool AllAnalyzable = true;
120*442bfcecSDan Gohman   for (const MachineInstr &Term : MBB->terminators()) {
121*442bfcecSDan Gohman #ifndef NDEBUG
122*442bfcecSDan Gohman     AnyBarrier |= Term.isBarrier();
123*442bfcecSDan Gohman #endif
124*442bfcecSDan Gohman     AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch();
125*442bfcecSDan Gohman   }
126*442bfcecSDan Gohman   assert((AnyBarrier || AllAnalyzable) &&
127*442bfcecSDan Gohman          "AnalyzeBranch needs to analyze any block with a fallthrough");
128*442bfcecSDan Gohman   if (AllAnalyzable)
129*442bfcecSDan Gohman     MBB->updateTerminator();
130*442bfcecSDan Gohman }
131950a13cfSDan Gohman 
132*442bfcecSDan Gohman namespace {
133*442bfcecSDan Gohman /// Sort blocks by their number.
134*442bfcecSDan Gohman struct CompareBlockNumbers {
135*442bfcecSDan Gohman   bool operator()(const MachineBasicBlock *A,
136*442bfcecSDan Gohman                   const MachineBasicBlock *B) const {
137*442bfcecSDan Gohman     return A->getNumber() > B->getNumber();
138*442bfcecSDan Gohman   }
139*442bfcecSDan Gohman };
140*442bfcecSDan Gohman /// Sort blocks by their number in the opposite order..
141*442bfcecSDan Gohman struct CompareBlockNumbersBackwards {
142*442bfcecSDan Gohman   bool operator()(const MachineBasicBlock *A,
143*442bfcecSDan Gohman                   const MachineBasicBlock *B) const {
144*442bfcecSDan Gohman     return A->getNumber() < B->getNumber();
145*442bfcecSDan Gohman   }
146*442bfcecSDan Gohman };
147*442bfcecSDan Gohman /// Bookkeeping for a loop to help ensure that we don't mix blocks not dominated
148*442bfcecSDan Gohman /// by the loop header among the loop's blocks.
149*442bfcecSDan Gohman struct Entry {
150*442bfcecSDan Gohman   const MachineLoop *Loop;
151*442bfcecSDan Gohman   unsigned NumBlocksLeft;
152950a13cfSDan Gohman 
153*442bfcecSDan Gohman   /// List of blocks not dominated by Loop's header that are deferred until
154*442bfcecSDan Gohman   /// after all of Loop's blocks have been seen.
155*442bfcecSDan Gohman   std::vector<MachineBasicBlock *> Deferred;
156*442bfcecSDan Gohman 
157*442bfcecSDan Gohman   explicit Entry(const MachineLoop *L)
158*442bfcecSDan Gohman       : Loop(L), NumBlocksLeft(L->getNumBlocks()) {}
159*442bfcecSDan Gohman };
160*442bfcecSDan Gohman }
161*442bfcecSDan Gohman 
162*442bfcecSDan Gohman /// Sort the blocks, taking special care to make sure that loops are not
163*442bfcecSDan Gohman /// interrupted by blocks not dominated by their header.
164*442bfcecSDan Gohman /// TODO: There are many opportunities for improving the heuristics here.
165*442bfcecSDan Gohman /// Explore them.
166*442bfcecSDan Gohman static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI,
167*442bfcecSDan Gohman                        const MachineDominatorTree &MDT) {
168*442bfcecSDan Gohman   // Prepare for a topological sort: Record the number of predecessors each
169*442bfcecSDan Gohman   // block has, ignoring loop backedges.
170*442bfcecSDan Gohman   MF.RenumberBlocks();
171*442bfcecSDan Gohman   SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0);
172*442bfcecSDan Gohman   for (MachineBasicBlock &MBB : MF) {
173*442bfcecSDan Gohman     unsigned N = MBB.pred_size();
174*442bfcecSDan Gohman     if (MachineLoop *L = MLI.getLoopFor(&MBB))
175*442bfcecSDan Gohman       if (L->getHeader() == &MBB)
176*442bfcecSDan Gohman         for (const MachineBasicBlock *Pred : MBB.predecessors())
177*442bfcecSDan Gohman           if (L->contains(Pred))
178*442bfcecSDan Gohman             --N;
179*442bfcecSDan Gohman     NumPredsLeft[MBB.getNumber()] = N;
180*442bfcecSDan Gohman   }
181*442bfcecSDan Gohman 
182*442bfcecSDan Gohman   // Topological sort the CFG, with additional constraints:
183*442bfcecSDan Gohman   //  - Between a loop header and the last block in the loop, there can be
184*442bfcecSDan Gohman   //    no blocks not dominated by the loop header.
185*442bfcecSDan Gohman   //  - It's desirable to preserve the original block order when possible.
186*442bfcecSDan Gohman   // We use two ready lists; Preferred and Ready. Preferred has recently
187*442bfcecSDan Gohman   // processed sucessors, to help preserve block sequences from the original
188*442bfcecSDan Gohman   // order. Ready has the remaining ready blocks.
189*442bfcecSDan Gohman   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
190*442bfcecSDan Gohman                 CompareBlockNumbers>
191*442bfcecSDan Gohman       Preferred;
192*442bfcecSDan Gohman   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
193*442bfcecSDan Gohman                 CompareBlockNumbersBackwards>
194*442bfcecSDan Gohman       Ready;
195*442bfcecSDan Gohman   SmallVector<Entry, 4> Loops;
196*442bfcecSDan Gohman   for (MachineBasicBlock *MBB = &MF.front();;) {
197*442bfcecSDan Gohman     const MachineLoop *L = MLI.getLoopFor(MBB);
198*442bfcecSDan Gohman     if (L) {
199*442bfcecSDan Gohman       // If MBB is a loop header, add it to the active loop list. We can't put
200*442bfcecSDan Gohman       // any blocks that it doesn't dominate until we see the end of the loop.
201*442bfcecSDan Gohman       if (L->getHeader() == MBB)
202*442bfcecSDan Gohman         Loops.push_back(Entry(L));
203*442bfcecSDan Gohman       // For each active loop the block is in, decrement the count. If MBB is
204*442bfcecSDan Gohman       // the last block in an active loop, take it off the list and pick up any
205*442bfcecSDan Gohman       // blocks deferred because the header didn't dominate them.
206*442bfcecSDan Gohman       for (Entry &E : Loops)
207*442bfcecSDan Gohman         if (E.Loop->contains(MBB) && --E.NumBlocksLeft == 0)
208*442bfcecSDan Gohman           for (auto DeferredBlock : E.Deferred)
209*442bfcecSDan Gohman             Ready.push(DeferredBlock);
210*442bfcecSDan Gohman       while (!Loops.empty() && Loops.back().NumBlocksLeft == 0)
211*442bfcecSDan Gohman         Loops.pop_back();
212*442bfcecSDan Gohman     }
213*442bfcecSDan Gohman     // The main topological sort logic.
214*442bfcecSDan Gohman     for (MachineBasicBlock *Succ : MBB->successors()) {
215*442bfcecSDan Gohman       // Ignore backedges.
216*442bfcecSDan Gohman       if (MachineLoop *SuccL = MLI.getLoopFor(Succ))
217*442bfcecSDan Gohman         if (SuccL->getHeader() == Succ && SuccL->contains(MBB))
218*442bfcecSDan Gohman           continue;
219*442bfcecSDan Gohman       // Decrement the predecessor count. If it's now zero, it's ready.
220*442bfcecSDan Gohman       if (--NumPredsLeft[Succ->getNumber()] == 0)
221*442bfcecSDan Gohman         Preferred.push(Succ);
222*442bfcecSDan Gohman     }
223*442bfcecSDan Gohman     // Determine the block to follow MBB. First try to find a preferred block,
224*442bfcecSDan Gohman     // to preserve the original block order when possible.
225*442bfcecSDan Gohman     MachineBasicBlock *Next = nullptr;
226*442bfcecSDan Gohman     while (!Preferred.empty()) {
227*442bfcecSDan Gohman       Next = Preferred.top();
228*442bfcecSDan Gohman       Preferred.pop();
229*442bfcecSDan Gohman       // If X isn't dominated by the top active loop header, defer it until that
230*442bfcecSDan Gohman       // loop is done.
231*442bfcecSDan Gohman       if (!Loops.empty() &&
232*442bfcecSDan Gohman           !MDT.dominates(Loops.back().Loop->getHeader(), Next)) {
233*442bfcecSDan Gohman         Loops.back().Deferred.push_back(Next);
234*442bfcecSDan Gohman         Next = nullptr;
235950a13cfSDan Gohman         continue;
236950a13cfSDan Gohman       }
237*442bfcecSDan Gohman       // If Next was originally ordered before MBB, and it isn't because it was
238*442bfcecSDan Gohman       // loop-rotated above the header, it's not preferred.
239*442bfcecSDan Gohman       if (Next->getNumber() < MBB->getNumber() &&
240*442bfcecSDan Gohman           (!L || !L->contains(Next) ||
241*442bfcecSDan Gohman            L->getHeader()->getNumber() < Next->getNumber())) {
242*442bfcecSDan Gohman         Ready.push(Next);
243*442bfcecSDan Gohman         Next = nullptr;
244*442bfcecSDan Gohman         continue;
245*442bfcecSDan Gohman       }
246950a13cfSDan Gohman       break;
247950a13cfSDan Gohman     }
248*442bfcecSDan Gohman     // If we didn't find a suitable block in the Preferred list, check the
249*442bfcecSDan Gohman     // general Ready list.
250*442bfcecSDan Gohman     if (!Next) {
251*442bfcecSDan Gohman       // If there are no more blocks to process, we're done.
252*442bfcecSDan Gohman       if (Ready.empty()) {
253*442bfcecSDan Gohman         MaybeUpdateTerminator(MBB);
254*442bfcecSDan Gohman         break;
255*442bfcecSDan Gohman       }
256*442bfcecSDan Gohman       for (;;) {
257*442bfcecSDan Gohman         Next = Ready.top();
258*442bfcecSDan Gohman         Ready.pop();
259*442bfcecSDan Gohman         // If Next isn't dominated by the top active loop header, defer it until
260*442bfcecSDan Gohman         // that loop is done.
261*442bfcecSDan Gohman         if (!Loops.empty() &&
262*442bfcecSDan Gohman             !MDT.dominates(Loops.back().Loop->getHeader(), Next)) {
263*442bfcecSDan Gohman           Loops.back().Deferred.push_back(Next);
264*442bfcecSDan Gohman           continue;
265*442bfcecSDan Gohman         }
266*442bfcecSDan Gohman         break;
267*442bfcecSDan Gohman       }
268*442bfcecSDan Gohman     }
269*442bfcecSDan Gohman     // Move the next block into place and iterate.
270*442bfcecSDan Gohman     Next->moveAfter(MBB);
271*442bfcecSDan Gohman     MaybeUpdateTerminator(MBB);
272*442bfcecSDan Gohman     MBB = Next;
273*442bfcecSDan Gohman   }
274*442bfcecSDan Gohman   assert(Loops.empty() && "Active loop list not finished");
275950a13cfSDan Gohman   MF.RenumberBlocks();
276950a13cfSDan Gohman 
277950a13cfSDan Gohman #ifndef NDEBUG
2788fe7e86bSDan Gohman   SmallSetVector<MachineLoop *, 8> OnStack;
2798fe7e86bSDan Gohman 
2808fe7e86bSDan Gohman   // Insert a sentinel representing the degenerate loop that starts at the
2818fe7e86bSDan Gohman   // function entry block and includes the entire function as a "loop" that
2828fe7e86bSDan Gohman   // executes once.
2838fe7e86bSDan Gohman   OnStack.insert(nullptr);
2848fe7e86bSDan Gohman 
2858fe7e86bSDan Gohman   for (auto &MBB : MF) {
2868fe7e86bSDan Gohman     assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
2878fe7e86bSDan Gohman 
2888fe7e86bSDan Gohman     MachineLoop *Loop = MLI.getLoopFor(&MBB);
2898fe7e86bSDan Gohman     if (Loop && &MBB == Loop->getHeader()) {
2908fe7e86bSDan Gohman       // Loop header. The loop predecessor should be sorted above, and the other
2918fe7e86bSDan Gohman       // predecessors should be backedges below.
2928fe7e86bSDan Gohman       for (auto Pred : MBB.predecessors())
2938fe7e86bSDan Gohman         assert(
2948fe7e86bSDan Gohman             (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) &&
2958fe7e86bSDan Gohman             "Loop header predecessors must be loop predecessors or backedges");
2968fe7e86bSDan Gohman       assert(OnStack.insert(Loop) && "Loops should be declared at most once.");
29732807932SDan Gohman     } else {
2988fe7e86bSDan Gohman       // Not a loop header. All predecessors should be sorted above.
299950a13cfSDan Gohman       for (auto Pred : MBB.predecessors())
300950a13cfSDan Gohman         assert(Pred->getNumber() < MBB.getNumber() &&
3018fe7e86bSDan Gohman                "Non-loop-header predecessors should be topologically sorted");
3028fe7e86bSDan Gohman       assert(OnStack.count(MLI.getLoopFor(&MBB)) &&
3038fe7e86bSDan Gohman              "Blocks must be nested in their loops");
304950a13cfSDan Gohman     }
3058fe7e86bSDan Gohman     while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back()))
3068fe7e86bSDan Gohman       OnStack.pop_back();
3078fe7e86bSDan Gohman   }
3088fe7e86bSDan Gohman   assert(OnStack.pop_back_val() == nullptr &&
3098fe7e86bSDan Gohman          "The function entry block shouldn't actually be a loop header");
3108fe7e86bSDan Gohman   assert(OnStack.empty() &&
3118fe7e86bSDan Gohman          "Control flow stack pushes and pops should be balanced.");
312950a13cfSDan Gohman #endif
313950a13cfSDan Gohman }
314950a13cfSDan Gohman 
315b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
316b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
317b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
318b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
319b3aa1ecaSDan Gohman /// explicit mentions.
32035e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred,
32135e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
322b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
323b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
324b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
325b3aa1ecaSDan Gohman         return true;
326b3aa1ecaSDan Gohman   return false;
327b3aa1ecaSDan Gohman }
328b3aa1ecaSDan Gohman 
329ed0f1138SDan Gohman /// Test whether MI is a child of some other node in an expression tree.
330ed0f1138SDan Gohman static bool IsChild(const MachineInstr *MI,
331ed0f1138SDan Gohman                     const WebAssemblyFunctionInfo &MFI) {
332ed0f1138SDan Gohman   if (MI->getNumOperands() == 0)
333ed0f1138SDan Gohman     return false;
334ed0f1138SDan Gohman   const MachineOperand &MO = MI->getOperand(0);
335ed0f1138SDan Gohman   if (!MO.isReg() || MO.isImplicit() || !MO.isDef())
336ed0f1138SDan Gohman     return false;
337ed0f1138SDan Gohman   unsigned Reg = MO.getReg();
338ed0f1138SDan Gohman   return TargetRegisterInfo::isVirtualRegister(Reg) &&
339ed0f1138SDan Gohman          MFI.isVRegStackified(Reg);
340ed0f1138SDan Gohman }
341ed0f1138SDan Gohman 
34232807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
3438fe7e86bSDan Gohman static void PlaceBlockMarker(MachineBasicBlock &MBB, MachineFunction &MF,
3448fe7e86bSDan Gohman                              SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
34532807932SDan Gohman                              const WebAssemblyInstrInfo &TII,
3468fe7e86bSDan Gohman                              const MachineLoopInfo &MLI,
347ed0f1138SDan Gohman                              MachineDominatorTree &MDT,
348ed0f1138SDan Gohman                              WebAssemblyFunctionInfo &MFI) {
3498fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
3508fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
3518fe7e86bSDan Gohman   // which reduces overall stack height.
35232807932SDan Gohman   MachineBasicBlock *Header = nullptr;
35332807932SDan Gohman   bool IsBranchedTo = false;
35432807932SDan Gohman   int MBBNumber = MBB.getNumber();
35532807932SDan Gohman   for (MachineBasicBlock *Pred : MBB.predecessors())
35632807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
35732807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
358b3aa1ecaSDan Gohman       if (ExplicitlyBranchesTo(Pred, &MBB))
35932807932SDan Gohman         IsBranchedTo = true;
36032807932SDan Gohman     }
36132807932SDan Gohman   if (!Header)
36232807932SDan Gohman     return;
36332807932SDan Gohman   if (!IsBranchedTo)
36432807932SDan Gohman     return;
36532807932SDan Gohman 
3668fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
3678fe7e86bSDan Gohman   MachineBasicBlock *LayoutPred = &*prev(MachineFunction::iterator(&MBB));
3688fe7e86bSDan Gohman 
3698fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
3708fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
3718fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
3728fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
3738fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
3748fe7e86bSDan Gohman         // Skip over an intervening scope.
3758fe7e86bSDan Gohman         I = next(MachineFunction::iterator(ScopeTop));
3768fe7e86bSDan Gohman       } else {
3778fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
3788fe7e86bSDan Gohman         Header = ScopeTop;
3798fe7e86bSDan Gohman         break;
3808fe7e86bSDan Gohman       }
3818fe7e86bSDan Gohman     }
3828fe7e86bSDan Gohman   }
3838fe7e86bSDan Gohman 
3848fe7e86bSDan Gohman   // If there's a loop which ends just before MBB which contains Header, we can
3858fe7e86bSDan Gohman   // reuse its label instead of inserting a new BLOCK.
3868fe7e86bSDan Gohman   for (MachineLoop *Loop = MLI.getLoopFor(LayoutPred);
3878fe7e86bSDan Gohman        Loop && Loop->contains(LayoutPred); Loop = Loop->getParentLoop())
3888fe7e86bSDan Gohman     if (Loop && LoopBottom(Loop) == LayoutPred && Loop->contains(Header))
3898fe7e86bSDan Gohman       return;
3908fe7e86bSDan Gohman 
3918fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
39232807932SDan Gohman   MachineBasicBlock::iterator InsertPos;
39332807932SDan Gohman   MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
3948fe7e86bSDan Gohman   if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
3958fe7e86bSDan Gohman     // Header is the header of a loop that does not lexically contain MBB, so
396a187ab2aSDan Gohman     // the BLOCK needs to be above the LOOP, after any END constructs.
39732807932SDan Gohman     InsertPos = Header->begin();
398a187ab2aSDan Gohman     while (InsertPos->getOpcode() != WebAssembly::LOOP)
399a187ab2aSDan Gohman       ++InsertPos;
40032807932SDan Gohman   } else {
4018887d1faSDan Gohman     // Otherwise, insert the BLOCK as late in Header as we can, but before the
4028887d1faSDan Gohman     // beginning of the local expression tree and any nested BLOCKs.
40332807932SDan Gohman     InsertPos = Header->getFirstTerminator();
404*442bfcecSDan Gohman     while (InsertPos != Header->begin() && IsChild(prev(InsertPos), MFI) &&
4051d68e80fSDan Gohman            prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
4061d68e80fSDan Gohman            prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
4071d68e80fSDan Gohman            prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
40832807932SDan Gohman       --InsertPos;
40932807932SDan Gohman   }
41032807932SDan Gohman 
4118fe7e86bSDan Gohman   // Add the BLOCK.
4121d68e80fSDan Gohman   BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK));
4131d68e80fSDan Gohman 
4141d68e80fSDan Gohman   // Mark the end of the block.
4151d68e80fSDan Gohman   InsertPos = MBB.begin();
4161d68e80fSDan Gohman   while (InsertPos != MBB.end() &&
4171d68e80fSDan Gohman          InsertPos->getOpcode() == WebAssembly::END_LOOP)
4181d68e80fSDan Gohman     ++InsertPos;
4191d68e80fSDan Gohman   BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK));
4208fe7e86bSDan Gohman 
4218fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
4228fe7e86bSDan Gohman   int Number = MBB.getNumber();
4238fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
4248fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
4258fe7e86bSDan Gohman     ScopeTops[Number] = Header;
426950a13cfSDan Gohman }
427950a13cfSDan Gohman 
4288fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
4291d68e80fSDan Gohman static void PlaceLoopMarker(
4301d68e80fSDan Gohman     MachineBasicBlock &MBB, MachineFunction &MF,
4318fe7e86bSDan Gohman     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
4321d68e80fSDan Gohman     DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops,
4331d68e80fSDan Gohman     const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
4348fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
4358fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
4368fe7e86bSDan Gohman     return;
4378fe7e86bSDan Gohman 
4388fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
4398fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
4408fe7e86bSDan Gohman   MachineBasicBlock *Bottom = LoopBottom(Loop);
441e3e4a5ffSDan Gohman   auto Iter = next(MachineFunction::iterator(Bottom));
442e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
443f6857223SDan Gohman     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
444f6857223SDan Gohman     // Give it a fake predecessor so that AsmPrinter prints its label.
445f6857223SDan Gohman     Label->addSuccessor(Label);
446f6857223SDan Gohman     MF.push_back(Label);
447e3e4a5ffSDan Gohman     Iter = next(MachineFunction::iterator(Bottom));
448e3e4a5ffSDan Gohman   }
4498fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
450f6857223SDan Gohman 
4511d68e80fSDan Gohman   // Mark the beginning of the loop (after the end of any existing loop that
4521d68e80fSDan Gohman   // ends here).
4531d68e80fSDan Gohman   auto InsertPos = MBB.begin();
4541d68e80fSDan Gohman   while (InsertPos != MBB.end() &&
4551d68e80fSDan Gohman          InsertPos->getOpcode() == WebAssembly::END_LOOP)
4561d68e80fSDan Gohman     ++InsertPos;
4571d68e80fSDan Gohman   BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP));
4581d68e80fSDan Gohman 
4591d68e80fSDan Gohman   // Mark the end of the loop.
4601d68e80fSDan Gohman   MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(),
4611d68e80fSDan Gohman                               TII.get(WebAssembly::END_LOOP));
4621d68e80fSDan Gohman   LoopTops[End] = &MBB;
4638fe7e86bSDan Gohman 
4648fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4658fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
466*442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
4678fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
4688fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
469e3e4a5ffSDan Gohman }
470950a13cfSDan Gohman 
4711d68e80fSDan Gohman static unsigned
4721d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
4731d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
4741d68e80fSDan Gohman   unsigned Depth = 0;
4751d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
4761d68e80fSDan Gohman     if (X == MBB)
4771d68e80fSDan Gohman       break;
4781d68e80fSDan Gohman     ++Depth;
4791d68e80fSDan Gohman   }
4801d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
4811d68e80fSDan Gohman   return Depth;
4821d68e80fSDan Gohman }
4831d68e80fSDan Gohman 
4848fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places.
4858fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
4868fe7e86bSDan Gohman                          const WebAssemblyInstrInfo &TII,
487ed0f1138SDan Gohman                          MachineDominatorTree &MDT,
488ed0f1138SDan Gohman                          WebAssemblyFunctionInfo &MFI) {
4898fe7e86bSDan Gohman   // For each block whose label represents the end of a scope, record the block
4908fe7e86bSDan Gohman   // which holds the beginning of the scope. This will allow us to quickly skip
4918fe7e86bSDan Gohman   // over scoped regions when walking blocks. We allocate one more than the
4928fe7e86bSDan Gohman   // number of blocks in the function to accommodate for the possible fake block
4938fe7e86bSDan Gohman   // we may insert at the end.
4948fe7e86bSDan Gohman   SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
4958fe7e86bSDan Gohman 
4961d68e80fSDan Gohman   // For eacn LOOP_END, the corresponding LOOP.
4971d68e80fSDan Gohman   DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops;
4981d68e80fSDan Gohman 
4998fe7e86bSDan Gohman   for (auto &MBB : MF) {
5008fe7e86bSDan Gohman     // Place the LOOP for MBB if MBB is the header of a loop.
5011d68e80fSDan Gohman     PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
5028fe7e86bSDan Gohman 
50332807932SDan Gohman     // Place the BLOCK for MBB if MBB is branched to from above.
504ed0f1138SDan Gohman     PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT, MFI);
505950a13cfSDan Gohman   }
506950a13cfSDan Gohman 
5071d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
5081d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
5091d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
5101d68e80fSDan Gohman     for (auto &MI : reverse(MBB)) {
5111d68e80fSDan Gohman       switch (MI.getOpcode()) {
5121d68e80fSDan Gohman       case WebAssembly::BLOCK:
5131d68e80fSDan Gohman         assert(ScopeTops[Stack.back()->getNumber()] == &MBB &&
5141d68e80fSDan Gohman                "Block should be balanced");
5151d68e80fSDan Gohman         Stack.pop_back();
5161d68e80fSDan Gohman         break;
5171d68e80fSDan Gohman       case WebAssembly::LOOP:
5181d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
5191d68e80fSDan Gohman         Stack.pop_back();
5201d68e80fSDan Gohman         Stack.pop_back();
5211d68e80fSDan Gohman         break;
5221d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
5231d68e80fSDan Gohman         Stack.push_back(&MBB);
5241d68e80fSDan Gohman         break;
5251d68e80fSDan Gohman       case WebAssembly::END_LOOP:
5261d68e80fSDan Gohman         Stack.push_back(&MBB);
5271d68e80fSDan Gohman         Stack.push_back(LoopTops[&MI]);
5281d68e80fSDan Gohman         break;
5291d68e80fSDan Gohman       default:
5301d68e80fSDan Gohman         if (MI.isTerminator()) {
5311d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
5321d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
5331d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
5341d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
5351d68e80fSDan Gohman           for (auto MO : Ops) {
5361d68e80fSDan Gohman             if (MO.isMBB())
5371d68e80fSDan Gohman               MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
5381d68e80fSDan Gohman             MI.addOperand(MF, MO);
53932807932SDan Gohman           }
5401d68e80fSDan Gohman         }
5411d68e80fSDan Gohman         break;
5421d68e80fSDan Gohman       }
5431d68e80fSDan Gohman     }
5441d68e80fSDan Gohman   }
5451d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
5461d68e80fSDan Gohman }
54732807932SDan Gohman 
548950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
549950a13cfSDan Gohman   DEBUG(dbgs() << "********** CFG Stackifying **********\n"
550950a13cfSDan Gohman                   "********** Function: "
551950a13cfSDan Gohman                << MF.getName() << '\n');
552950a13cfSDan Gohman 
553950a13cfSDan Gohman   const auto &MLI = getAnalysis<MachineLoopInfo>();
55432807932SDan Gohman   auto &MDT = getAnalysis<MachineDominatorTree>();
5559c3bf318SDerek Schuff   // Liveness is not tracked for EXPR_STACK physreg.
556950a13cfSDan Gohman   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
557ed0f1138SDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
5589c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
559950a13cfSDan Gohman 
560*442bfcecSDan Gohman   // Sorting needs all loops to be single-entry.
561950a13cfSDan Gohman   EliminateMultipleEntryLoops(MF, MLI);
562950a13cfSDan Gohman 
563*442bfcecSDan Gohman   // Sort the blocks, with contiguous loops.
564*442bfcecSDan Gohman   SortBlocks(MF, MLI, MDT);
565950a13cfSDan Gohman 
566950a13cfSDan Gohman   // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
567ed0f1138SDan Gohman   PlaceMarkers(MF, MLI, TII, MDT, MFI);
56832807932SDan Gohman 
569950a13cfSDan Gohman   return true;
570950a13cfSDan Gohman }
571