blob: 558ac2299931ae3f1b7e3da9a23b060198c3f93e [file] [log] [blame]
Dan Gohman950a13c2015-09-16 16:51:30 +00001//===-- 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///
Dan Gohman442bfce2016-02-16 16:22:41 +000013/// 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.
Dan Gohman950a13c2015-09-16 16:51:30 +000017///
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///
Dan Gohman950a13c2015-09-16 16:51:30 +000024//===----------------------------------------------------------------------===//
25
26#include "WebAssembly.h"
27#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
Dan Gohmaned0f1132016-01-30 05:01:06 +000028#include "WebAssemblyMachineFunctionInfo.h"
Dan Gohman950a13c2015-09-16 16:51:30 +000029#include "WebAssemblySubtarget.h"
Dan Gohman442bfce2016-02-16 16:22:41 +000030#include "llvm/ADT/PriorityQueue.h"
Dan Gohman8fe7e862015-12-14 22:51:54 +000031#include "llvm/ADT/SetVector.h"
Dan Gohman32807932015-11-23 16:19:56 +000032#include "llvm/CodeGen/MachineDominators.h"
Dan Gohman950a13c2015-09-16 16:51:30 +000033#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineLoopInfo.h"
Derek Schuff9c3bf312016-01-13 17:10:28 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman950a13c2015-09-16 16:51:30 +000037#include "llvm/CodeGen/Passes.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/raw_ostream.h"
40using namespace llvm;
41
42#define DEBUG_TYPE "wasm-cfg-stackify"
43
44namespace {
45class WebAssemblyCFGStackify final : public MachineFunctionPass {
Mehdi Amini117296c2016-10-01 02:56:57 +000046 StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
Dan Gohman950a13c2015-09-16 16:51:30 +000047
48 void getAnalysisUsage(AnalysisUsage &AU) const override {
49 AU.setPreservesCFG();
Dan Gohman32807932015-11-23 16:19:56 +000050 AU.addRequired<MachineDominatorTree>();
51 AU.addPreserved<MachineDominatorTree>();
Dan Gohman950a13c2015-09-16 16:51:30 +000052 AU.addRequired<MachineLoopInfo>();
53 AU.addPreserved<MachineLoopInfo>();
54 MachineFunctionPass::getAnalysisUsage(AU);
55 }
56
57 bool runOnMachineFunction(MachineFunction &MF) override;
58
59public:
60 static char ID; // Pass identification, replacement for typeid
61 WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
62};
63} // end anonymous namespace
64
65char WebAssemblyCFGStackify::ID = 0;
66FunctionPass *llvm::createWebAssemblyCFGStackify() {
67 return new WebAssemblyCFGStackify();
68}
69
Dan Gohman8fe7e862015-12-14 22:51:54 +000070/// Return the "bottom" block of a loop. This differs from
71/// MachineLoop::getBottomBlock in that it works even if the loop is
72/// discontiguous.
73static 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
Dan Gohman442bfce2016-02-16 16:22:41 +000081static 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}
Dan Gohman950a13c2015-09-16 16:51:30 +000097
Dan Gohman442bfce2016-02-16 16:22:41 +000098namespace {
99/// Sort blocks by their number.
100struct 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..
107struct 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.
115struct Entry {
116 const MachineLoop *Loop;
117 unsigned NumBlocksLeft;
Dan Gohman950a13c2015-09-16 16:51:30 +0000118
Dan Gohman442bfce2016-02-16 16:22:41 +0000119 /// 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;
Dan Gohman950a13c2015-09-16 16:51:30 +0000122
Dan Gohman442bfce2016-02-16 16:22:41 +0000123 explicit Entry(const MachineLoop *L)
124 : Loop(L), NumBlocksLeft(L->getNumBlocks()) {}
125};
126}
Dan Gohman950a13c2015-09-16 16:51:30 +0000127
Dan Gohman442bfce2016-02-16 16:22:41 +0000128/// 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.
132static 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;
Dan Gohman950a13c2015-09-16 16:51:30 +0000146 }
147
Dan Gohman442bfce2016-02-16 16:22:41 +0000148 // 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");
Dan Gohman950a13c2015-09-16 16:51:30 +0000241 MF.RenumberBlocks();
242
243#ifndef NDEBUG
Dan Gohman8fe7e862015-12-14 22:51:54 +0000244 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.");
Dan Gohman950a13c2015-09-16 16:51:30 +0000263 } else {
Dan Gohman8fe7e862015-12-14 22:51:54 +0000264 // Not a loop header. All predecessors should be sorted above.
Dan Gohman950a13c2015-09-16 16:51:30 +0000265 for (auto Pred : MBB.predecessors())
266 assert(Pred->getNumber() < MBB.getNumber() &&
Dan Gohman8fe7e862015-12-14 22:51:54 +0000267 "Non-loop-header predecessors should be topologically sorted");
268 assert(OnStack.count(MLI.getLoopFor(&MBB)) &&
269 "Blocks must be nested in their loops");
Dan Gohman950a13c2015-09-16 16:51:30 +0000270 }
Dan Gohman8fe7e862015-12-14 22:51:54 +0000271 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.");
Dan Gohman950a13c2015-09-16 16:51:30 +0000278#endif
279}
280
Dan Gohmanb3aa1ec2015-12-16 19:06:41 +0000281/// 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.
Dan Gohman35e4a282016-01-08 01:06:00 +0000286static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred,
287 MachineBasicBlock *MBB) {
Dan Gohmanb3aa1ec2015-12-16 19:06:41 +0000288 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
Dan Gohmaned0f1132016-01-30 05:01:06 +0000295/// Test whether MI is a child of some other node in an expression tree.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000296static bool IsChild(const MachineInstr &MI,
Dan Gohmaned0f1132016-01-30 05:01:06 +0000297 const WebAssemblyFunctionInfo &MFI) {
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000298 if (MI.getNumOperands() == 0)
Dan Gohmaned0f1132016-01-30 05:01:06 +0000299 return false;
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000300 const MachineOperand &MO = MI.getOperand(0);
Dan Gohmaned0f1132016-01-30 05:01:06 +0000301 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
Dan Gohman32807932015-11-23 16:19:56 +0000308/// Insert a BLOCK marker for branches to MBB (if needed).
Dan Gohman3a643e82016-10-06 22:10:23 +0000309static 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) {
Dan Gohman8fe7e862015-12-14 22:51:54 +0000317 // 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.
Dan Gohman32807932015-11-23 16:19:56 +0000320 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;
Dan Gohmanb3aa1ec2015-12-16 19:06:41 +0000326 if (ExplicitlyBranchesTo(Pred, &MBB))
Dan Gohman32807932015-11-23 16:19:56 +0000327 IsBranchedTo = true;
328 }
329 if (!Header)
330 return;
331 if (!IsBranchedTo)
Dan Gohman950a13c2015-09-16 16:51:30 +0000332 return;
333
Dan Gohman8fe7e862015-12-14 22:51:54 +0000334 assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
Benjamin Krameref0a45a2016-09-05 12:06:47 +0000335 MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB));
Dan Gohman8fe7e862015-12-14 22:51:54 +0000336
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.
Benjamin Krameref0a45a2016-09-05 12:06:47 +0000343 I = std::next(MachineFunction::iterator(ScopeTop));
Dan Gohman8fe7e862015-12-14 22:51:54 +0000344 } else {
345 // We found a scope level at an appropriate depth.
346 Header = ScopeTop;
347 break;
348 }
349 }
350 }
351
Dan Gohman8fe7e862015-12-14 22:51:54 +0000352 // Decide where in Header to put the BLOCK.
Dan Gohman32807932015-11-23 16:19:56 +0000353 MachineBasicBlock::iterator InsertPos;
354 MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
Dan Gohman8fe7e862015-12-14 22:51:54 +0000355 if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
356 // Header is the header of a loop that does not lexically contain MBB, so
Dan Gohmana187ab22016-02-12 21:19:25 +0000357 // the BLOCK needs to be above the LOOP, after any END constructs.
Dan Gohman32807932015-11-23 16:19:56 +0000358 InsertPos = Header->begin();
Dan Gohman3a643e82016-10-06 22:10:23 +0000359 while (InsertPos->getOpcode() == WebAssembly::END_BLOCK ||
360 InsertPos->getOpcode() == WebAssembly::END_LOOP)
Dan Gohmana187ab22016-02-12 21:19:25 +0000361 ++InsertPos;
Dan Gohman32807932015-11-23 16:19:56 +0000362 } else {
Dan Gohman8887d1f2015-12-25 00:31:02 +0000363 // 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.
Dan Gohman32807932015-11-23 16:19:56 +0000365 InsertPos = Header->getFirstTerminator();
Benjamin Krameref0a45a2016-09-05 12:06:47 +0000366 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)
Dan Gohman32807932015-11-23 16:19:56 +0000371 --InsertPos;
Dan Gohman950a13c2015-09-16 16:51:30 +0000372 }
373
Dan Gohman8fe7e862015-12-14 22:51:54 +0000374 // Add the BLOCK.
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000375 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() &&
Dan Gohman3a643e82016-10-06 22:10:23 +0000380 InsertPos->getOpcode() == WebAssembly::END_LOOP &&
381 LoopTops[&*InsertPos]->getNumber() >= Header->getNumber())
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000382 ++InsertPos;
383 BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK));
Dan Gohman8fe7e862015-12-14 22:51:54 +0000384
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).
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000393static 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) {
Dan Gohman8fe7e862015-12-14 22:51:54 +0000398 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);
Benjamin Krameref0a45a2016-09-05 12:06:47 +0000405 auto Iter = std::next(MachineFunction::iterator(Bottom));
Dan Gohman8fe7e862015-12-14 22:51:54 +0000406 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);
Benjamin Krameref0a45a2016-09-05 12:06:47 +0000411 Iter = std::next(MachineFunction::iterator(Bottom));
Dan Gohman8fe7e862015-12-14 22:51:54 +0000412 }
413 MachineBasicBlock *AfterLoop = &*Iter;
Dan Gohman8fe7e862015-12-14 22:51:54 +0000414
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000415 // 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;
Dan Gohman8fe7e862015-12-14 22:51:54 +0000427
428 assert((!ScopeTops[AfterLoop->getNumber()] ||
429 ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
Dan Gohman442bfce2016-02-16 16:22:41 +0000430 "With block sorting the outermost loop for a block should be first.");
Dan Gohman8fe7e862015-12-14 22:51:54 +0000431 if (!ScopeTops[AfterLoop->getNumber()])
432 ScopeTops[AfterLoop->getNumber()] = &MBB;
Dan Gohman950a13c2015-09-16 16:51:30 +0000433}
434
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000435static unsigned
436GetDepth(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
Dan Gohman950a13c2015-09-16 16:51:30 +0000448/// Insert LOOP and BLOCK markers at appropriate places.
449static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
Dan Gohman32807932015-11-23 16:19:56 +0000450 const WebAssemblyInstrInfo &TII,
Dan Gohmaned0f1132016-01-30 05:01:06 +0000451 MachineDominatorTree &MDT,
452 WebAssemblyFunctionInfo &MFI) {
Dan Gohman8fe7e862015-12-14 22:51:54 +0000453 // 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
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000460 // For eacn LOOP_END, the corresponding LOOP.
461 DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops;
462
Dan Gohman950a13c2015-09-16 16:51:30 +0000463 for (auto &MBB : MF) {
Dan Gohman32807932015-11-23 16:19:56 +0000464 // Place the LOOP for MBB if MBB is the header of a loop.
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000465 PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
Dan Gohman950a13c2015-09-16 16:51:30 +0000466
Dan Gohman32807932015-11-23 16:19:56 +0000467 // Place the BLOCK for MBB if MBB is branched to from above.
Dan Gohman3a643e82016-10-06 22:10:23 +0000468 PlaceBlockMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI, MDT, MFI);
Dan Gohman950a13c2015-09-16 16:51:30 +0000469 }
Dan Gohman950a13c2015-09-16 16:51:30 +0000470
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000471 // 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:
Dan Gohman3a643e82016-10-06 22:10:23 +0000477 assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= MBB.getNumber() &&
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000478 "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();
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000484 break;
485 case WebAssembly::END_BLOCK:
486 Stack.push_back(&MBB);
487 break;
488 case WebAssembly::END_LOOP:
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000489 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");
Dan Gohman32807932015-11-23 16:19:56 +0000508}
Dan Gohman32807932015-11-23 16:19:56 +0000509
Dan Gohman950a13c2015-09-16 16:51:30 +0000510bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
511 DEBUG(dbgs() << "********** CFG Stackifying **********\n"
512 "********** Function: "
513 << MF.getName() << '\n');
514
515 const auto &MLI = getAnalysis<MachineLoopInfo>();
Dan Gohman32807932015-11-23 16:19:56 +0000516 auto &MDT = getAnalysis<MachineDominatorTree>();
Dan Gohmane0405332016-10-03 22:43:53 +0000517 // Liveness is not tracked for VALUE_STACK physreg.
Dan Gohman950a13c2015-09-16 16:51:30 +0000518 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
Dan Gohmaned0f1132016-01-30 05:01:06 +0000519 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
Derek Schuff9c3bf312016-01-13 17:10:28 +0000520 MF.getRegInfo().invalidateLiveness();
Dan Gohman950a13c2015-09-16 16:51:30 +0000521
Dan Gohman442bfce2016-02-16 16:22:41 +0000522 // Sort the blocks, with contiguous loops.
523 SortBlocks(MF, MLI, MDT);
Dan Gohman950a13c2015-09-16 16:51:30 +0000524
525 // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
Dan Gohmaned0f1132016-01-30 05:01:06 +0000526 PlaceMarkers(MF, MLI, TII, MDT, MFI);
Dan Gohman32807932015-11-23 16:19:56 +0000527
Dan Gohman950a13c2015-09-16 16:51:30 +0000528 return true;
529}