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(MachineBasicBlock &MBB, MachineFunction &MF,
310                              SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
311                              const WebAssemblyInstrInfo &TII,
312                              const MachineLoopInfo &MLI,
313                              MachineDominatorTree &MDT,
314                              WebAssemblyFunctionInfo &MFI) {
315   // First compute the nearest common dominator of all forward non-fallthrough
316   // predecessors so that we minimize the time that the BLOCK is on the stack,
317   // which reduces overall stack height.
318   MachineBasicBlock *Header = nullptr;
319   bool IsBranchedTo = false;
320   int MBBNumber = MBB.getNumber();
321   for (MachineBasicBlock *Pred : MBB.predecessors())
322     if (Pred->getNumber() < MBBNumber) {
323       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
324       if (ExplicitlyBranchesTo(Pred, &MBB))
325         IsBranchedTo = true;
326     }
327   if (!Header)
328     return;
329   if (!IsBranchedTo)
330     return;
331 
332   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
333   MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB));
334 
335   // If the nearest common dominator is inside a more deeply nested context,
336   // walk out to the nearest scope which isn't more deeply nested.
337   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
338     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
339       if (ScopeTop->getNumber() > Header->getNumber()) {
340         // Skip over an intervening scope.
341         I = std::next(MachineFunction::iterator(ScopeTop));
342       } else {
343         // We found a scope level at an appropriate depth.
344         Header = ScopeTop;
345         break;
346       }
347     }
348   }
349 
350   // If there's a loop which ends just before MBB which contains Header, we can
351   // reuse its label instead of inserting a new BLOCK.
352   for (MachineLoop *Loop = MLI.getLoopFor(LayoutPred);
353        Loop && Loop->contains(LayoutPred); Loop = Loop->getParentLoop())
354     if (Loop && LoopBottom(Loop) == LayoutPred && Loop->contains(Header))
355       return;
356 
357   // Decide where in Header to put the BLOCK.
358   MachineBasicBlock::iterator InsertPos;
359   MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
360   if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
361     // Header is the header of a loop that does not lexically contain MBB, so
362     // the BLOCK needs to be above the LOOP, after any END constructs.
363     InsertPos = Header->begin();
364     while (InsertPos->getOpcode() != WebAssembly::LOOP)
365       ++InsertPos;
366   } else {
367     // Otherwise, insert the BLOCK as late in Header as we can, but before the
368     // beginning of the local expression tree and any nested BLOCKs.
369     InsertPos = Header->getFirstTerminator();
370     while (InsertPos != Header->begin() &&
371            IsChild(*std::prev(InsertPos), MFI) &&
372            std::prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
373            std::prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
374            std::prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
375       --InsertPos;
376   }
377 
378   // Add the BLOCK.
379   BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK));
380 
381   // Mark the end of the block.
382   InsertPos = MBB.begin();
383   while (InsertPos != MBB.end() &&
384          InsertPos->getOpcode() == WebAssembly::END_LOOP)
385     ++InsertPos;
386   BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK));
387 
388   // Track the farthest-spanning scope that ends at this point.
389   int Number = MBB.getNumber();
390   if (!ScopeTops[Number] ||
391       ScopeTops[Number]->getNumber() > Header->getNumber())
392     ScopeTops[Number] = Header;
393 }
394 
395 /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
396 static void PlaceLoopMarker(
397     MachineBasicBlock &MBB, MachineFunction &MF,
398     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
399     DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops,
400     const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
401   MachineLoop *Loop = MLI.getLoopFor(&MBB);
402   if (!Loop || Loop->getHeader() != &MBB)
403     return;
404 
405   // The operand of a LOOP is the first block after the loop. If the loop is the
406   // bottom of the function, insert a dummy block at the end.
407   MachineBasicBlock *Bottom = LoopBottom(Loop);
408   auto Iter = std::next(MachineFunction::iterator(Bottom));
409   if (Iter == MF.end()) {
410     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
411     // Give it a fake predecessor so that AsmPrinter prints its label.
412     Label->addSuccessor(Label);
413     MF.push_back(Label);
414     Iter = std::next(MachineFunction::iterator(Bottom));
415   }
416   MachineBasicBlock *AfterLoop = &*Iter;
417 
418   // Mark the beginning of the loop (after the end of any existing loop that
419   // ends here).
420   auto InsertPos = MBB.begin();
421   while (InsertPos != MBB.end() &&
422          InsertPos->getOpcode() == WebAssembly::END_LOOP)
423     ++InsertPos;
424   BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP));
425 
426   // Mark the end of the loop.
427   MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(),
428                               TII.get(WebAssembly::END_LOOP));
429   LoopTops[End] = &MBB;
430 
431   assert((!ScopeTops[AfterLoop->getNumber()] ||
432           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
433          "With block sorting the outermost loop for a block should be first.");
434   if (!ScopeTops[AfterLoop->getNumber()])
435     ScopeTops[AfterLoop->getNumber()] = &MBB;
436 }
437 
438 static unsigned
439 GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
440          const MachineBasicBlock *MBB) {
441   unsigned Depth = 0;
442   for (auto X : reverse(Stack)) {
443     if (X == MBB)
444       break;
445     ++Depth;
446   }
447   assert(Depth < Stack.size() && "Branch destination should be in scope");
448   return Depth;
449 }
450 
451 /// Insert LOOP and BLOCK markers at appropriate places.
452 static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
453                          const WebAssemblyInstrInfo &TII,
454                          MachineDominatorTree &MDT,
455                          WebAssemblyFunctionInfo &MFI) {
456   // For each block whose label represents the end of a scope, record the block
457   // which holds the beginning of the scope. This will allow us to quickly skip
458   // over scoped regions when walking blocks. We allocate one more than the
459   // number of blocks in the function to accommodate for the possible fake block
460   // we may insert at the end.
461   SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
462 
463   // For eacn LOOP_END, the corresponding LOOP.
464   DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops;
465 
466   for (auto &MBB : MF) {
467     // Place the LOOP for MBB if MBB is the header of a loop.
468     PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
469 
470     // Place the BLOCK for MBB if MBB is branched to from above.
471     PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT, MFI);
472   }
473 
474   // Now rewrite references to basic blocks to be depth immediates.
475   SmallVector<const MachineBasicBlock *, 8> Stack;
476   for (auto &MBB : reverse(MF)) {
477     for (auto &MI : reverse(MBB)) {
478       switch (MI.getOpcode()) {
479       case WebAssembly::BLOCK:
480         assert(ScopeTops[Stack.back()->getNumber()] == &MBB &&
481                "Block should be balanced");
482         Stack.pop_back();
483         break;
484       case WebAssembly::LOOP:
485         assert(Stack.back() == &MBB && "Loop top should be balanced");
486         Stack.pop_back();
487         Stack.pop_back();
488         break;
489       case WebAssembly::END_BLOCK:
490         Stack.push_back(&MBB);
491         break;
492       case WebAssembly::END_LOOP:
493         Stack.push_back(&MBB);
494         Stack.push_back(LoopTops[&MI]);
495         break;
496       default:
497         if (MI.isTerminator()) {
498           // Rewrite MBB operands to be depth immediates.
499           SmallVector<MachineOperand, 4> Ops(MI.operands());
500           while (MI.getNumOperands() > 0)
501             MI.RemoveOperand(MI.getNumOperands() - 1);
502           for (auto MO : Ops) {
503             if (MO.isMBB())
504               MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
505             MI.addOperand(MF, MO);
506           }
507         }
508         break;
509       }
510     }
511   }
512   assert(Stack.empty() && "Control flow should be balanced");
513 }
514 
515 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
516   DEBUG(dbgs() << "********** CFG Stackifying **********\n"
517                   "********** Function: "
518                << MF.getName() << '\n');
519 
520   const auto &MLI = getAnalysis<MachineLoopInfo>();
521   auto &MDT = getAnalysis<MachineDominatorTree>();
522   // Liveness is not tracked for VALUE_STACK physreg.
523   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
524   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
525   MF.getRegInfo().invalidateLiveness();
526 
527   // Sort the blocks, with contiguous loops.
528   SortBlocks(MF, MLI, MDT);
529 
530   // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
531   PlaceMarkers(MF, MLI, TII, MDT, MFI);
532 
533   return true;
534 }
535