1 //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements a CFG stacking pass.
12 ///
13 /// This pass reorders the blocks in a function to put them into topological
14 /// order, ignoring loop backedges, and without any loop being interrupted
15 /// by a block not dominated by the loop header, with special care to keep the
16 /// order as similar as possible to the original order.
17 ///
18 /// Then, it inserts BLOCK and LOOP markers to mark the start of scopes, since
19 /// scope boundaries serve as the labels for WebAssembly's control transfers.
20 ///
21 /// This is sufficient to convert arbitrary CFGs into a form that works on
22 /// WebAssembly, provided that all loops are single-entry.
23 ///
24 //===----------------------------------------------------------------------===//
25 
26 #include "WebAssembly.h"
27 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
28 #include "WebAssemblyMachineFunctionInfo.h"
29 #include "WebAssemblySubtarget.h"
30 #include "llvm/ADT/PriorityQueue.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/CodeGen/MachineDominators.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "wasm-cfg-stackify"
43 
44 namespace {
45 class WebAssemblyCFGStackify final : public MachineFunctionPass {
46   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
47 
48   void getAnalysisUsage(AnalysisUsage &AU) const override {
49     AU.setPreservesCFG();
50     AU.addRequired<MachineDominatorTree>();
51     AU.addPreserved<MachineDominatorTree>();
52     AU.addRequired<MachineLoopInfo>();
53     AU.addPreserved<MachineLoopInfo>();
54     MachineFunctionPass::getAnalysisUsage(AU);
55   }
56 
57   bool runOnMachineFunction(MachineFunction &MF) override;
58 
59 public:
60   static char ID; // Pass identification, replacement for typeid
61   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
62 };
63 } // end anonymous namespace
64 
65 char WebAssemblyCFGStackify::ID = 0;
66 FunctionPass *llvm::createWebAssemblyCFGStackify() {
67   return new WebAssemblyCFGStackify();
68 }
69 
70 /// Return the "bottom" block of a loop. This differs from
71 /// MachineLoop::getBottomBlock in that it works even if the loop is
72 /// discontiguous.
73 static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) {
74   MachineBasicBlock *Bottom = Loop->getHeader();
75   for (MachineBasicBlock *MBB : Loop->blocks())
76     if (MBB->getNumber() > Bottom->getNumber())
77       Bottom = MBB;
78   return Bottom;
79 }
80 
81 static void MaybeUpdateTerminator(MachineBasicBlock *MBB) {
82 #ifndef NDEBUG
83   bool AnyBarrier = false;
84 #endif
85   bool AllAnalyzable = true;
86   for (const MachineInstr &Term : MBB->terminators()) {
87 #ifndef NDEBUG
88     AnyBarrier |= Term.isBarrier();
89 #endif
90     AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch();
91   }
92   assert((AnyBarrier || AllAnalyzable) &&
93          "AnalyzeBranch needs to analyze any block with a fallthrough");
94   if (AllAnalyzable)
95     MBB->updateTerminator();
96 }
97 
98 namespace {
99 /// Sort blocks by their number.
100 struct CompareBlockNumbers {
101   bool operator()(const MachineBasicBlock *A,
102                   const MachineBasicBlock *B) const {
103     return A->getNumber() > B->getNumber();
104   }
105 };
106 /// Sort blocks by their number in the opposite order..
107 struct CompareBlockNumbersBackwards {
108   bool operator()(const MachineBasicBlock *A,
109                   const MachineBasicBlock *B) const {
110     return A->getNumber() < B->getNumber();
111   }
112 };
113 /// Bookkeeping for a loop to help ensure that we don't mix blocks not dominated
114 /// by the loop header among the loop's blocks.
115 struct Entry {
116   const MachineLoop *Loop;
117   unsigned NumBlocksLeft;
118 
119   /// List of blocks not dominated by Loop's header that are deferred until
120   /// after all of Loop's blocks have been seen.
121   std::vector<MachineBasicBlock *> Deferred;
122 
123   explicit Entry(const MachineLoop *L)
124       : Loop(L), NumBlocksLeft(L->getNumBlocks()) {}
125 };
126 }
127 
128 /// Sort the blocks, taking special care to make sure that loops are not
129 /// interrupted by blocks not dominated by their header.
130 /// TODO: There are many opportunities for improving the heuristics here.
131 /// Explore them.
132 static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI,
133                        const MachineDominatorTree &MDT) {
134   // Prepare for a topological sort: Record the number of predecessors each
135   // block has, ignoring loop backedges.
136   MF.RenumberBlocks();
137   SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0);
138   for (MachineBasicBlock &MBB : MF) {
139     unsigned N = MBB.pred_size();
140     if (MachineLoop *L = MLI.getLoopFor(&MBB))
141       if (L->getHeader() == &MBB)
142         for (const MachineBasicBlock *Pred : MBB.predecessors())
143           if (L->contains(Pred))
144             --N;
145     NumPredsLeft[MBB.getNumber()] = N;
146   }
147 
148   // Topological sort the CFG, with additional constraints:
149   //  - Between a loop header and the last block in the loop, there can be
150   //    no blocks not dominated by the loop header.
151   //  - It's desirable to preserve the original block order when possible.
152   // We use two ready lists; Preferred and Ready. Preferred has recently
153   // processed sucessors, to help preserve block sequences from the original
154   // order. Ready has the remaining ready blocks.
155   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
156                 CompareBlockNumbers>
157       Preferred;
158   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
159                 CompareBlockNumbersBackwards>
160       Ready;
161   SmallVector<Entry, 4> Loops;
162   for (MachineBasicBlock *MBB = &MF.front();;) {
163     const MachineLoop *L = MLI.getLoopFor(MBB);
164     if (L) {
165       // If MBB is a loop header, add it to the active loop list. We can't put
166       // any blocks that it doesn't dominate until we see the end of the loop.
167       if (L->getHeader() == MBB)
168         Loops.push_back(Entry(L));
169       // For each active loop the block is in, decrement the count. If MBB is
170       // the last block in an active loop, take it off the list and pick up any
171       // blocks deferred because the header didn't dominate them.
172       for (Entry &E : Loops)
173         if (E.Loop->contains(MBB) && --E.NumBlocksLeft == 0)
174           for (auto DeferredBlock : E.Deferred)
175             Ready.push(DeferredBlock);
176       while (!Loops.empty() && Loops.back().NumBlocksLeft == 0)
177         Loops.pop_back();
178     }
179     // The main topological sort logic.
180     for (MachineBasicBlock *Succ : MBB->successors()) {
181       // Ignore backedges.
182       if (MachineLoop *SuccL = MLI.getLoopFor(Succ))
183         if (SuccL->getHeader() == Succ && SuccL->contains(MBB))
184           continue;
185       // Decrement the predecessor count. If it's now zero, it's ready.
186       if (--NumPredsLeft[Succ->getNumber()] == 0)
187         Preferred.push(Succ);
188     }
189     // Determine the block to follow MBB. First try to find a preferred block,
190     // to preserve the original block order when possible.
191     MachineBasicBlock *Next = nullptr;
192     while (!Preferred.empty()) {
193       Next = Preferred.top();
194       Preferred.pop();
195       // If X isn't dominated by the top active loop header, defer it until that
196       // loop is done.
197       if (!Loops.empty() &&
198           !MDT.dominates(Loops.back().Loop->getHeader(), Next)) {
199         Loops.back().Deferred.push_back(Next);
200         Next = nullptr;
201         continue;
202       }
203       // If Next was originally ordered before MBB, and it isn't because it was
204       // loop-rotated above the header, it's not preferred.
205       if (Next->getNumber() < MBB->getNumber() &&
206           (!L || !L->contains(Next) ||
207            L->getHeader()->getNumber() < Next->getNumber())) {
208         Ready.push(Next);
209         Next = nullptr;
210         continue;
211       }
212       break;
213     }
214     // If we didn't find a suitable block in the Preferred list, check the
215     // general Ready list.
216     if (!Next) {
217       // If there are no more blocks to process, we're done.
218       if (Ready.empty()) {
219         MaybeUpdateTerminator(MBB);
220         break;
221       }
222       for (;;) {
223         Next = Ready.top();
224         Ready.pop();
225         // If Next isn't dominated by the top active loop header, defer it until
226         // that loop is done.
227         if (!Loops.empty() &&
228             !MDT.dominates(Loops.back().Loop->getHeader(), Next)) {
229           Loops.back().Deferred.push_back(Next);
230           continue;
231         }
232         break;
233       }
234     }
235     // Move the next block into place and iterate.
236     Next->moveAfter(MBB);
237     MaybeUpdateTerminator(MBB);
238     MBB = Next;
239   }
240   assert(Loops.empty() && "Active loop list not finished");
241   MF.RenumberBlocks();
242 
243 #ifndef NDEBUG
244   SmallSetVector<MachineLoop *, 8> OnStack;
245 
246   // Insert a sentinel representing the degenerate loop that starts at the
247   // function entry block and includes the entire function as a "loop" that
248   // executes once.
249   OnStack.insert(nullptr);
250 
251   for (auto &MBB : MF) {
252     assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
253 
254     MachineLoop *Loop = MLI.getLoopFor(&MBB);
255     if (Loop && &MBB == Loop->getHeader()) {
256       // Loop header. The loop predecessor should be sorted above, and the other
257       // predecessors should be backedges below.
258       for (auto Pred : MBB.predecessors())
259         assert(
260             (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) &&
261             "Loop header predecessors must be loop predecessors or backedges");
262       assert(OnStack.insert(Loop) && "Loops should be declared at most once.");
263     } else {
264       // Not a loop header. All predecessors should be sorted above.
265       for (auto Pred : MBB.predecessors())
266         assert(Pred->getNumber() < MBB.getNumber() &&
267                "Non-loop-header predecessors should be topologically sorted");
268       assert(OnStack.count(MLI.getLoopFor(&MBB)) &&
269              "Blocks must be nested in their loops");
270     }
271     while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back()))
272       OnStack.pop_back();
273   }
274   assert(OnStack.pop_back_val() == nullptr &&
275          "The function entry block shouldn't actually be a loop header");
276   assert(OnStack.empty() &&
277          "Control flow stack pushes and pops should be balanced.");
278 #endif
279 }
280 
281 /// Test whether Pred has any terminators explicitly branching to MBB, as
282 /// opposed to falling through. Note that it's possible (eg. in unoptimized
283 /// code) for a branch instruction to both branch to a block and fallthrough
284 /// to it, so we check the actual branch operands to see if there are any
285 /// explicit mentions.
286 static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred,
287                                  MachineBasicBlock *MBB) {
288   for (MachineInstr &MI : Pred->terminators())
289     for (MachineOperand &MO : MI.explicit_operands())
290       if (MO.isMBB() && MO.getMBB() == MBB)
291         return true;
292   return false;
293 }
294 
295 /// Test whether MI is a child of some other node in an expression tree.
296 static bool IsChild(const MachineInstr &MI,
297                     const WebAssemblyFunctionInfo &MFI) {
298   if (MI.getNumOperands() == 0)
299     return false;
300   const MachineOperand &MO = MI.getOperand(0);
301   if (!MO.isReg() || MO.isImplicit() || !MO.isDef())
302     return false;
303   unsigned Reg = MO.getReg();
304   return TargetRegisterInfo::isVirtualRegister(Reg) &&
305          MFI.isVRegStackified(Reg);
306 }
307 
308 /// Insert a BLOCK marker for branches to MBB (if needed).
309 static void PlaceBlockMarker(
310     MachineBasicBlock &MBB, MachineFunction &MF,
311     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
312     DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops,
313     const WebAssemblyInstrInfo &TII,
314     const MachineLoopInfo &MLI,
315     MachineDominatorTree &MDT,
316     WebAssemblyFunctionInfo &MFI) {
317   // First compute the nearest common dominator of all forward non-fallthrough
318   // predecessors so that we minimize the time that the BLOCK is on the stack,
319   // which reduces overall stack height.
320   MachineBasicBlock *Header = nullptr;
321   bool IsBranchedTo = false;
322   int MBBNumber = MBB.getNumber();
323   for (MachineBasicBlock *Pred : MBB.predecessors())
324     if (Pred->getNumber() < MBBNumber) {
325       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
326       if (ExplicitlyBranchesTo(Pred, &MBB))
327         IsBranchedTo = true;
328     }
329   if (!Header)
330     return;
331   if (!IsBranchedTo)
332     return;
333 
334   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
335   MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB));
336 
337   // If the nearest common dominator is inside a more deeply nested context,
338   // walk out to the nearest scope which isn't more deeply nested.
339   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
340     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
341       if (ScopeTop->getNumber() > Header->getNumber()) {
342         // Skip over an intervening scope.
343         I = std::next(MachineFunction::iterator(ScopeTop));
344       } else {
345         // We found a scope level at an appropriate depth.
346         Header = ScopeTop;
347         break;
348       }
349     }
350   }
351 
352   // Decide where in Header to put the BLOCK.
353   MachineBasicBlock::iterator InsertPos;
354   MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
355   if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
356     // Header is the header of a loop that does not lexically contain MBB, so
357     // the BLOCK needs to be above the LOOP, after any END constructs.
358     InsertPos = Header->begin();
359     while (InsertPos->getOpcode() == WebAssembly::END_BLOCK ||
360            InsertPos->getOpcode() == WebAssembly::END_LOOP)
361       ++InsertPos;
362   } else {
363     // Otherwise, insert the BLOCK as late in Header as we can, but before the
364     // beginning of the local expression tree and any nested BLOCKs.
365     InsertPos = Header->getFirstTerminator();
366     while (InsertPos != Header->begin() &&
367            IsChild(*std::prev(InsertPos), MFI) &&
368            std::prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
369            std::prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
370            std::prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
371       --InsertPos;
372   }
373 
374   // Add the BLOCK.
375   BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK));
376 
377   // Mark the end of the block.
378   InsertPos = MBB.begin();
379   while (InsertPos != MBB.end() &&
380          InsertPos->getOpcode() == WebAssembly::END_LOOP &&
381          LoopTops[&*InsertPos]->getNumber() >= Header->getNumber())
382     ++InsertPos;
383   BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK));
384 
385   // Track the farthest-spanning scope that ends at this point.
386   int Number = MBB.getNumber();
387   if (!ScopeTops[Number] ||
388       ScopeTops[Number]->getNumber() > Header->getNumber())
389     ScopeTops[Number] = Header;
390 }
391 
392 /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
393 static void PlaceLoopMarker(
394     MachineBasicBlock &MBB, MachineFunction &MF,
395     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
396     DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops,
397     const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
398   MachineLoop *Loop = MLI.getLoopFor(&MBB);
399   if (!Loop || Loop->getHeader() != &MBB)
400     return;
401 
402   // The operand of a LOOP is the first block after the loop. If the loop is the
403   // bottom of the function, insert a dummy block at the end.
404   MachineBasicBlock *Bottom = LoopBottom(Loop);
405   auto Iter = std::next(MachineFunction::iterator(Bottom));
406   if (Iter == MF.end()) {
407     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
408     // Give it a fake predecessor so that AsmPrinter prints its label.
409     Label->addSuccessor(Label);
410     MF.push_back(Label);
411     Iter = std::next(MachineFunction::iterator(Bottom));
412   }
413   MachineBasicBlock *AfterLoop = &*Iter;
414 
415   // Mark the beginning of the loop (after the end of any existing loop that
416   // ends here).
417   auto InsertPos = MBB.begin();
418   while (InsertPos != MBB.end() &&
419          InsertPos->getOpcode() == WebAssembly::END_LOOP)
420     ++InsertPos;
421   BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP));
422 
423   // Mark the end of the loop.
424   MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(),
425                               TII.get(WebAssembly::END_LOOP));
426   LoopTops[End] = &MBB;
427 
428   assert((!ScopeTops[AfterLoop->getNumber()] ||
429           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
430          "With block sorting the outermost loop for a block should be first.");
431   if (!ScopeTops[AfterLoop->getNumber()])
432     ScopeTops[AfterLoop->getNumber()] = &MBB;
433 }
434 
435 static unsigned
436 GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
437          const MachineBasicBlock *MBB) {
438   unsigned Depth = 0;
439   for (auto X : reverse(Stack)) {
440     if (X == MBB)
441       break;
442     ++Depth;
443   }
444   assert(Depth < Stack.size() && "Branch destination should be in scope");
445   return Depth;
446 }
447 
448 /// Insert LOOP and BLOCK markers at appropriate places.
449 static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
450                          const WebAssemblyInstrInfo &TII,
451                          MachineDominatorTree &MDT,
452                          WebAssemblyFunctionInfo &MFI) {
453   // For each block whose label represents the end of a scope, record the block
454   // which holds the beginning of the scope. This will allow us to quickly skip
455   // over scoped regions when walking blocks. We allocate one more than the
456   // number of blocks in the function to accommodate for the possible fake block
457   // we may insert at the end.
458   SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
459 
460   // For eacn LOOP_END, the corresponding LOOP.
461   DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops;
462 
463   for (auto &MBB : MF) {
464     // Place the LOOP for MBB if MBB is the header of a loop.
465     PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
466 
467     // Place the BLOCK for MBB if MBB is branched to from above.
468     PlaceBlockMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI, MDT, MFI);
469   }
470 
471   // Now rewrite references to basic blocks to be depth immediates.
472   SmallVector<const MachineBasicBlock *, 8> Stack;
473   for (auto &MBB : reverse(MF)) {
474     for (auto &MI : reverse(MBB)) {
475       switch (MI.getOpcode()) {
476       case WebAssembly::BLOCK:
477         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= MBB.getNumber() &&
478                "Block should be balanced");
479         Stack.pop_back();
480         break;
481       case WebAssembly::LOOP:
482         assert(Stack.back() == &MBB && "Loop top should be balanced");
483         Stack.pop_back();
484         break;
485       case WebAssembly::END_BLOCK:
486         Stack.push_back(&MBB);
487         break;
488       case WebAssembly::END_LOOP:
489         Stack.push_back(LoopTops[&MI]);
490         break;
491       default:
492         if (MI.isTerminator()) {
493           // Rewrite MBB operands to be depth immediates.
494           SmallVector<MachineOperand, 4> Ops(MI.operands());
495           while (MI.getNumOperands() > 0)
496             MI.RemoveOperand(MI.getNumOperands() - 1);
497           for (auto MO : Ops) {
498             if (MO.isMBB())
499               MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
500             MI.addOperand(MF, MO);
501           }
502         }
503         break;
504       }
505     }
506   }
507   assert(Stack.empty() && "Control flow should be balanced");
508 }
509 
510 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
511   DEBUG(dbgs() << "********** CFG Stackifying **********\n"
512                   "********** Function: "
513                << MF.getName() << '\n');
514 
515   const auto &MLI = getAnalysis<MachineLoopInfo>();
516   auto &MDT = getAnalysis<MachineDominatorTree>();
517   // Liveness is not tracked for VALUE_STACK physreg.
518   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
519   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
520   MF.getRegInfo().invalidateLiveness();
521 
522   // Sort the blocks, with contiguous loops.
523   SortBlocks(MF, MLI, MDT);
524 
525   // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
526   PlaceMarkers(MF, MLI, TII, MDT, MFI);
527 
528   return true;
529 }
530