1950a13cfSDan Gohman //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2950a13cfSDan Gohman //
3950a13cfSDan Gohman //                     The LLVM Compiler Infrastructure
4950a13cfSDan Gohman //
5950a13cfSDan Gohman // This file is distributed under the University of Illinois Open Source
6950a13cfSDan Gohman // License. See LICENSE.TXT for details.
7950a13cfSDan Gohman //
8950a13cfSDan Gohman //===----------------------------------------------------------------------===//
9950a13cfSDan Gohman ///
10950a13cfSDan Gohman /// \file
11950a13cfSDan Gohman /// \brief This file implements a CFG stacking pass.
12950a13cfSDan Gohman ///
13*f52ee17aSDan Gohman /// This pass inserts BLOCK and LOOP markers to mark the start of scopes, since
14950a13cfSDan Gohman /// scope boundaries serve as the labels for WebAssembly's control transfers.
15950a13cfSDan Gohman ///
16950a13cfSDan Gohman /// This is sufficient to convert arbitrary CFGs into a form that works on
17950a13cfSDan Gohman /// WebAssembly, provided that all loops are single-entry.
18950a13cfSDan Gohman ///
19950a13cfSDan Gohman //===----------------------------------------------------------------------===//
20950a13cfSDan Gohman 
21950a13cfSDan Gohman #include "WebAssembly.h"
22950a13cfSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
23ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
24950a13cfSDan Gohman #include "WebAssemblySubtarget.h"
254fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
2632807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
27950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h"
28950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
29950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h"
309c3bf318SDerek Schuff #include "llvm/CodeGen/MachineRegisterInfo.h"
31950a13cfSDan Gohman #include "llvm/CodeGen/Passes.h"
32950a13cfSDan Gohman #include "llvm/Support/Debug.h"
33950a13cfSDan Gohman #include "llvm/Support/raw_ostream.h"
34950a13cfSDan Gohman using namespace llvm;
35950a13cfSDan Gohman 
36950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify"
37950a13cfSDan Gohman 
38950a13cfSDan Gohman namespace {
39950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass {
40117296c0SMehdi Amini   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
41950a13cfSDan Gohman 
42950a13cfSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
43950a13cfSDan Gohman     AU.setPreservesCFG();
4432807932SDan Gohman     AU.addRequired<MachineDominatorTree>();
4532807932SDan Gohman     AU.addPreserved<MachineDominatorTree>();
46950a13cfSDan Gohman     AU.addRequired<MachineLoopInfo>();
47950a13cfSDan Gohman     AU.addPreserved<MachineLoopInfo>();
48950a13cfSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
49950a13cfSDan Gohman   }
50950a13cfSDan Gohman 
51950a13cfSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
52950a13cfSDan Gohman 
53950a13cfSDan Gohman public:
54950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
55950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
56950a13cfSDan Gohman };
57950a13cfSDan Gohman } // end anonymous namespace
58950a13cfSDan Gohman 
59950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
60950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
61950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
62950a13cfSDan Gohman }
63950a13cfSDan Gohman 
64b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
65b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
66b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
67b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
68b3aa1ecaSDan Gohman /// explicit mentions.
6935e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred,
7035e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
71b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
72b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
73b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
74b3aa1ecaSDan Gohman         return true;
75b3aa1ecaSDan Gohman   return false;
76b3aa1ecaSDan Gohman }
77b3aa1ecaSDan Gohman 
7832807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
793a643e8dSDan Gohman static void PlaceBlockMarker(
803a643e8dSDan Gohman     MachineBasicBlock &MBB, MachineFunction &MF,
818fe7e86bSDan Gohman     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
822726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &BlockTops,
832726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &LoopTops,
8432807932SDan Gohman     const WebAssemblyInstrInfo &TII,
858fe7e86bSDan Gohman     const MachineLoopInfo &MLI,
86ed0f1138SDan Gohman     MachineDominatorTree &MDT,
87ed0f1138SDan Gohman     WebAssemblyFunctionInfo &MFI) {
888fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
898fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
908fe7e86bSDan Gohman   // which reduces overall stack height.
9132807932SDan Gohman   MachineBasicBlock *Header = nullptr;
9232807932SDan Gohman   bool IsBranchedTo = false;
9332807932SDan Gohman   int MBBNumber = MBB.getNumber();
9432807932SDan Gohman   for (MachineBasicBlock *Pred : MBB.predecessors())
9532807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
9632807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
97b3aa1ecaSDan Gohman       if (ExplicitlyBranchesTo(Pred, &MBB))
9832807932SDan Gohman         IsBranchedTo = true;
9932807932SDan Gohman     }
10032807932SDan Gohman   if (!Header)
10132807932SDan Gohman     return;
10232807932SDan Gohman   if (!IsBranchedTo)
10332807932SDan Gohman     return;
10432807932SDan Gohman 
1058fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
106ef0a45aaSBenjamin Kramer   MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB));
1078fe7e86bSDan Gohman 
1088fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
1098fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
1108fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
1118fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
1128fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
1138fe7e86bSDan Gohman         // Skip over an intervening scope.
114ef0a45aaSBenjamin Kramer         I = std::next(MachineFunction::iterator(ScopeTop));
1158fe7e86bSDan Gohman       } else {
1168fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
1178fe7e86bSDan Gohman         Header = ScopeTop;
1188fe7e86bSDan Gohman         break;
1198fe7e86bSDan Gohman       }
1208fe7e86bSDan Gohman     }
1218fe7e86bSDan Gohman   }
1228fe7e86bSDan Gohman 
1238fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
12432807932SDan Gohman   MachineBasicBlock::iterator InsertPos;
12532807932SDan Gohman   MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
1268fe7e86bSDan Gohman   if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
1278fe7e86bSDan Gohman     // Header is the header of a loop that does not lexically contain MBB, so
128a187ab2aSDan Gohman     // the BLOCK needs to be above the LOOP, after any END constructs.
12932807932SDan Gohman     InsertPos = Header->begin();
1303a643e8dSDan Gohman     while (InsertPos->getOpcode() == WebAssembly::END_BLOCK ||
1313a643e8dSDan Gohman            InsertPos->getOpcode() == WebAssembly::END_LOOP)
132a187ab2aSDan Gohman       ++InsertPos;
13332807932SDan Gohman   } else {
1348887d1faSDan Gohman     // Otherwise, insert the BLOCK as late in Header as we can, but before the
1358887d1faSDan Gohman     // beginning of the local expression tree and any nested BLOCKs.
13632807932SDan Gohman     InsertPos = Header->getFirstTerminator();
137ef0a45aaSBenjamin Kramer     while (InsertPos != Header->begin() &&
1384fc4e42dSDan Gohman            WebAssembly::isChild(*std::prev(InsertPos), MFI) &&
139ef0a45aaSBenjamin Kramer            std::prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
140ef0a45aaSBenjamin Kramer            std::prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
141ef0a45aaSBenjamin Kramer            std::prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
14232807932SDan Gohman       --InsertPos;
14332807932SDan Gohman   }
14432807932SDan Gohman 
1458fe7e86bSDan Gohman   // Add the BLOCK.
1462726b88cSDan Gohman   MachineInstr *Begin = BuildMI(*Header, InsertPos, DebugLoc(),
1472726b88cSDan Gohman                                 TII.get(WebAssembly::BLOCK))
1484fc4e42dSDan Gohman       .addImm(int64_t(WebAssembly::ExprType::Void));
1491d68e80fSDan Gohman 
1501d68e80fSDan Gohman   // Mark the end of the block.
1511d68e80fSDan Gohman   InsertPos = MBB.begin();
1521d68e80fSDan Gohman   while (InsertPos != MBB.end() &&
1533a643e8dSDan Gohman          InsertPos->getOpcode() == WebAssembly::END_LOOP &&
1542726b88cSDan Gohman          LoopTops[&*InsertPos]->getParent()->getNumber() >= Header->getNumber())
1551d68e80fSDan Gohman     ++InsertPos;
1562726b88cSDan Gohman   MachineInstr *End = BuildMI(MBB, InsertPos, DebugLoc(),
1572726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
1582726b88cSDan Gohman   BlockTops[End] = Begin;
1598fe7e86bSDan Gohman 
1608fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
1618fe7e86bSDan Gohman   int Number = MBB.getNumber();
1628fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
1638fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
1648fe7e86bSDan Gohman     ScopeTops[Number] = Header;
165950a13cfSDan Gohman }
166950a13cfSDan Gohman 
1678fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
1681d68e80fSDan Gohman static void PlaceLoopMarker(
1691d68e80fSDan Gohman     MachineBasicBlock &MBB, MachineFunction &MF,
1708fe7e86bSDan Gohman     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
1712726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &LoopTops,
1721d68e80fSDan Gohman     const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
1738fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
1748fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
1758fe7e86bSDan Gohman     return;
1768fe7e86bSDan Gohman 
1778fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
1788fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
1798fe7e86bSDan Gohman   MachineBasicBlock *Bottom = LoopBottom(Loop);
180ef0a45aaSBenjamin Kramer   auto Iter = std::next(MachineFunction::iterator(Bottom));
181e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
182f6857223SDan Gohman     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
183f6857223SDan Gohman     // Give it a fake predecessor so that AsmPrinter prints its label.
184f6857223SDan Gohman     Label->addSuccessor(Label);
185f6857223SDan Gohman     MF.push_back(Label);
186ef0a45aaSBenjamin Kramer     Iter = std::next(MachineFunction::iterator(Bottom));
187e3e4a5ffSDan Gohman   }
1888fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
189f6857223SDan Gohman 
1901d68e80fSDan Gohman   // Mark the beginning of the loop (after the end of any existing loop that
1911d68e80fSDan Gohman   // ends here).
1921d68e80fSDan Gohman   auto InsertPos = MBB.begin();
1931d68e80fSDan Gohman   while (InsertPos != MBB.end() &&
1941d68e80fSDan Gohman          InsertPos->getOpcode() == WebAssembly::END_LOOP)
1951d68e80fSDan Gohman     ++InsertPos;
1962726b88cSDan Gohman   MachineInstr *Begin = BuildMI(MBB, InsertPos, DebugLoc(),
1972726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
1984fc4e42dSDan Gohman       .addImm(int64_t(WebAssembly::ExprType::Void));
1991d68e80fSDan Gohman 
2001d68e80fSDan Gohman   // Mark the end of the loop.
2011d68e80fSDan Gohman   MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(),
2021d68e80fSDan Gohman                               TII.get(WebAssembly::END_LOOP));
2032726b88cSDan Gohman   LoopTops[End] = Begin;
2048fe7e86bSDan Gohman 
2058fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
2068fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
207442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
2088fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
2098fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
210e3e4a5ffSDan Gohman }
211950a13cfSDan Gohman 
2121d68e80fSDan Gohman static unsigned
2131d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
2141d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
2151d68e80fSDan Gohman   unsigned Depth = 0;
2161d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
2171d68e80fSDan Gohman     if (X == MBB)
2181d68e80fSDan Gohman       break;
2191d68e80fSDan Gohman     ++Depth;
2201d68e80fSDan Gohman   }
2211d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
2221d68e80fSDan Gohman   return Depth;
2231d68e80fSDan Gohman }
2241d68e80fSDan Gohman 
2252726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
2262726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
2272726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
2282726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
2292726b88cSDan Gohman /// that end at the function end need to have a return type signature that
2302726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
2312726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
2322726b88cSDan Gohman static void FixEndsAtEndOfFunction(
2332726b88cSDan Gohman     MachineFunction &MF,
2342726b88cSDan Gohman     const WebAssemblyFunctionInfo &MFI,
2352726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &BlockTops,
2362726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &LoopTops) {
2372726b88cSDan Gohman   assert(MFI.getResults().size() <= 1);
2382726b88cSDan Gohman 
2392726b88cSDan Gohman   if (MFI.getResults().empty())
2402726b88cSDan Gohman     return;
2412726b88cSDan Gohman 
2422726b88cSDan Gohman   WebAssembly::ExprType retType;
2432726b88cSDan Gohman   switch (MFI.getResults().front().SimpleTy) {
2444fc4e42dSDan Gohman   case MVT::i32: retType = WebAssembly::ExprType::I32; break;
2454fc4e42dSDan Gohman   case MVT::i64: retType = WebAssembly::ExprType::I64; break;
2464fc4e42dSDan Gohman   case MVT::f32: retType = WebAssembly::ExprType::F32; break;
2474fc4e42dSDan Gohman   case MVT::f64: retType = WebAssembly::ExprType::F64; break;
2484fc4e42dSDan Gohman   case MVT::v16i8: retType = WebAssembly::ExprType::I8x16; break;
2494fc4e42dSDan Gohman   case MVT::v8i16: retType = WebAssembly::ExprType::I16x8; break;
2504fc4e42dSDan Gohman   case MVT::v4i32: retType = WebAssembly::ExprType::I32x4; break;
2514fc4e42dSDan Gohman   case MVT::v4f32: retType = WebAssembly::ExprType::F32x4; break;
2522726b88cSDan Gohman   default: llvm_unreachable("unexpected return type");
2532726b88cSDan Gohman   }
2542726b88cSDan Gohman 
2552726b88cSDan Gohman   for (MachineBasicBlock &MBB : reverse(MF)) {
2562726b88cSDan Gohman     for (MachineInstr &MI : reverse(MBB)) {
2572726b88cSDan Gohman       if (MI.isPosition() || MI.isDebugValue())
2582726b88cSDan Gohman         continue;
2592726b88cSDan Gohman       if (MI.getOpcode() == WebAssembly::END_BLOCK) {
2602726b88cSDan Gohman         BlockTops[&MI]->getOperand(0).setImm(int32_t(retType));
2612726b88cSDan Gohman         continue;
2622726b88cSDan Gohman       }
2632726b88cSDan Gohman       if (MI.getOpcode() == WebAssembly::END_LOOP) {
2642726b88cSDan Gohman         LoopTops[&MI]->getOperand(0).setImm(int32_t(retType));
2652726b88cSDan Gohman         continue;
2662726b88cSDan Gohman       }
2672726b88cSDan Gohman       // Something other than an `end`. We're done.
2682726b88cSDan Gohman       return;
2692726b88cSDan Gohman     }
2702726b88cSDan Gohman   }
2712726b88cSDan Gohman }
2722726b88cSDan Gohman 
273d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
274d934cb88SDan Gohman // were a block.
275d934cb88SDan Gohman static void AppendEndToFunction(
276d934cb88SDan Gohman     MachineFunction &MF,
277d934cb88SDan Gohman     const WebAssemblyInstrInfo &TII) {
278d934cb88SDan Gohman   BuildMI(MF.back(), MF.back().end(), DebugLoc(),
279d934cb88SDan Gohman           TII.get(WebAssembly::END_FUNCTION));
280d934cb88SDan Gohman }
281d934cb88SDan Gohman 
2828fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places.
2838fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
2848fe7e86bSDan Gohman                          const WebAssemblyInstrInfo &TII,
285ed0f1138SDan Gohman                          MachineDominatorTree &MDT,
286ed0f1138SDan Gohman                          WebAssemblyFunctionInfo &MFI) {
2878fe7e86bSDan Gohman   // For each block whose label represents the end of a scope, record the block
2888fe7e86bSDan Gohman   // which holds the beginning of the scope. This will allow us to quickly skip
2898fe7e86bSDan Gohman   // over scoped regions when walking blocks. We allocate one more than the
2908fe7e86bSDan Gohman   // number of blocks in the function to accommodate for the possible fake block
2918fe7e86bSDan Gohman   // we may insert at the end.
2928fe7e86bSDan Gohman   SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
2938fe7e86bSDan Gohman 
2942726b88cSDan Gohman   // For each LOOP_END, the corresponding LOOP.
2952726b88cSDan Gohman   DenseMap<const MachineInstr *, MachineInstr *> LoopTops;
2962726b88cSDan Gohman 
2972726b88cSDan Gohman   // For each END_BLOCK, the corresponding BLOCK.
2982726b88cSDan Gohman   DenseMap<const MachineInstr *, MachineInstr *> BlockTops;
2991d68e80fSDan Gohman 
3008fe7e86bSDan Gohman   for (auto &MBB : MF) {
3018fe7e86bSDan Gohman     // Place the LOOP for MBB if MBB is the header of a loop.
3021d68e80fSDan Gohman     PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
3038fe7e86bSDan Gohman 
30432807932SDan Gohman     // Place the BLOCK for MBB if MBB is branched to from above.
3052726b88cSDan Gohman     PlaceBlockMarker(MBB, MF, ScopeTops, BlockTops, LoopTops, TII, MLI, MDT, MFI);
306950a13cfSDan Gohman   }
307950a13cfSDan Gohman 
3081d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
3091d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
3101d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
3111d68e80fSDan Gohman     for (auto &MI : reverse(MBB)) {
3121d68e80fSDan Gohman       switch (MI.getOpcode()) {
3131d68e80fSDan Gohman       case WebAssembly::BLOCK:
3143a643e8dSDan Gohman         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= MBB.getNumber() &&
3151d68e80fSDan Gohman                "Block should be balanced");
3161d68e80fSDan Gohman         Stack.pop_back();
3171d68e80fSDan Gohman         break;
3181d68e80fSDan Gohman       case WebAssembly::LOOP:
3191d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
3201d68e80fSDan Gohman         Stack.pop_back();
3211d68e80fSDan Gohman         break;
3221d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
3231d68e80fSDan Gohman         Stack.push_back(&MBB);
3241d68e80fSDan Gohman         break;
3251d68e80fSDan Gohman       case WebAssembly::END_LOOP:
3262726b88cSDan Gohman         Stack.push_back(LoopTops[&MI]->getParent());
3271d68e80fSDan Gohman         break;
3281d68e80fSDan Gohman       default:
3291d68e80fSDan Gohman         if (MI.isTerminator()) {
3301d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
3311d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
3321d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
3331d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
3341d68e80fSDan Gohman           for (auto MO : Ops) {
3351d68e80fSDan Gohman             if (MO.isMBB())
3361d68e80fSDan Gohman               MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
3371d68e80fSDan Gohman             MI.addOperand(MF, MO);
33832807932SDan Gohman           }
3391d68e80fSDan Gohman         }
3401d68e80fSDan Gohman         break;
3411d68e80fSDan Gohman       }
3421d68e80fSDan Gohman     }
3431d68e80fSDan Gohman   }
3441d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
3452726b88cSDan Gohman 
3462726b88cSDan Gohman   // Fix up block/loop signatures at the end of the function to conform to
3472726b88cSDan Gohman   // WebAssembly's rules.
3482726b88cSDan Gohman   FixEndsAtEndOfFunction(MF, MFI, BlockTops, LoopTops);
349d934cb88SDan Gohman 
350d934cb88SDan Gohman   // Add an end instruction at the end of the function body.
351d934cb88SDan Gohman   if (!MF.getSubtarget<WebAssemblySubtarget>()
352d934cb88SDan Gohman         .getTargetTriple().isOSBinFormatELF())
353d934cb88SDan Gohman     AppendEndToFunction(MF, TII);
3541d68e80fSDan Gohman }
35532807932SDan Gohman 
356950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
357950a13cfSDan Gohman   DEBUG(dbgs() << "********** CFG Stackifying **********\n"
358950a13cfSDan Gohman                   "********** Function: "
359950a13cfSDan Gohman                << MF.getName() << '\n');
360950a13cfSDan Gohman 
361950a13cfSDan Gohman   const auto &MLI = getAnalysis<MachineLoopInfo>();
36232807932SDan Gohman   auto &MDT = getAnalysis<MachineDominatorTree>();
363e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
364950a13cfSDan Gohman   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
365ed0f1138SDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
3669c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
367950a13cfSDan Gohman 
368950a13cfSDan Gohman   // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
369ed0f1138SDan Gohman   PlaceMarkers(MF, MLI, TII, MDT, MFI);
37032807932SDan Gohman 
371950a13cfSDan Gohman   return true;
372950a13cfSDan Gohman }
373