blob: 7581687a7d6f36a012f6e9a2537bd93f083775b5 [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
Dan Gohmana187ab22016-02-12 21:19:25 +0000337 // the BLOCK needs to be above the LOOP, after any END constructs.
Dan Gohman32807932015-11-23 16:19:56 +0000338 InsertPos = Header->begin();
Dan Gohmana187ab22016-02-12 21:19:25 +0000339 while (InsertPos->getOpcode() != WebAssembly::LOOP)
340 ++InsertPos;
Dan Gohman32807932015-11-23 16:19:56 +0000341 } else {
Dan Gohman8887d1f2015-12-25 00:31:02 +0000342 // Otherwise, insert the BLOCK as late in Header as we can, but before the
343 // beginning of the local expression tree and any nested BLOCKs.
Dan Gohman32807932015-11-23 16:19:56 +0000344 InsertPos = Header->getFirstTerminator();
345 while (InsertPos != Header->begin() &&
Dan Gohmaned0f1132016-01-30 05:01:06 +0000346 IsChild(prev(InsertPos), MFI) &&
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000347 prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
348 prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
349 prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
Dan Gohman32807932015-11-23 16:19:56 +0000350 --InsertPos;
Dan Gohman950a13c2015-09-16 16:51:30 +0000351 }
352
Dan Gohman8fe7e862015-12-14 22:51:54 +0000353 // Add the BLOCK.
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000354 BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK));
355
356 // Mark the end of the block.
357 InsertPos = MBB.begin();
358 while (InsertPos != MBB.end() &&
359 InsertPos->getOpcode() == WebAssembly::END_LOOP)
360 ++InsertPos;
361 BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK));
Dan Gohman8fe7e862015-12-14 22:51:54 +0000362
363 // Track the farthest-spanning scope that ends at this point.
364 int Number = MBB.getNumber();
365 if (!ScopeTops[Number] ||
366 ScopeTops[Number]->getNumber() > Header->getNumber())
367 ScopeTops[Number] = Header;
368}
369
370/// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000371static void PlaceLoopMarker(
372 MachineBasicBlock &MBB, MachineFunction &MF,
373 SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
374 DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops,
375 const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
Dan Gohman8fe7e862015-12-14 22:51:54 +0000376 MachineLoop *Loop = MLI.getLoopFor(&MBB);
377 if (!Loop || Loop->getHeader() != &MBB)
378 return;
379
380 // The operand of a LOOP is the first block after the loop. If the loop is the
381 // bottom of the function, insert a dummy block at the end.
382 MachineBasicBlock *Bottom = LoopBottom(Loop);
383 auto Iter = next(MachineFunction::iterator(Bottom));
384 if (Iter == MF.end()) {
385 MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
386 // Give it a fake predecessor so that AsmPrinter prints its label.
387 Label->addSuccessor(Label);
388 MF.push_back(Label);
389 Iter = next(MachineFunction::iterator(Bottom));
390 }
391 MachineBasicBlock *AfterLoop = &*Iter;
Dan Gohman8fe7e862015-12-14 22:51:54 +0000392
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000393 // Mark the beginning of the loop (after the end of any existing loop that
394 // ends here).
395 auto InsertPos = MBB.begin();
396 while (InsertPos != MBB.end() &&
397 InsertPos->getOpcode() == WebAssembly::END_LOOP)
398 ++InsertPos;
399 BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP));
400
401 // Mark the end of the loop.
402 MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(),
403 TII.get(WebAssembly::END_LOOP));
404 LoopTops[End] = &MBB;
Dan Gohman8fe7e862015-12-14 22:51:54 +0000405
406 assert((!ScopeTops[AfterLoop->getNumber()] ||
407 ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
408 "With RPO we should visit the outer-most loop for a block first.");
409 if (!ScopeTops[AfterLoop->getNumber()])
410 ScopeTops[AfterLoop->getNumber()] = &MBB;
Dan Gohman950a13c2015-09-16 16:51:30 +0000411}
412
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000413static unsigned
414GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
415 const MachineBasicBlock *MBB) {
416 unsigned Depth = 0;
417 for (auto X : reverse(Stack)) {
418 if (X == MBB)
419 break;
420 ++Depth;
421 }
422 assert(Depth < Stack.size() && "Branch destination should be in scope");
423 return Depth;
424}
425
Dan Gohman950a13c2015-09-16 16:51:30 +0000426/// Insert LOOP and BLOCK markers at appropriate places.
427static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
Dan Gohman32807932015-11-23 16:19:56 +0000428 const WebAssemblyInstrInfo &TII,
Dan Gohmaned0f1132016-01-30 05:01:06 +0000429 MachineDominatorTree &MDT,
430 WebAssemblyFunctionInfo &MFI) {
Dan Gohman8fe7e862015-12-14 22:51:54 +0000431 // For each block whose label represents the end of a scope, record the block
432 // which holds the beginning of the scope. This will allow us to quickly skip
433 // over scoped regions when walking blocks. We allocate one more than the
434 // number of blocks in the function to accommodate for the possible fake block
435 // we may insert at the end.
436 SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
437
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000438 // For eacn LOOP_END, the corresponding LOOP.
439 DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops;
440
Dan Gohman950a13c2015-09-16 16:51:30 +0000441 for (auto &MBB : MF) {
Dan Gohman32807932015-11-23 16:19:56 +0000442 // Place the LOOP for MBB if MBB is the header of a loop.
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000443 PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
Dan Gohman950a13c2015-09-16 16:51:30 +0000444
Dan Gohman32807932015-11-23 16:19:56 +0000445 // Place the BLOCK for MBB if MBB is branched to from above.
Dan Gohmaned0f1132016-01-30 05:01:06 +0000446 PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT, MFI);
Dan Gohman950a13c2015-09-16 16:51:30 +0000447 }
Dan Gohman950a13c2015-09-16 16:51:30 +0000448
Dan Gohman1d68e80f2016-01-12 19:14:46 +0000449 // Now rewrite references to basic blocks to be depth immediates.
450 SmallVector<const MachineBasicBlock *, 8> Stack;
451 for (auto &MBB : reverse(MF)) {
452 for (auto &MI : reverse(MBB)) {
453 switch (MI.getOpcode()) {
454 case WebAssembly::BLOCK:
455 assert(ScopeTops[Stack.back()->getNumber()] == &MBB &&
456 "Block should be balanced");
457 Stack.pop_back();
458 break;
459 case WebAssembly::LOOP:
460 assert(Stack.back() == &MBB && "Loop top should be balanced");
461 Stack.pop_back();
462 Stack.pop_back();
463 break;
464 case WebAssembly::END_BLOCK:
465 Stack.push_back(&MBB);
466 break;
467 case WebAssembly::END_LOOP:
468 Stack.push_back(&MBB);
469 Stack.push_back(LoopTops[&MI]);
470 break;
471 default:
472 if (MI.isTerminator()) {
473 // Rewrite MBB operands to be depth immediates.
474 SmallVector<MachineOperand, 4> Ops(MI.operands());
475 while (MI.getNumOperands() > 0)
476 MI.RemoveOperand(MI.getNumOperands() - 1);
477 for (auto MO : Ops) {
478 if (MO.isMBB())
479 MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
480 MI.addOperand(MF, MO);
481 }
482 }
483 break;
484 }
485 }
486 }
487 assert(Stack.empty() && "Control flow should be balanced");
Dan Gohman32807932015-11-23 16:19:56 +0000488}
Dan Gohman32807932015-11-23 16:19:56 +0000489
Dan Gohman950a13c2015-09-16 16:51:30 +0000490bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
491 DEBUG(dbgs() << "********** CFG Stackifying **********\n"
492 "********** Function: "
493 << MF.getName() << '\n');
494
495 const auto &MLI = getAnalysis<MachineLoopInfo>();
Dan Gohman32807932015-11-23 16:19:56 +0000496 auto &MDT = getAnalysis<MachineDominatorTree>();
Derek Schuff9c3bf312016-01-13 17:10:28 +0000497 // Liveness is not tracked for EXPR_STACK physreg.
Dan Gohman950a13c2015-09-16 16:51:30 +0000498 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
Dan Gohmaned0f1132016-01-30 05:01:06 +0000499 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
Derek Schuff9c3bf312016-01-13 17:10:28 +0000500 MF.getRegInfo().invalidateLiveness();
Dan Gohman950a13c2015-09-16 16:51:30 +0000501
502 // RPO sorting needs all loops to be single-entry.
503 EliminateMultipleEntryLoops(MF, MLI);
504
505 // Sort the blocks in RPO, with contiguous loops.
506 SortBlocks(MF, MLI);
507
508 // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
Dan Gohmaned0f1132016-01-30 05:01:06 +0000509 PlaceMarkers(MF, MLI, TII, MDT, MFI);
Dan Gohman32807932015-11-23 16:19:56 +0000510
Dan Gohman950a13c2015-09-16 16:51:30 +0000511 return true;
512}