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
115f8f34e4SAdrian Prantl /// This file implements a CFG stacking pass.
12950a13cfSDan Gohman ///
13f52ee17aSDan 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 "MCTargetDesc/WebAssemblyMCTargetDesc.h"
226bda14b3SChandler Carruth #include "WebAssembly.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;
6040926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
6140926451SJacob Gravelle                 "Insert BLOCK and LOOP markers for WebAssembly scopes",
6240926451SJacob Gravelle                 false, false)
6340926451SJacob Gravelle 
64950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
65950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
66950a13cfSDan Gohman }
67950a13cfSDan Gohman 
68b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
69b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
70b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
71b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
72b3aa1ecaSDan Gohman /// explicit mentions.
7335e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred,
7435e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
75b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
76b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
77b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
78b3aa1ecaSDan Gohman         return true;
79b3aa1ecaSDan Gohman   return false;
80b3aa1ecaSDan Gohman }
81b3aa1ecaSDan Gohman 
8232807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
833a643e8dSDan Gohman static void PlaceBlockMarker(
843a643e8dSDan Gohman     MachineBasicBlock &MBB, MachineFunction &MF,
858fe7e86bSDan Gohman     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
862726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &BlockTops,
872726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &LoopTops,
8832807932SDan Gohman     const WebAssemblyInstrInfo &TII,
898fe7e86bSDan Gohman     const MachineLoopInfo &MLI,
90ed0f1138SDan Gohman     MachineDominatorTree &MDT,
91ed0f1138SDan Gohman     WebAssemblyFunctionInfo &MFI) {
928fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
938fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
948fe7e86bSDan Gohman   // which reduces overall stack height.
9532807932SDan Gohman   MachineBasicBlock *Header = nullptr;
9632807932SDan Gohman   bool IsBranchedTo = false;
9732807932SDan Gohman   int MBBNumber = MBB.getNumber();
9832807932SDan Gohman   for (MachineBasicBlock *Pred : MBB.predecessors())
9932807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
10032807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
101b3aa1ecaSDan Gohman       if (ExplicitlyBranchesTo(Pred, &MBB))
10232807932SDan Gohman         IsBranchedTo = true;
10332807932SDan Gohman     }
10432807932SDan Gohman   if (!Header)
10532807932SDan Gohman     return;
10632807932SDan Gohman   if (!IsBranchedTo)
10732807932SDan Gohman     return;
10832807932SDan Gohman 
1098fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
110ef0a45aaSBenjamin Kramer   MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB));
1118fe7e86bSDan Gohman 
1128fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
1138fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
1148fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
1158fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
1168fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
1178fe7e86bSDan Gohman         // Skip over an intervening scope.
118ef0a45aaSBenjamin Kramer         I = std::next(MachineFunction::iterator(ScopeTop));
1198fe7e86bSDan Gohman       } else {
1208fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
1218fe7e86bSDan Gohman         Header = ScopeTop;
1228fe7e86bSDan Gohman         break;
1238fe7e86bSDan Gohman       }
1248fe7e86bSDan Gohman     }
1258fe7e86bSDan Gohman   }
1268fe7e86bSDan Gohman 
1278fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
12832807932SDan Gohman   MachineBasicBlock::iterator InsertPos;
12932807932SDan Gohman   MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
1308fe7e86bSDan Gohman   if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
1318fe7e86bSDan Gohman     // Header is the header of a loop that does not lexically contain MBB, so
132a187ab2aSDan Gohman     // the BLOCK needs to be above the LOOP, after any END constructs.
13332807932SDan Gohman     InsertPos = Header->begin();
1343a643e8dSDan Gohman     while (InsertPos->getOpcode() == WebAssembly::END_BLOCK ||
1353a643e8dSDan Gohman            InsertPos->getOpcode() == WebAssembly::END_LOOP)
136a187ab2aSDan Gohman       ++InsertPos;
13732807932SDan Gohman   } else {
1388887d1faSDan Gohman     // Otherwise, insert the BLOCK as late in Header as we can, but before the
1398887d1faSDan Gohman     // beginning of the local expression tree and any nested BLOCKs.
14032807932SDan Gohman     InsertPos = Header->getFirstTerminator();
141ef0a45aaSBenjamin Kramer     while (InsertPos != Header->begin() &&
1424fc4e42dSDan Gohman            WebAssembly::isChild(*std::prev(InsertPos), MFI) &&
143ef0a45aaSBenjamin Kramer            std::prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
144ef0a45aaSBenjamin Kramer            std::prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
145ef0a45aaSBenjamin Kramer            std::prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
14632807932SDan Gohman       --InsertPos;
14732807932SDan Gohman   }
1482b8158f4SHeejin Ahn   // The header block in which a 'block' mark will be inserted should have a
1492b8158f4SHeejin Ahn   // terminator because it is branching to a non-layout successor.
1502b8158f4SHeejin Ahn   assert(InsertPos != Header->end());
15132807932SDan Gohman 
1528fe7e86bSDan Gohman   // Add the BLOCK.
15392401cc1SHeejin Ahn   MachineInstr *Begin =
15492401cc1SHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
1552726b88cSDan Gohman               TII.get(WebAssembly::BLOCK))
1564fc4e42dSDan Gohman           .addImm(int64_t(WebAssembly::ExprType::Void));
1571d68e80fSDan Gohman 
1581d68e80fSDan Gohman   // Mark the end of the block.
1591d68e80fSDan Gohman   InsertPos = MBB.begin();
1601d68e80fSDan Gohman   while (InsertPos != MBB.end() &&
1613a643e8dSDan Gohman          InsertPos->getOpcode() == WebAssembly::END_LOOP &&
1622726b88cSDan Gohman          LoopTops[&*InsertPos]->getParent()->getNumber() >= Header->getNumber())
1631d68e80fSDan Gohman     ++InsertPos;
16410b31358SDerek Schuff   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
1652726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
1662726b88cSDan Gohman   BlockTops[End] = Begin;
1678fe7e86bSDan Gohman 
1688fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
1698fe7e86bSDan Gohman   int Number = MBB.getNumber();
1708fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
1718fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
1728fe7e86bSDan Gohman     ScopeTops[Number] = Header;
173950a13cfSDan Gohman }
174950a13cfSDan Gohman 
1758fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
1761d68e80fSDan Gohman static void PlaceLoopMarker(
1771d68e80fSDan Gohman     MachineBasicBlock &MBB, MachineFunction &MF,
1788fe7e86bSDan Gohman     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
1792726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &LoopTops,
1801d68e80fSDan Gohman     const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
1818fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
1828fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
1838fe7e86bSDan Gohman     return;
1848fe7e86bSDan Gohman 
1858fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
1868fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
1878fe7e86bSDan Gohman   MachineBasicBlock *Bottom = LoopBottom(Loop);
188ef0a45aaSBenjamin Kramer   auto Iter = std::next(MachineFunction::iterator(Bottom));
189e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
190f6857223SDan Gohman     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
191f6857223SDan Gohman     // Give it a fake predecessor so that AsmPrinter prints its label.
192f6857223SDan Gohman     Label->addSuccessor(Label);
193f6857223SDan Gohman     MF.push_back(Label);
194ef0a45aaSBenjamin Kramer     Iter = std::next(MachineFunction::iterator(Bottom));
195e3e4a5ffSDan Gohman   }
1968fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
197f6857223SDan Gohman 
1981d68e80fSDan Gohman   // Mark the beginning of the loop (after the end of any existing loop that
1991d68e80fSDan Gohman   // ends here).
2001d68e80fSDan Gohman   auto InsertPos = MBB.begin();
2011d68e80fSDan Gohman   while (InsertPos != MBB.end() &&
2021d68e80fSDan Gohman          InsertPos->getOpcode() == WebAssembly::END_LOOP)
2031d68e80fSDan Gohman     ++InsertPos;
20410b31358SDerek Schuff   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
2052726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
2064fc4e42dSDan Gohman                             .addImm(int64_t(WebAssembly::ExprType::Void));
2071d68e80fSDan Gohman 
20810b31358SDerek Schuff   // Mark the end of the loop (using arbitrary debug location that branched
20910b31358SDerek Schuff   // to the loop end as its location).
21010b31358SDerek Schuff   DebugLoc EndDL = (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
21110b31358SDerek Schuff   MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), EndDL,
2121d68e80fSDan Gohman                               TII.get(WebAssembly::END_LOOP));
2132726b88cSDan Gohman   LoopTops[End] = Begin;
2148fe7e86bSDan Gohman 
2158fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
2168fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
217442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
2188fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
2198fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
220e3e4a5ffSDan Gohman }
221950a13cfSDan Gohman 
2221d68e80fSDan Gohman static unsigned
2231d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
2241d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
2251d68e80fSDan Gohman   unsigned Depth = 0;
2261d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
2271d68e80fSDan Gohman     if (X == MBB)
2281d68e80fSDan Gohman       break;
2291d68e80fSDan Gohman     ++Depth;
2301d68e80fSDan Gohman   }
2311d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
2321d68e80fSDan Gohman   return Depth;
2331d68e80fSDan Gohman }
2341d68e80fSDan Gohman 
2352726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
2362726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
2372726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
2382726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
2392726b88cSDan Gohman /// that end at the function end need to have a return type signature that
2402726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
2412726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
2422726b88cSDan Gohman static void FixEndsAtEndOfFunction(
2432726b88cSDan Gohman     MachineFunction &MF,
2442726b88cSDan Gohman     const WebAssemblyFunctionInfo &MFI,
2452726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &BlockTops,
2462726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &LoopTops) {
2472726b88cSDan Gohman   assert(MFI.getResults().size() <= 1);
2482726b88cSDan Gohman 
2492726b88cSDan Gohman   if (MFI.getResults().empty())
2502726b88cSDan Gohman     return;
2512726b88cSDan Gohman 
2522726b88cSDan Gohman   WebAssembly::ExprType retType;
2532726b88cSDan Gohman   switch (MFI.getResults().front().SimpleTy) {
2544fc4e42dSDan Gohman   case MVT::i32: retType = WebAssembly::ExprType::I32; break;
2554fc4e42dSDan Gohman   case MVT::i64: retType = WebAssembly::ExprType::I64; break;
2564fc4e42dSDan Gohman   case MVT::f32: retType = WebAssembly::ExprType::F32; break;
2574fc4e42dSDan Gohman   case MVT::f64: retType = WebAssembly::ExprType::F64; break;
2584fc4e42dSDan Gohman   case MVT::v16i8: retType = WebAssembly::ExprType::I8x16; break;
2594fc4e42dSDan Gohman   case MVT::v8i16: retType = WebAssembly::ExprType::I16x8; break;
2604fc4e42dSDan Gohman   case MVT::v4i32: retType = WebAssembly::ExprType::I32x4; break;
2614fc4e42dSDan Gohman   case MVT::v4f32: retType = WebAssembly::ExprType::F32x4; break;
2620de58729SHeejin Ahn   case MVT::ExceptRef: retType = WebAssembly::ExprType::ExceptRef; break;
2632726b88cSDan Gohman   default: llvm_unreachable("unexpected return type");
2642726b88cSDan Gohman   }
2652726b88cSDan Gohman 
2662726b88cSDan Gohman   for (MachineBasicBlock &MBB : reverse(MF)) {
2672726b88cSDan Gohman     for (MachineInstr &MI : reverse(MBB)) {
268*801bf7ebSShiva Chen       if (MI.isPosition() || MI.isDebugInstr())
2692726b88cSDan Gohman         continue;
2702726b88cSDan Gohman       if (MI.getOpcode() == WebAssembly::END_BLOCK) {
2712726b88cSDan Gohman         BlockTops[&MI]->getOperand(0).setImm(int32_t(retType));
2722726b88cSDan Gohman         continue;
2732726b88cSDan Gohman       }
2742726b88cSDan Gohman       if (MI.getOpcode() == WebAssembly::END_LOOP) {
2752726b88cSDan Gohman         LoopTops[&MI]->getOperand(0).setImm(int32_t(retType));
2762726b88cSDan Gohman         continue;
2772726b88cSDan Gohman       }
2782726b88cSDan Gohman       // Something other than an `end`. We're done.
2792726b88cSDan Gohman       return;
2802726b88cSDan Gohman     }
2812726b88cSDan Gohman   }
2822726b88cSDan Gohman }
2832726b88cSDan Gohman 
284d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
285d934cb88SDan Gohman // were a block.
286d934cb88SDan Gohman static void AppendEndToFunction(
287d934cb88SDan Gohman     MachineFunction &MF,
288d934cb88SDan Gohman     const WebAssemblyInstrInfo &TII) {
28910b31358SDerek Schuff   BuildMI(MF.back(), MF.back().end(),
29010b31358SDerek Schuff           MF.back().findPrevDebugLoc(MF.back().end()),
291d934cb88SDan Gohman           TII.get(WebAssembly::END_FUNCTION));
292d934cb88SDan Gohman }
293d934cb88SDan Gohman 
2948fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places.
2958fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
2968fe7e86bSDan Gohman                          const WebAssemblyInstrInfo &TII,
297ed0f1138SDan Gohman                          MachineDominatorTree &MDT,
298ed0f1138SDan Gohman                          WebAssemblyFunctionInfo &MFI) {
2998fe7e86bSDan Gohman   // For each block whose label represents the end of a scope, record the block
3008fe7e86bSDan Gohman   // which holds the beginning of the scope. This will allow us to quickly skip
3018fe7e86bSDan Gohman   // over scoped regions when walking blocks. We allocate one more than the
3028fe7e86bSDan Gohman   // number of blocks in the function to accommodate for the possible fake block
3038fe7e86bSDan Gohman   // we may insert at the end.
3048fe7e86bSDan Gohman   SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
3058fe7e86bSDan Gohman 
3062726b88cSDan Gohman   // For each LOOP_END, the corresponding LOOP.
3072726b88cSDan Gohman   DenseMap<const MachineInstr *, MachineInstr *> LoopTops;
3082726b88cSDan Gohman 
3092726b88cSDan Gohman   // For each END_BLOCK, the corresponding BLOCK.
3102726b88cSDan Gohman   DenseMap<const MachineInstr *, MachineInstr *> BlockTops;
3111d68e80fSDan Gohman 
3128fe7e86bSDan Gohman   for (auto &MBB : MF) {
3138fe7e86bSDan Gohman     // Place the LOOP for MBB if MBB is the header of a loop.
3141d68e80fSDan Gohman     PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
3158fe7e86bSDan Gohman 
31632807932SDan Gohman     // Place the BLOCK for MBB if MBB is branched to from above.
3172726b88cSDan Gohman     PlaceBlockMarker(MBB, MF, ScopeTops, BlockTops, LoopTops, TII, MLI, MDT, MFI);
318950a13cfSDan Gohman   }
319950a13cfSDan Gohman 
3201d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
3211d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
3221d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
3231d68e80fSDan Gohman     for (auto &MI : reverse(MBB)) {
3241d68e80fSDan Gohman       switch (MI.getOpcode()) {
3251d68e80fSDan Gohman       case WebAssembly::BLOCK:
3263a643e8dSDan Gohman         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= MBB.getNumber() &&
3271d68e80fSDan Gohman                "Block should be balanced");
3281d68e80fSDan Gohman         Stack.pop_back();
3291d68e80fSDan Gohman         break;
3301d68e80fSDan Gohman       case WebAssembly::LOOP:
3311d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
3321d68e80fSDan Gohman         Stack.pop_back();
3331d68e80fSDan Gohman         break;
3341d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
3351d68e80fSDan Gohman         Stack.push_back(&MBB);
3361d68e80fSDan Gohman         break;
3371d68e80fSDan Gohman       case WebAssembly::END_LOOP:
3382726b88cSDan Gohman         Stack.push_back(LoopTops[&MI]->getParent());
3391d68e80fSDan Gohman         break;
3401d68e80fSDan Gohman       default:
3411d68e80fSDan Gohman         if (MI.isTerminator()) {
3421d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
3431d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
3441d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
3451d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
3461d68e80fSDan Gohman           for (auto MO : Ops) {
3471d68e80fSDan Gohman             if (MO.isMBB())
3481d68e80fSDan Gohman               MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
3491d68e80fSDan Gohman             MI.addOperand(MF, MO);
35032807932SDan Gohman           }
3511d68e80fSDan Gohman         }
3521d68e80fSDan Gohman         break;
3531d68e80fSDan Gohman       }
3541d68e80fSDan Gohman     }
3551d68e80fSDan Gohman   }
3561d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
3572726b88cSDan Gohman 
3582726b88cSDan Gohman   // Fix up block/loop signatures at the end of the function to conform to
3592726b88cSDan Gohman   // WebAssembly's rules.
3602726b88cSDan Gohman   FixEndsAtEndOfFunction(MF, MFI, BlockTops, LoopTops);
361d934cb88SDan Gohman 
362d934cb88SDan Gohman   // Add an end instruction at the end of the function body.
363d934cb88SDan Gohman   if (!MF.getSubtarget<WebAssemblySubtarget>()
364d934cb88SDan Gohman         .getTargetTriple().isOSBinFormatELF())
365d934cb88SDan Gohman     AppendEndToFunction(MF, TII);
3661d68e80fSDan Gohman }
36732807932SDan Gohman 
368950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
369950a13cfSDan Gohman   DEBUG(dbgs() << "********** CFG Stackifying **********\n"
370950a13cfSDan Gohman                   "********** Function: "
371950a13cfSDan Gohman                << MF.getName() << '\n');
372950a13cfSDan Gohman 
373950a13cfSDan Gohman   const auto &MLI = getAnalysis<MachineLoopInfo>();
37432807932SDan Gohman   auto &MDT = getAnalysis<MachineDominatorTree>();
375e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
376950a13cfSDan Gohman   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
377ed0f1138SDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
3789c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
379950a13cfSDan Gohman 
380950a13cfSDan Gohman   // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
381ed0f1138SDan Gohman   PlaceMarkers(MF, MLI, TII, MDT, MFI);
38232807932SDan Gohman 
383950a13cfSDan Gohman   return true;
384950a13cfSDan Gohman }
385