blob: 9b987650d2f7aaf943e9e2fc9d3432eff8b8a8a2 [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///
13/// This pass reorders the blocks in a function to put them into a reverse
14/// post-order [0], with special care to keep the order as similar as possible
15/// to the original order, and to keep loops contiguous even in the case of
16/// split backedges.
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/// [0] https://en.wikipedia.org/wiki/Depth-first_search#Vertex_orderings
25///
26//===----------------------------------------------------------------------===//
27
28#include "WebAssembly.h"
29#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
Dan Gohmaned0f1132016-01-30 05:01:06 +000030#include "WebAssemblyMachineFunctionInfo.h"
Dan Gohman950a13c2015-09-16 16:51:30 +000031#include "WebAssemblySubtarget.h"
32#include "llvm/ADT/SCCIterator.h"
Dan Gohman8fe7e862015-12-14 22:51:54 +000033#include "llvm/ADT/SetVector.h"
Dan Gohman32807932015-11-23 16:19:56 +000034#include "llvm/CodeGen/MachineDominators.h"
Dan Gohman950a13c2015-09-16 16:51:30 +000035#include "llvm/CodeGen/MachineFunction.h"
36#include "llvm/CodeGen/MachineInstrBuilder.h"
37#include "llvm/CodeGen/MachineLoopInfo.h"
Derek Schuff9c3bf312016-01-13 17:10:28 +000038#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman950a13c2015-09-16 16:51:30 +000039#include "llvm/CodeGen/Passes.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Support/raw_ostream.h"
42using namespace llvm;
43
44#define DEBUG_TYPE "wasm-cfg-stackify"
45
46namespace {
47class WebAssemblyCFGStackify final : public MachineFunctionPass {
48 const char *getPassName() const override {
49 return "WebAssembly CFG Stackify";
50 }
51
52 void getAnalysisUsage(AnalysisUsage &AU) const override {
53 AU.setPreservesCFG();
Dan Gohman32807932015-11-23 16:19:56 +000054 AU.addRequired<MachineDominatorTree>();
55 AU.addPreserved<MachineDominatorTree>();
Dan Gohman950a13c2015-09-16 16:51:30 +000056 AU.addRequired<MachineLoopInfo>();
57 AU.addPreserved<MachineLoopInfo>();
58 MachineFunctionPass::getAnalysisUsage(AU);
59 }
60
61 bool runOnMachineFunction(MachineFunction &MF) override;
62
63public:
64 static char ID; // Pass identification, replacement for typeid
65 WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
66};
67} // end anonymous namespace
68
69char WebAssemblyCFGStackify::ID = 0;
70FunctionPass *llvm::createWebAssemblyCFGStackify() {
71 return new WebAssemblyCFGStackify();
72}
73
74static void EliminateMultipleEntryLoops(MachineFunction &MF,
75 const MachineLoopInfo &MLI) {
76 SmallPtrSet<MachineBasicBlock *, 8> InSet;
77 for (scc_iterator<MachineFunction *> I = scc_begin(&MF), E = scc_end(&MF);
78 I != E; ++I) {
79 const std::vector<MachineBasicBlock *> &CurrentSCC = *I;
80
81 // Skip trivial SCCs.
82 if (CurrentSCC.size() == 1)
83 continue;
84
85 InSet.insert(CurrentSCC.begin(), CurrentSCC.end());
86 MachineBasicBlock *Header = nullptr;
87 for (MachineBasicBlock *MBB : CurrentSCC) {
88 for (MachineBasicBlock *Pred : MBB->predecessors()) {
89 if (InSet.count(Pred))
90 continue;
91 if (!Header) {
92 Header = MBB;
93 break;
94 }
95 // TODO: Implement multiple-entry loops.
96 report_fatal_error("multiple-entry loops are not supported yet");
97 }
98 }
99 assert(MLI.isLoopHeader(Header));
100
101 InSet.clear();
102 }
103}
104
105namespace {
106/// Post-order traversal stack entry.
107struct POStackEntry {
108 MachineBasicBlock *MBB;
109 SmallVector<MachineBasicBlock *, 0> Succs;
110
111 POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF,
112 const MachineLoopInfo &MLI);
113};
114} // end anonymous namespace
115
Dan Gohman32807932015-11-23 16:19:56 +0000116static bool LoopContains(const MachineLoop *Loop,
117 const MachineBasicBlock *MBB) {
118 return Loop ? Loop->contains(MBB) : true;
119}
120
Dan Gohman950a13c2015-09-16 16:51:30 +0000121POStackEntry::POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF,
122 const MachineLoopInfo &MLI)
123 : MBB(MBB), Succs(MBB->successors()) {
124 // RPO is not a unique form, since at every basic block with multiple
125 // successors, the DFS has to pick which order to visit the successors in.
126 // Sort them strategically (see below).
127 MachineLoop *Loop = MLI.getLoopFor(MBB);
128 MachineFunction::iterator Next = next(MachineFunction::iterator(MBB));
129 MachineBasicBlock *LayoutSucc = Next == MF.end() ? nullptr : &*Next;
130 std::stable_sort(
131 Succs.begin(), Succs.end(),
132 [=, &MLI](const MachineBasicBlock *A, const MachineBasicBlock *B) {
133 if (A == B)
134 return false;
135
136 // Keep loops contiguous by preferring the block that's in the same
137 // loop.
Dan Gohman32807932015-11-23 16:19:56 +0000138 bool LoopContainsA = LoopContains(Loop, A);
139 bool LoopContainsB = LoopContains(Loop, B);
140 if (LoopContainsA && !LoopContainsB)
Dan Gohman950a13c2015-09-16 16:51:30 +0000141 return true;
Dan Gohman32807932015-11-23 16:19:56 +0000142 if (!LoopContainsA && LoopContainsB)
Dan Gohman950a13c2015-09-16 16:51:30 +0000143 return false;
144
145 // Minimize perturbation by preferring the block which is the immediate
146 // layout successor.
147 if (A == LayoutSucc)
148 return true;
149 if (B == LayoutSucc)
150 return false;
151
152 // TODO: More sophisticated orderings may be profitable here.
153
154 return false;
155 });
156}
157
Dan Gohman8fe7e862015-12-14 22:51:54 +0000158/// Return the "bottom" block of a loop. This differs from
159/// MachineLoop::getBottomBlock in that it works even if the loop is
160/// discontiguous.
161static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) {
162 MachineBasicBlock *Bottom = Loop->getHeader();
163 for (MachineBasicBlock *MBB : Loop->blocks())
164 if (MBB->getNumber() > Bottom->getNumber())
165 Bottom = MBB;
166 return Bottom;
167}
168
Dan Gohman950a13c2015-09-16 16:51:30 +0000169/// Sort the blocks in RPO, taking special care to make sure that loops are
170/// contiguous even in the case of split backedges.
Dan Gohman8fe7e862015-12-14 22:51:54 +0000171///
172/// TODO: Determine whether RPO is actually worthwhile, or whether we should
173/// move to just a stable-topological-sort-based approach that would preserve
174/// more of the original order.
Dan Gohman950a13c2015-09-16 16:51:30 +0000175static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI) {
176 // Note that we do our own RPO rather than using
177 // "llvm/ADT/PostOrderIterator.h" because we want control over the order that
178 // successors are visited in (see above). Also, we can sort the blocks in the
179 // MachineFunction as we go.
180 SmallPtrSet<MachineBasicBlock *, 16> Visited;
181 SmallVector<POStackEntry, 16> Stack;
182
Dan Gohman96029f72015-11-30 18:42:08 +0000183 MachineBasicBlock *EntryBlock = &*MF.begin();
184 Visited.insert(EntryBlock);
185 Stack.push_back(POStackEntry(EntryBlock, MF, MLI));
Dan Gohman950a13c2015-09-16 16:51:30 +0000186
187 for (;;) {
188 POStackEntry &Entry = Stack.back();
189 SmallVectorImpl<MachineBasicBlock *> &Succs = Entry.Succs;
190 if (!Succs.empty()) {
191 MachineBasicBlock *Succ = Succs.pop_back_val();
192 if (Visited.insert(Succ).second)
193 Stack.push_back(POStackEntry(Succ, MF, MLI));
194 continue;
195 }
196
197 // Put the block in its position in the MachineFunction.
198 MachineBasicBlock &MBB = *Entry.MBB;
Nico Weber00406472015-11-07 02:47:31 +0000199 MBB.moveBefore(&*MF.begin());
Dan Gohman950a13c2015-09-16 16:51:30 +0000200
201 // Branch instructions may utilize a fallthrough, so update them if a
202 // fallthrough has been added or removed.
203 if (!MBB.empty() && MBB.back().isTerminator() && !MBB.back().isBranch() &&
204 !MBB.back().isBarrier())
205 report_fatal_error(
206 "Non-branch terminator with fallthrough cannot yet be rewritten");
207 if (MBB.empty() || !MBB.back().isTerminator() || MBB.back().isBranch())
208 MBB.updateTerminator();
209
210 Stack.pop_back();
211 if (Stack.empty())
212 break;
213 }
214
215 // Now that we've sorted the blocks in RPO, renumber them.
216 MF.RenumberBlocks();
217
218#ifndef NDEBUG
Dan Gohman8fe7e862015-12-14 22:51:54 +0000219 SmallSetVector<MachineLoop *, 8> OnStack;
220
221 // Insert a sentinel representing the degenerate loop that starts at the
222 // function entry block and includes the entire function as a "loop" that
223 // executes once.
224 OnStack.insert(nullptr);
225
226 for (auto &MBB : MF) {
227 assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
228
229 MachineLoop *Loop = MLI.getLoopFor(&MBB);
230 if (Loop && &MBB == Loop->getHeader()) {
231 // Loop header. The loop predecessor should be sorted above, and the other
232 // predecessors should be backedges below.
233 for (auto Pred : MBB.predecessors())
234 assert(
235 (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) &&
236 "Loop header predecessors must be loop predecessors or backedges");
237 assert(OnStack.insert(Loop) && "Loops should be declared at most once.");
Dan Gohman950a13c2015-09-16 16:51:30 +0000238 } else {
Dan Gohman8fe7e862015-12-14 22:51:54 +0000239 // Not a loop header. All predecessors should be sorted above.
Dan Gohman950a13c2015-09-16 16:51:30 +0000240 for (auto Pred : MBB.predecessors())
241 assert(Pred->getNumber() < MBB.getNumber() &&
Dan Gohman8fe7e862015-12-14 22:51:54 +0000242 "Non-loop-header predecessors should be topologically sorted");
243 assert(OnStack.count(MLI.getLoopFor(&MBB)) &&
244 "Blocks must be nested in their loops");
Dan Gohman950a13c2015-09-16 16:51:30 +0000245 }
Dan Gohman8fe7e862015-12-14 22:51:54 +0000246 while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back()))
247 OnStack.pop_back();
248 }
249 assert(OnStack.pop_back_val() == nullptr &&
250 "The function entry block shouldn't actually be a loop header");
251 assert(OnStack.empty() &&
252 "Control flow stack pushes and pops should be balanced.");
Dan Gohman950a13c2015-09-16 16:51:30 +0000253#endif
254}
255
Dan Gohmanb3aa1ec2015-12-16 19:06:41 +0000256/// Test whether Pred has any terminators explicitly branching to MBB, as
257/// opposed to falling through. Note that it's possible (eg. in unoptimized
258/// code) for a branch instruction to both branch to a block and fallthrough
259/// to it, so we check the actual branch operands to see if there are any
260/// explicit mentions.
Dan Gohman35e4a282016-01-08 01:06:00 +0000261static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred,
262 MachineBasicBlock *MBB) {
Dan Gohmanb3aa1ec2015-12-16 19:06:41 +0000263 for (MachineInstr &MI : Pred->terminators())
264 for (MachineOperand &MO : MI.explicit_operands())
265 if (MO.isMBB() && MO.getMBB() == MBB)
266 return true;
267 return false;
268}
269
Dan Gohmaned0f1132016-01-30 05:01:06 +0000270/// Test whether MI is a child of some other node in an expression tree.
271static bool IsChild(const MachineInstr *MI,
272 const WebAssemblyFunctionInfo &MFI) {
273 if (MI->getNumOperands() == 0)
274 return false;
275 const MachineOperand &MO = MI->getOperand(0);
276 if (!MO.isReg() || MO.isImplicit() || !MO.isDef())
277 return false;
278 unsigned Reg = MO.getReg();
279 return TargetRegisterInfo::isVirtualRegister(Reg) &&
280 MFI.isVRegStackified(Reg);
281}
282
Dan Gohman32807932015-11-23 16:19:56 +0000283/// Insert a BLOCK marker for branches to MBB (if needed).
Dan Gohman8fe7e862015-12-14 22:51:54 +0000284static void PlaceBlockMarker(MachineBasicBlock &MBB, MachineFunction &MF,
285 SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
286 const WebAssemblyInstrInfo &TII,
287 const MachineLoopInfo &MLI,
Dan Gohmaned0f1132016-01-30 05:01:06 +0000288 MachineDominatorTree &MDT,
289 WebAssemblyFunctionInfo &MFI) {
Dan Gohman8fe7e862015-12-14 22:51:54 +0000290 // First compute the nearest common dominator of all forward non-fallthrough
291 // predecessors so that we minimize the time that the BLOCK is on the stack,
292 // which reduces overall stack height.
Dan Gohman32807932015-11-23 16:19:56 +0000293 MachineBasicBlock *Header = nullptr;
294 bool IsBranchedTo = false;
295 int MBBNumber = MBB.getNumber();
296 for (MachineBasicBlock *Pred : MBB.predecessors())
297 if (Pred->getNumber() < MBBNumber) {
298 Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
Dan Gohmanb3aa1ec2015-12-16 19:06:41 +0000299 if (ExplicitlyBranchesTo(Pred, &MBB))
Dan Gohman32807932015-11-23 16:19:56 +0000300 IsBranchedTo = true;
301 }
302 if (!Header)
303 return;
304 if (!IsBranchedTo)
Dan Gohman950a13c2015-09-16 16:51:30 +0000305 return;
306
Dan Gohman8fe7e862015-12-14 22:51:54 +0000307 assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
308 MachineBasicBlock *LayoutPred = &*prev(MachineFunction::iterator(&MBB));
309
310 // If the nearest common dominator is inside a more deeply nested context,
311 // walk out to the nearest scope which isn't more deeply nested.
312 for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
313 if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
314 if (ScopeTop->getNumber() > Header->getNumber()) {
315 // Skip over an intervening scope.
316 I = next(MachineFunction::iterator(ScopeTop));
317 } else {
318 // We found a scope level at an appropriate depth.
319 Header = ScopeTop;
320 break;
321 }
322 }
323 }
324
325 // If there's a loop which ends just before MBB which contains Header, we can
326 // reuse its label instead of inserting a new BLOCK.
327 for (MachineLoop *Loop = MLI.getLoopFor(LayoutPred);
328 Loop && Loop->contains(LayoutPred); Loop = Loop->getParentLoop())
329 if (Loop && LoopBottom(Loop) == LayoutPred && Loop->contains(Header))
330 return;
331
332 // Decide where in Header to put the BLOCK.
Dan Gohman32807932015-11-23 16:19:56 +0000333 MachineBasicBlock::iterator InsertPos;
334 MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
Dan Gohman8fe7e862015-12-14 22:51:54 +0000335 if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
336 // Header is the header of a loop that does not lexically contain MBB, so
337 // the BLOCK needs to be above the LOOP.
Dan Gohman32807932015-11-23 16:19:56 +0000338 InsertPos = Header->begin();
Dan Gohman32807932015-11-23 16:19:56 +0000339 } else {
Dan Gohman8887d1f2015-12-25 00:31:02 +0000340 // Otherwise, insert the BLOCK as late in Header as we can, but before the
341 // beginning of the local expression tree and any nested BLOCKs.
Dan Gohman32807932015-11-23 16:19:56 +0000342 InsertPos = Header->getFirstTerminator();
343 while (InsertPos != Header->begin() &&
Dan Gohmaned0f1132016-01-30 05:01:06 +0000344 IsChild(prev(InsertPos), MFI) &&
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000345 prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
346 prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
347 prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
Dan Gohman32807932015-11-23 16:19:56 +0000348 --InsertPos;
Dan Gohman950a13c2015-09-16 16:51:30 +0000349 }
350
Dan Gohman8fe7e862015-12-14 22:51:54 +0000351 // Add the BLOCK.
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000352 BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK));
353
354 // Mark the end of the block.
355 InsertPos = MBB.begin();
356 while (InsertPos != MBB.end() &&
357 InsertPos->getOpcode() == WebAssembly::END_LOOP)
358 ++InsertPos;
359 BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK));
Dan Gohman8fe7e862015-12-14 22:51:54 +0000360
361 // Track the farthest-spanning scope that ends at this point.
362 int Number = MBB.getNumber();
363 if (!ScopeTops[Number] ||
364 ScopeTops[Number]->getNumber() > Header->getNumber())
365 ScopeTops[Number] = Header;
366}
367
368/// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000369static void PlaceLoopMarker(
370 MachineBasicBlock &MBB, MachineFunction &MF,
371 SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
372 DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops,
373 const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
Dan Gohman8fe7e862015-12-14 22:51:54 +0000374 MachineLoop *Loop = MLI.getLoopFor(&MBB);
375 if (!Loop || Loop->getHeader() != &MBB)
376 return;
377
378 // The operand of a LOOP is the first block after the loop. If the loop is the
379 // bottom of the function, insert a dummy block at the end.
380 MachineBasicBlock *Bottom = LoopBottom(Loop);
381 auto Iter = next(MachineFunction::iterator(Bottom));
382 if (Iter == MF.end()) {
383 MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
384 // Give it a fake predecessor so that AsmPrinter prints its label.
385 Label->addSuccessor(Label);
386 MF.push_back(Label);
387 Iter = next(MachineFunction::iterator(Bottom));
388 }
389 MachineBasicBlock *AfterLoop = &*Iter;
Dan Gohman8fe7e862015-12-14 22:51:54 +0000390
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000391 // Mark the beginning of the loop (after the end of any existing loop that
392 // ends here).
393 auto InsertPos = MBB.begin();
394 while (InsertPos != MBB.end() &&
395 InsertPos->getOpcode() == WebAssembly::END_LOOP)
396 ++InsertPos;
397 BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP));
398
399 // Mark the end of the loop.
400 MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(),
401 TII.get(WebAssembly::END_LOOP));
402 LoopTops[End] = &MBB;
Dan Gohman8fe7e862015-12-14 22:51:54 +0000403
404 assert((!ScopeTops[AfterLoop->getNumber()] ||
405 ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
406 "With RPO we should visit the outer-most loop for a block first.");
407 if (!ScopeTops[AfterLoop->getNumber()])
408 ScopeTops[AfterLoop->getNumber()] = &MBB;
Dan Gohman950a13c2015-09-16 16:51:30 +0000409}
410
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000411static unsigned
412GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
413 const MachineBasicBlock *MBB) {
414 unsigned Depth = 0;
415 for (auto X : reverse(Stack)) {
416 if (X == MBB)
417 break;
418 ++Depth;
419 }
420 assert(Depth < Stack.size() && "Branch destination should be in scope");
421 return Depth;
422}
423
Dan Gohman950a13c2015-09-16 16:51:30 +0000424/// Insert LOOP and BLOCK markers at appropriate places.
425static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
Dan Gohman32807932015-11-23 16:19:56 +0000426 const WebAssemblyInstrInfo &TII,
Dan Gohmaned0f1132016-01-30 05:01:06 +0000427 MachineDominatorTree &MDT,
428 WebAssemblyFunctionInfo &MFI) {
Dan Gohman8fe7e862015-12-14 22:51:54 +0000429 // For each block whose label represents the end of a scope, record the block
430 // which holds the beginning of the scope. This will allow us to quickly skip
431 // over scoped regions when walking blocks. We allocate one more than the
432 // number of blocks in the function to accommodate for the possible fake block
433 // we may insert at the end.
434 SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
435
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000436 // For eacn LOOP_END, the corresponding LOOP.
437 DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops;
438
Dan Gohman950a13c2015-09-16 16:51:30 +0000439 for (auto &MBB : MF) {
Dan Gohman32807932015-11-23 16:19:56 +0000440 // Place the LOOP for MBB if MBB is the header of a loop.
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000441 PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
Dan Gohman950a13c2015-09-16 16:51:30 +0000442
Dan Gohman32807932015-11-23 16:19:56 +0000443 // Place the BLOCK for MBB if MBB is branched to from above.
Dan Gohmaned0f1132016-01-30 05:01:06 +0000444 PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT, MFI);
Dan Gohman950a13c2015-09-16 16:51:30 +0000445 }
Dan Gohman950a13c2015-09-16 16:51:30 +0000446
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000447 // Now rewrite references to basic blocks to be depth immediates.
448 SmallVector<const MachineBasicBlock *, 8> Stack;
449 for (auto &MBB : reverse(MF)) {
450 for (auto &MI : reverse(MBB)) {
451 switch (MI.getOpcode()) {
452 case WebAssembly::BLOCK:
453 assert(ScopeTops[Stack.back()->getNumber()] == &MBB &&
454 "Block should be balanced");
455 Stack.pop_back();
456 break;
457 case WebAssembly::LOOP:
458 assert(Stack.back() == &MBB && "Loop top should be balanced");
459 Stack.pop_back();
460 Stack.pop_back();
461 break;
462 case WebAssembly::END_BLOCK:
463 Stack.push_back(&MBB);
464 break;
465 case WebAssembly::END_LOOP:
466 Stack.push_back(&MBB);
467 Stack.push_back(LoopTops[&MI]);
468 break;
469 default:
470 if (MI.isTerminator()) {
471 // Rewrite MBB operands to be depth immediates.
472 SmallVector<MachineOperand, 4> Ops(MI.operands());
473 while (MI.getNumOperands() > 0)
474 MI.RemoveOperand(MI.getNumOperands() - 1);
475 for (auto MO : Ops) {
476 if (MO.isMBB())
477 MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
478 MI.addOperand(MF, MO);
479 }
480 }
481 break;
482 }
483 }
484 }
485 assert(Stack.empty() && "Control flow should be balanced");
Dan Gohman32807932015-11-23 16:19:56 +0000486}
Dan Gohman32807932015-11-23 16:19:56 +0000487
Dan Gohman950a13c2015-09-16 16:51:30 +0000488bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
489 DEBUG(dbgs() << "********** CFG Stackifying **********\n"
490 "********** Function: "
491 << MF.getName() << '\n');
492
493 const auto &MLI = getAnalysis<MachineLoopInfo>();
Dan Gohman32807932015-11-23 16:19:56 +0000494 auto &MDT = getAnalysis<MachineDominatorTree>();
Derek Schuff9c3bf312016-01-13 17:10:28 +0000495 // Liveness is not tracked for EXPR_STACK physreg.
Dan Gohman950a13c2015-09-16 16:51:30 +0000496 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
Dan Gohmaned0f1132016-01-30 05:01:06 +0000497 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
Derek Schuff9c3bf312016-01-13 17:10:28 +0000498 MF.getRegInfo().invalidateLiveness();
Dan Gohman950a13c2015-09-16 16:51:30 +0000499
500 // RPO sorting needs all loops to be single-entry.
501 EliminateMultipleEntryLoops(MF, MLI);
502
503 // Sort the blocks in RPO, with contiguous loops.
504 SortBlocks(MF, MLI);
505
506 // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
Dan Gohmaned0f1132016-01-30 05:01:06 +0000507 PlaceMarkers(MF, MLI, TII, MDT, MFI);
Dan Gohman32807932015-11-23 16:19:56 +0000508
Dan Gohman950a13c2015-09-16 16:51:30 +0000509 return true;
510}