1950a13cfSDan Gohman //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2950a13cfSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6950a13cfSDan Gohman //
7950a13cfSDan Gohman //===----------------------------------------------------------------------===//
8950a13cfSDan Gohman ///
9950a13cfSDan Gohman /// \file
105f8f34e4SAdrian Prantl /// This file implements a CFG stacking pass.
11950a13cfSDan Gohman ///
12e76fa9ecSHeejin Ahn /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes,
13e76fa9ecSHeejin Ahn /// since scope boundaries serve as the labels for WebAssembly's control
14e76fa9ecSHeejin Ahn /// 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 ///
19e76fa9ecSHeejin Ahn /// In case we use exceptions, this pass also fixes mismatches in unwind
20e76fa9ecSHeejin Ahn /// destinations created during transforming CFG into wasm structured format.
21e76fa9ecSHeejin Ahn ///
22950a13cfSDan Gohman //===----------------------------------------------------------------------===//
23950a13cfSDan Gohman 
246bda14b3SChandler Carruth #include "WebAssembly.h"
25e76fa9ecSHeejin Ahn #include "WebAssemblyExceptionInfo.h"
26ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
27276f9e8cSHeejin Ahn #include "WebAssemblySortRegion.h"
28950a13cfSDan Gohman #include "WebAssemblySubtarget.h"
294fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
30c4ac74fbSHeejin Ahn #include "llvm/ADT/Statistic.h"
3132807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
32950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
33904cd3e0SReid Kleckner #include "llvm/CodeGen/MachineLoopInfo.h"
34e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h"
35fe0006c8SSimon Pilgrim #include "llvm/Target/TargetMachine.h"
36950a13cfSDan Gohman using namespace llvm;
37276f9e8cSHeejin Ahn using WebAssembly::SortRegionInfo;
38950a13cfSDan Gohman 
39950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify"
40950a13cfSDan Gohman 
41c4ac74fbSHeejin Ahn STATISTIC(NumUnwindMismatches, "Number of EH pad unwind mismatches found");
42c4ac74fbSHeejin Ahn 
43950a13cfSDan Gohman namespace {
44950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass {
45117296c0SMehdi Amini   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
46950a13cfSDan Gohman 
47950a13cfSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
4832807932SDan Gohman     AU.addRequired<MachineDominatorTree>();
49950a13cfSDan Gohman     AU.addRequired<MachineLoopInfo>();
50e76fa9ecSHeejin Ahn     AU.addRequired<WebAssemblyExceptionInfo>();
51950a13cfSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
52950a13cfSDan Gohman   }
53950a13cfSDan Gohman 
54950a13cfSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
55950a13cfSDan Gohman 
56e76fa9ecSHeejin Ahn   // For each block whose label represents the end of a scope, record the block
57e76fa9ecSHeejin Ahn   // which holds the beginning of the scope. This will allow us to quickly skip
58e76fa9ecSHeejin Ahn   // over scoped regions when walking blocks.
59e76fa9ecSHeejin Ahn   SmallVector<MachineBasicBlock *, 8> ScopeTops;
60e76fa9ecSHeejin Ahn 
61c4ac74fbSHeejin Ahn   // Placing markers.
62e76fa9ecSHeejin Ahn   void placeMarkers(MachineFunction &MF);
63e76fa9ecSHeejin Ahn   void placeBlockMarker(MachineBasicBlock &MBB);
64e76fa9ecSHeejin Ahn   void placeLoopMarker(MachineBasicBlock &MBB);
65e76fa9ecSHeejin Ahn   void placeTryMarker(MachineBasicBlock &MBB);
66cf699b45SHeejin Ahn   void removeUnnecessaryInstrs(MachineFunction &MF);
67c4ac74fbSHeejin Ahn   bool fixUnwindMismatches(MachineFunction &MF);
68e76fa9ecSHeejin Ahn   void rewriteDepthImmediates(MachineFunction &MF);
69e76fa9ecSHeejin Ahn   void fixEndsAtEndOfFunction(MachineFunction &MF);
70e76fa9ecSHeejin Ahn 
71e76fa9ecSHeejin Ahn   // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY).
72e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
73e76fa9ecSHeejin Ahn   // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY.
74e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
75e76fa9ecSHeejin Ahn   // <TRY marker, EH pad> map
76e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
77e76fa9ecSHeejin Ahn   // <EH pad, TRY marker> map
78e76fa9ecSHeejin Ahn   DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
79e76fa9ecSHeejin Ahn 
80c4ac74fbSHeejin Ahn   // There can be an appendix block at the end of each function, shared for:
81c4ac74fbSHeejin Ahn   // - creating a correct signature for fallthrough returns
82c4ac74fbSHeejin Ahn   // - target for rethrows that need to unwind to the caller, but are trapped
83c4ac74fbSHeejin Ahn   //   inside another try/catch
84c4ac74fbSHeejin Ahn   MachineBasicBlock *AppendixBB = nullptr;
85c4ac74fbSHeejin Ahn   MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
86c4ac74fbSHeejin Ahn     if (!AppendixBB) {
87c4ac74fbSHeejin Ahn       AppendixBB = MF.CreateMachineBasicBlock();
88c4ac74fbSHeejin Ahn       // Give it a fake predecessor so that AsmPrinter prints its label.
89c4ac74fbSHeejin Ahn       AppendixBB->addSuccessor(AppendixBB);
90c4ac74fbSHeejin Ahn       MF.push_back(AppendixBB);
91c4ac74fbSHeejin Ahn     }
92c4ac74fbSHeejin Ahn     return AppendixBB;
93c4ac74fbSHeejin Ahn   }
94c4ac74fbSHeejin Ahn 
95cf699b45SHeejin Ahn   // Helper functions to register / unregister scope information created by
96cf699b45SHeejin Ahn   // marker instructions.
97e76fa9ecSHeejin Ahn   void registerScope(MachineInstr *Begin, MachineInstr *End);
98e76fa9ecSHeejin Ahn   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
99e76fa9ecSHeejin Ahn                         MachineBasicBlock *EHPad);
100cf699b45SHeejin Ahn   void unregisterScope(MachineInstr *Begin);
101e76fa9ecSHeejin Ahn 
102950a13cfSDan Gohman public:
103950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
104950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
105e76fa9ecSHeejin Ahn   ~WebAssemblyCFGStackify() override { releaseMemory(); }
106e76fa9ecSHeejin Ahn   void releaseMemory() override;
107950a13cfSDan Gohman };
108950a13cfSDan Gohman } // end anonymous namespace
109950a13cfSDan Gohman 
110950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
11140926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
112c4ac74fbSHeejin Ahn                 "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false,
113f208f631SHeejin Ahn                 false)
11440926451SJacob Gravelle 
115950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
116950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
117950a13cfSDan Gohman }
118950a13cfSDan Gohman 
119b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
120b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
121b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
122b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
123b3aa1ecaSDan Gohman /// explicit mentions.
12418c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
12535e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
126b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
127b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
128b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
129b3aa1ecaSDan Gohman         return true;
130b3aa1ecaSDan Gohman   return false;
131b3aa1ecaSDan Gohman }
132b3aa1ecaSDan Gohman 
133e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB,
134e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
135e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
136e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only
137e76fa9ecSHeejin Ahn // used for sanity checking.
138e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
13918c56a07SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB,
140e76fa9ecSHeejin Ahn                      const SmallPtrSet<const MachineInstr *, 4> &BeforeSet,
141e76fa9ecSHeejin Ahn                      const SmallPtrSet<const MachineInstr *, 4> &AfterSet) {
142e76fa9ecSHeejin Ahn   auto InsertPos = MBB->end();
143e76fa9ecSHeejin Ahn   while (InsertPos != MBB->begin()) {
144e76fa9ecSHeejin Ahn     if (BeforeSet.count(&*std::prev(InsertPos))) {
145e76fa9ecSHeejin Ahn #ifndef NDEBUG
146e76fa9ecSHeejin Ahn       // Sanity check
147e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
148e76fa9ecSHeejin Ahn         assert(!AfterSet.count(&*std::prev(Pos)));
149e76fa9ecSHeejin Ahn #endif
150e76fa9ecSHeejin Ahn       break;
151e76fa9ecSHeejin Ahn     }
152e76fa9ecSHeejin Ahn     --InsertPos;
153e76fa9ecSHeejin Ahn   }
154e76fa9ecSHeejin Ahn   return InsertPos;
155e76fa9ecSHeejin Ahn }
156e76fa9ecSHeejin Ahn 
157e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB,
158e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
159e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
160e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only
161e76fa9ecSHeejin Ahn // used for sanity checking.
162e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
16318c56a07SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB,
164e76fa9ecSHeejin Ahn                    const SmallPtrSet<const MachineInstr *, 4> &BeforeSet,
165e76fa9ecSHeejin Ahn                    const SmallPtrSet<const MachineInstr *, 4> &AfterSet) {
166e76fa9ecSHeejin Ahn   auto InsertPos = MBB->begin();
167e76fa9ecSHeejin Ahn   while (InsertPos != MBB->end()) {
168e76fa9ecSHeejin Ahn     if (AfterSet.count(&*InsertPos)) {
169e76fa9ecSHeejin Ahn #ifndef NDEBUG
170e76fa9ecSHeejin Ahn       // Sanity check
171e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
172e76fa9ecSHeejin Ahn         assert(!BeforeSet.count(&*Pos));
173e76fa9ecSHeejin Ahn #endif
174e76fa9ecSHeejin Ahn       break;
175e76fa9ecSHeejin Ahn     }
176e76fa9ecSHeejin Ahn     ++InsertPos;
177e76fa9ecSHeejin Ahn   }
178e76fa9ecSHeejin Ahn   return InsertPos;
179e76fa9ecSHeejin Ahn }
180e76fa9ecSHeejin Ahn 
181e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
182e76fa9ecSHeejin Ahn                                            MachineInstr *End) {
183e76fa9ecSHeejin Ahn   BeginToEnd[Begin] = End;
184e76fa9ecSHeejin Ahn   EndToBegin[End] = Begin;
185e76fa9ecSHeejin Ahn }
186e76fa9ecSHeejin Ahn 
187e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
188e76fa9ecSHeejin Ahn                                               MachineInstr *End,
189e76fa9ecSHeejin Ahn                                               MachineBasicBlock *EHPad) {
190e76fa9ecSHeejin Ahn   registerScope(Begin, End);
191e76fa9ecSHeejin Ahn   TryToEHPad[Begin] = EHPad;
192e76fa9ecSHeejin Ahn   EHPadToTry[EHPad] = Begin;
193e76fa9ecSHeejin Ahn }
194e76fa9ecSHeejin Ahn 
195cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
196cf699b45SHeejin Ahn   assert(BeginToEnd.count(Begin));
197cf699b45SHeejin Ahn   MachineInstr *End = BeginToEnd[Begin];
198cf699b45SHeejin Ahn   assert(EndToBegin.count(End));
199cf699b45SHeejin Ahn   BeginToEnd.erase(Begin);
200cf699b45SHeejin Ahn   EndToBegin.erase(End);
201cf699b45SHeejin Ahn   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
202cf699b45SHeejin Ahn   if (EHPad) {
203cf699b45SHeejin Ahn     assert(EHPadToTry.count(EHPad));
204cf699b45SHeejin Ahn     TryToEHPad.erase(Begin);
205cf699b45SHeejin Ahn     EHPadToTry.erase(EHPad);
206cf699b45SHeejin Ahn   }
207cf699b45SHeejin Ahn }
208cf699b45SHeejin Ahn 
20932807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
210c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and
211c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later.
212e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
21344a5a4b1SHeejin Ahn   assert(!MBB.isEHPad());
214e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
215e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
216e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
217e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
218e76fa9ecSHeejin Ahn 
2198fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
2208fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
2218fe7e86bSDan Gohman   // which reduces overall stack height.
22232807932SDan Gohman   MachineBasicBlock *Header = nullptr;
22332807932SDan Gohman   bool IsBranchedTo = false;
22432807932SDan Gohman   int MBBNumber = MBB.getNumber();
225e76fa9ecSHeejin Ahn   for (MachineBasicBlock *Pred : MBB.predecessors()) {
22632807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
22732807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
22852e240a0SHeejin Ahn       if (explicitlyBranchesTo(Pred, &MBB))
22932807932SDan Gohman         IsBranchedTo = true;
23032807932SDan Gohman     }
231e76fa9ecSHeejin Ahn   }
23232807932SDan Gohman   if (!Header)
23332807932SDan Gohman     return;
23432807932SDan Gohman   if (!IsBranchedTo)
23532807932SDan Gohman     return;
23632807932SDan Gohman 
2378fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
2385c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
2398fe7e86bSDan Gohman 
2408fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
2418fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
2428fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
2438fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
2448fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
2458fe7e86bSDan Gohman         // Skip over an intervening scope.
2465c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
2478fe7e86bSDan Gohman       } else {
2488fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
2498fe7e86bSDan Gohman         Header = ScopeTop;
2508fe7e86bSDan Gohman         break;
2518fe7e86bSDan Gohman       }
2528fe7e86bSDan Gohman     }
2538fe7e86bSDan Gohman   }
2548fe7e86bSDan Gohman 
2558fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
256e76fa9ecSHeejin Ahn 
257e76fa9ecSHeejin Ahn   // Instructions that should go before the BLOCK.
258e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
259e76fa9ecSHeejin Ahn   // Instructions that should go after the BLOCK.
260e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
261e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
26244a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
26344a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the BLOCK, because the loop is
26444a5a4b1SHeejin Ahn     // nested in this BLOCK. Otherwise it should be before the BLOCK.
26544a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
26644a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
26744a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
268e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
269e76fa9ecSHeejin Ahn #ifndef NDEBUG
270e76fa9ecSHeejin Ahn       else
271e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
272e76fa9ecSHeejin Ahn #endif
273e76fa9ecSHeejin Ahn     }
274e76fa9ecSHeejin Ahn 
275834debffSHeejin Ahn     // If there is a previously placed BLOCK/TRY marker and its corresponding
276834debffSHeejin Ahn     // END marker is before the current BLOCK's END marker, that should be
277834debffSHeejin Ahn     // placed after this BLOCK. Otherwise it should be placed before this BLOCK
278834debffSHeejin Ahn     // marker.
27944a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
280834debffSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY) {
281834debffSHeejin Ahn       if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
282e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
283834debffSHeejin Ahn #ifndef NDEBUG
284834debffSHeejin Ahn       else
285834debffSHeejin Ahn         BeforeSet.insert(&MI);
286834debffSHeejin Ahn #endif
287834debffSHeejin Ahn     }
288e76fa9ecSHeejin Ahn 
289e76fa9ecSHeejin Ahn #ifndef NDEBUG
290e76fa9ecSHeejin Ahn     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
291e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
292e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
293e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
294e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
295e76fa9ecSHeejin Ahn #endif
296e76fa9ecSHeejin Ahn 
297e76fa9ecSHeejin Ahn     // Terminators should go after the BLOCK.
298e76fa9ecSHeejin Ahn     if (MI.isTerminator())
299e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
300e76fa9ecSHeejin Ahn   }
301e76fa9ecSHeejin Ahn 
302e76fa9ecSHeejin Ahn   // Local expression tree should go after the BLOCK.
303e76fa9ecSHeejin Ahn   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
304e76fa9ecSHeejin Ahn        --I) {
305409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
306409b4391SYury Delendik       continue;
307e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
308e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
309e76fa9ecSHeejin Ahn     else
310e76fa9ecSHeejin Ahn       break;
31132807932SDan Gohman   }
31232807932SDan Gohman 
3138fe7e86bSDan Gohman   // Add the BLOCK.
3142cb27072SThomas Lively   WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
31518c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
31692401cc1SHeejin Ahn   MachineInstr *Begin =
31792401cc1SHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
3182726b88cSDan Gohman               TII.get(WebAssembly::BLOCK))
319d6f48786SHeejin Ahn           .addImm(int64_t(ReturnType));
3201d68e80fSDan Gohman 
321e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_BLOCK.
322e76fa9ecSHeejin Ahn   BeforeSet.clear();
323e76fa9ecSHeejin Ahn   AfterSet.clear();
324e76fa9ecSHeejin Ahn   for (auto &MI : MBB) {
325e76fa9ecSHeejin Ahn #ifndef NDEBUG
326e76fa9ecSHeejin Ahn     // END_BLOCK should precede existing LOOP and TRY markers.
327e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
328e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
329e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
330e76fa9ecSHeejin Ahn #endif
331e76fa9ecSHeejin Ahn 
332e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and the header of the
333e76fa9ecSHeejin Ahn     // loop is above this block's header, the END_LOOP should be placed after
334e76fa9ecSHeejin Ahn     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
335e76fa9ecSHeejin Ahn     // should be placed before the BLOCK. The same for END_TRY.
336e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP ||
337e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY) {
338e76fa9ecSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
339e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
340e76fa9ecSHeejin Ahn #ifndef NDEBUG
341e76fa9ecSHeejin Ahn       else
342e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
343e76fa9ecSHeejin Ahn #endif
344e76fa9ecSHeejin Ahn     }
345e76fa9ecSHeejin Ahn   }
346e76fa9ecSHeejin Ahn 
3471d68e80fSDan Gohman   // Mark the end of the block.
34818c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
34910b31358SDerek Schuff   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
3502726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
351e76fa9ecSHeejin Ahn   registerScope(Begin, End);
3528fe7e86bSDan Gohman 
3538fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
3548fe7e86bSDan Gohman   int Number = MBB.getNumber();
3558fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
3568fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
3578fe7e86bSDan Gohman     ScopeTops[Number] = Header;
358950a13cfSDan Gohman }
359950a13cfSDan Gohman 
3608fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
361e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
362e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
363e76fa9ecSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
364276f9e8cSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
365276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
366e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
367e76fa9ecSHeejin Ahn 
3688fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
3698fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
3708fe7e86bSDan Gohman     return;
3718fe7e86bSDan Gohman 
3728fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
3738fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
374276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(Loop);
3755c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
376e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
377c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
3785c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
379e3e4a5ffSDan Gohman   }
3808fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
381f6857223SDan Gohman 
382e76fa9ecSHeejin Ahn   // Decide where in Header to put the LOOP.
383e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
384e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
385e76fa9ecSHeejin Ahn   for (const auto &MI : MBB) {
386e76fa9ecSHeejin Ahn     // LOOP marker should be after any existing loop that ends here. Otherwise
387e76fa9ecSHeejin Ahn     // we assume the instruction belongs to the loop.
388e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
389e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
390e76fa9ecSHeejin Ahn #ifndef NDEBUG
391e76fa9ecSHeejin Ahn     else
392e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
393e76fa9ecSHeejin Ahn #endif
394e76fa9ecSHeejin Ahn   }
395e76fa9ecSHeejin Ahn 
396e76fa9ecSHeejin Ahn   // Mark the beginning of the loop.
39718c56a07SHeejin Ahn   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
39810b31358SDerek Schuff   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
3992726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
4002cb27072SThomas Lively                             .addImm(int64_t(WebAssembly::BlockType::Void));
4011d68e80fSDan Gohman 
402e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_LOOP.
403e76fa9ecSHeejin Ahn   BeforeSet.clear();
404e76fa9ecSHeejin Ahn   AfterSet.clear();
405e76fa9ecSHeejin Ahn #ifndef NDEBUG
406e76fa9ecSHeejin Ahn   for (const auto &MI : MBB)
407e76fa9ecSHeejin Ahn     // Existing END_LOOP markers belong to parent loops of this loop
408e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
409e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
410e76fa9ecSHeejin Ahn #endif
411e76fa9ecSHeejin Ahn 
412e76fa9ecSHeejin Ahn   // Mark the end of the loop (using arbitrary debug location that branched to
413e76fa9ecSHeejin Ahn   // the loop end as its location).
41418c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
41567f74aceSHeejin Ahn   DebugLoc EndDL = AfterLoop->pred_empty()
41667f74aceSHeejin Ahn                        ? DebugLoc()
41767f74aceSHeejin Ahn                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
418e76fa9ecSHeejin Ahn   MachineInstr *End =
419e76fa9ecSHeejin Ahn       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
420e76fa9ecSHeejin Ahn   registerScope(Begin, End);
4218fe7e86bSDan Gohman 
4228fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4238fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
424442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
4258fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
4268fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
427e3e4a5ffSDan Gohman }
428950a13cfSDan Gohman 
429e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
43044a5a4b1SHeejin Ahn   assert(MBB.isEHPad());
431e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
432e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
433e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
434276f9e8cSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
435e76fa9ecSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
436276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
437e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
438e76fa9ecSHeejin Ahn 
439e76fa9ecSHeejin Ahn   // Compute the nearest common dominator of all unwind predecessors
440e76fa9ecSHeejin Ahn   MachineBasicBlock *Header = nullptr;
441e76fa9ecSHeejin Ahn   int MBBNumber = MBB.getNumber();
442e76fa9ecSHeejin Ahn   for (auto *Pred : MBB.predecessors()) {
443e76fa9ecSHeejin Ahn     if (Pred->getNumber() < MBBNumber) {
444e76fa9ecSHeejin Ahn       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
44518c56a07SHeejin Ahn       assert(!explicitlyBranchesTo(Pred, &MBB) &&
446e76fa9ecSHeejin Ahn              "Explicit branch to an EH pad!");
447e76fa9ecSHeejin Ahn     }
448e76fa9ecSHeejin Ahn   }
449e76fa9ecSHeejin Ahn   if (!Header)
450e76fa9ecSHeejin Ahn     return;
451e76fa9ecSHeejin Ahn 
452e76fa9ecSHeejin Ahn   // If this try is at the bottom of the function, insert a dummy block at the
453e76fa9ecSHeejin Ahn   // end.
454e76fa9ecSHeejin Ahn   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
455e76fa9ecSHeejin Ahn   assert(WE);
456276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(WE);
457e76fa9ecSHeejin Ahn 
4585c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
459e76fa9ecSHeejin Ahn   if (Iter == MF.end()) {
460c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
4615c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
462e76fa9ecSHeejin Ahn   }
46320cf0749SHeejin Ahn   MachineBasicBlock *Cont = &*Iter;
464e76fa9ecSHeejin Ahn 
46520cf0749SHeejin Ahn   assert(Cont != &MF.front());
4665c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
467e76fa9ecSHeejin Ahn 
468e76fa9ecSHeejin Ahn   // If the nearest common dominator is inside a more deeply nested context,
469e76fa9ecSHeejin Ahn   // walk out to the nearest scope which isn't more deeply nested.
470e76fa9ecSHeejin Ahn   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
471e76fa9ecSHeejin Ahn     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
472e76fa9ecSHeejin Ahn       if (ScopeTop->getNumber() > Header->getNumber()) {
473e76fa9ecSHeejin Ahn         // Skip over an intervening scope.
4745c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
475e76fa9ecSHeejin Ahn       } else {
476e76fa9ecSHeejin Ahn         // We found a scope level at an appropriate depth.
477e76fa9ecSHeejin Ahn         Header = ScopeTop;
478e76fa9ecSHeejin Ahn         break;
479e76fa9ecSHeejin Ahn       }
480e76fa9ecSHeejin Ahn     }
481e76fa9ecSHeejin Ahn   }
482e76fa9ecSHeejin Ahn 
483e76fa9ecSHeejin Ahn   // Decide where in Header to put the TRY.
484e76fa9ecSHeejin Ahn 
48544a5a4b1SHeejin Ahn   // Instructions that should go before the TRY.
486e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
48744a5a4b1SHeejin Ahn   // Instructions that should go after the TRY.
488e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
489e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
49044a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
49144a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the TRY, because the loop is nested
49244a5a4b1SHeejin Ahn     // in this TRY. Otherwise it should be before the TRY.
493e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
49444a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
49544a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
496e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
497e76fa9ecSHeejin Ahn #ifndef NDEBUG
498e76fa9ecSHeejin Ahn       else
499e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
500e76fa9ecSHeejin Ahn #endif
501e76fa9ecSHeejin Ahn     }
502e76fa9ecSHeejin Ahn 
50344a5a4b1SHeejin Ahn     // All previously inserted BLOCK/TRY markers should be after the TRY because
50444a5a4b1SHeejin Ahn     // they are all nested trys.
50544a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
50644a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
507e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
508e76fa9ecSHeejin Ahn 
509e76fa9ecSHeejin Ahn #ifndef NDEBUG
51044a5a4b1SHeejin Ahn     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
51144a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
51244a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
513e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
514e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
515e76fa9ecSHeejin Ahn #endif
516e76fa9ecSHeejin Ahn 
517e76fa9ecSHeejin Ahn     // Terminators should go after the TRY.
518e76fa9ecSHeejin Ahn     if (MI.isTerminator())
519e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
520e76fa9ecSHeejin Ahn   }
521e76fa9ecSHeejin Ahn 
5226a37c5d6SHeejin Ahn   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
5236a37c5d6SHeejin Ahn   // contain the call within it. So the call should go after the TRY. The
5246a37c5d6SHeejin Ahn   // exception is when the header's terminator is a rethrow instruction, in
5256a37c5d6SHeejin Ahn   // which case that instruction, not a call instruction before it, is gonna
5266a37c5d6SHeejin Ahn   // throw.
5276a37c5d6SHeejin Ahn   MachineInstr *ThrowingCall = nullptr;
5286a37c5d6SHeejin Ahn   if (MBB.isPredecessor(Header)) {
5296a37c5d6SHeejin Ahn     auto TermPos = Header->getFirstTerminator();
5306a37c5d6SHeejin Ahn     if (TermPos == Header->end() ||
5316a37c5d6SHeejin Ahn         TermPos->getOpcode() != WebAssembly::RETHROW) {
5326a37c5d6SHeejin Ahn       for (auto &MI : reverse(*Header)) {
5336a37c5d6SHeejin Ahn         if (MI.isCall()) {
5346a37c5d6SHeejin Ahn           AfterSet.insert(&MI);
5356a37c5d6SHeejin Ahn           ThrowingCall = &MI;
5366a37c5d6SHeejin Ahn           // Possibly throwing calls are usually wrapped by EH_LABEL
5376a37c5d6SHeejin Ahn           // instructions. We don't want to split them and the call.
5386a37c5d6SHeejin Ahn           if (MI.getIterator() != Header->begin() &&
5396a37c5d6SHeejin Ahn               std::prev(MI.getIterator())->isEHLabel()) {
5406a37c5d6SHeejin Ahn             AfterSet.insert(&*std::prev(MI.getIterator()));
5416a37c5d6SHeejin Ahn             ThrowingCall = &*std::prev(MI.getIterator());
5426a37c5d6SHeejin Ahn           }
5436a37c5d6SHeejin Ahn           break;
5446a37c5d6SHeejin Ahn         }
5456a37c5d6SHeejin Ahn       }
5466a37c5d6SHeejin Ahn     }
5476a37c5d6SHeejin Ahn   }
5486a37c5d6SHeejin Ahn 
549e76fa9ecSHeejin Ahn   // Local expression tree should go after the TRY.
5506a37c5d6SHeejin Ahn   // For BLOCK placement, we start the search from the previous instruction of a
5516a37c5d6SHeejin Ahn   // BB's terminator, but in TRY's case, we should start from the previous
5526a37c5d6SHeejin Ahn   // instruction of a call that can throw, or a EH_LABEL that precedes the call,
5536a37c5d6SHeejin Ahn   // because the return values of the call's previous instructions can be
5546a37c5d6SHeejin Ahn   // stackified and consumed by the throwing call.
5556a37c5d6SHeejin Ahn   auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
5566a37c5d6SHeejin Ahn                                     : Header->getFirstTerminator();
5576a37c5d6SHeejin Ahn   for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
558409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
559409b4391SYury Delendik       continue;
560e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
561e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
562e76fa9ecSHeejin Ahn     else
563e76fa9ecSHeejin Ahn       break;
564e76fa9ecSHeejin Ahn   }
565e76fa9ecSHeejin Ahn 
566e76fa9ecSHeejin Ahn   // Add the TRY.
56718c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
568e76fa9ecSHeejin Ahn   MachineInstr *Begin =
569e76fa9ecSHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
570e76fa9ecSHeejin Ahn               TII.get(WebAssembly::TRY))
5712cb27072SThomas Lively           .addImm(int64_t(WebAssembly::BlockType::Void));
572e76fa9ecSHeejin Ahn 
573e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_TRY.
574e76fa9ecSHeejin Ahn   BeforeSet.clear();
575e76fa9ecSHeejin Ahn   AfterSet.clear();
57620cf0749SHeejin Ahn   for (const auto &MI : *Cont) {
577e76fa9ecSHeejin Ahn #ifndef NDEBUG
57844a5a4b1SHeejin Ahn     // END_TRY should precede existing LOOP and BLOCK markers.
57944a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
58044a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::BLOCK)
581e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
582e76fa9ecSHeejin Ahn 
583e76fa9ecSHeejin Ahn     // All END_TRY markers placed earlier belong to exceptions that contains
584e76fa9ecSHeejin Ahn     // this one.
585e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_TRY)
586e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
587e76fa9ecSHeejin Ahn #endif
588e76fa9ecSHeejin Ahn 
589e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and its header is after
590e76fa9ecSHeejin Ahn     // where TRY marker is, this loop is contained within the 'catch' part, so
591e76fa9ecSHeejin Ahn     // the END_TRY marker should go after that. Otherwise, the whole try-catch
592e76fa9ecSHeejin Ahn     // is contained within this loop, so the END_TRY should go before that.
593e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP) {
594222718fdSHeejin Ahn       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
595222718fdSHeejin Ahn       // are in the same BB, LOOP is always before TRY.
596222718fdSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
597e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
598e76fa9ecSHeejin Ahn #ifndef NDEBUG
599e76fa9ecSHeejin Ahn       else
600e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
601e76fa9ecSHeejin Ahn #endif
602e76fa9ecSHeejin Ahn     }
60344a5a4b1SHeejin Ahn 
60444a5a4b1SHeejin Ahn     // It is not possible for an END_BLOCK to be already in this block.
605e76fa9ecSHeejin Ahn   }
606e76fa9ecSHeejin Ahn 
607e76fa9ecSHeejin Ahn   // Mark the end of the TRY.
60820cf0749SHeejin Ahn   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
609e76fa9ecSHeejin Ahn   MachineInstr *End =
61020cf0749SHeejin Ahn       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
611e76fa9ecSHeejin Ahn               TII.get(WebAssembly::END_TRY));
612e76fa9ecSHeejin Ahn   registerTryScope(Begin, End, &MBB);
613e76fa9ecSHeejin Ahn 
61482da1ffcSHeejin Ahn   // Track the farthest-spanning scope that ends at this point. We create two
61582da1ffcSHeejin Ahn   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
61682da1ffcSHeejin Ahn   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
61782da1ffcSHeejin Ahn   // markers should not span across 'catch'. For example, this should not
61882da1ffcSHeejin Ahn   // happen:
61982da1ffcSHeejin Ahn   //
62082da1ffcSHeejin Ahn   // try
62182da1ffcSHeejin Ahn   //   block     --|  (X)
62282da1ffcSHeejin Ahn   // catch         |
62382da1ffcSHeejin Ahn   //   end_block --|
62482da1ffcSHeejin Ahn   // end_try
62582da1ffcSHeejin Ahn   for (int Number : {Cont->getNumber(), MBB.getNumber()}) {
626e76fa9ecSHeejin Ahn     if (!ScopeTops[Number] ||
627e76fa9ecSHeejin Ahn         ScopeTops[Number]->getNumber() > Header->getNumber())
628e76fa9ecSHeejin Ahn       ScopeTops[Number] = Header;
629e76fa9ecSHeejin Ahn   }
63082da1ffcSHeejin Ahn }
631e76fa9ecSHeejin Ahn 
632cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
633cf699b45SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
634cf699b45SHeejin Ahn 
635cf699b45SHeejin Ahn   // When there is an unconditional branch right before a catch instruction and
636cf699b45SHeejin Ahn   // it branches to the end of end_try marker, we don't need the branch, because
637cf699b45SHeejin Ahn   // it there is no exception, the control flow transfers to that point anyway.
638cf699b45SHeejin Ahn   // bb0:
639cf699b45SHeejin Ahn   //   try
640cf699b45SHeejin Ahn   //     ...
641cf699b45SHeejin Ahn   //     br bb2      <- Not necessary
642cf699b45SHeejin Ahn   // bb1:
643cf699b45SHeejin Ahn   //   catch
644cf699b45SHeejin Ahn   //     ...
645cf699b45SHeejin Ahn   // bb2:
646cf699b45SHeejin Ahn   //   end
647cf699b45SHeejin Ahn   for (auto &MBB : MF) {
648cf699b45SHeejin Ahn     if (!MBB.isEHPad())
649cf699b45SHeejin Ahn       continue;
650cf699b45SHeejin Ahn 
651cf699b45SHeejin Ahn     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
652cf699b45SHeejin Ahn     SmallVector<MachineOperand, 4> Cond;
6535c644c9bSHeejin Ahn     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
654cf699b45SHeejin Ahn     MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent();
655cf699b45SHeejin Ahn     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
6563fe6ea46SHeejin Ahn     // This condition means either
6573fe6ea46SHeejin Ahn     // 1. This BB ends with a single unconditional branch whose destinaion is
6583fe6ea46SHeejin Ahn     //    Cont.
6593fe6ea46SHeejin Ahn     // 2. This BB ends with a conditional branch followed by an unconditional
6603fe6ea46SHeejin Ahn     //    branch, and the unconditional branch's destination is Cont.
6613fe6ea46SHeejin Ahn     // In both cases, we want to remove the last (= unconditional) branch.
662cf699b45SHeejin Ahn     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
6633fe6ea46SHeejin Ahn                        (!Cond.empty() && FBB && FBB == Cont))) {
6643fe6ea46SHeejin Ahn       bool ErasedUncondBr = false;
665a5099ad9SHeejin Ahn       (void)ErasedUncondBr;
6663fe6ea46SHeejin Ahn       for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
6673fe6ea46SHeejin Ahn            I != E; --I) {
6683fe6ea46SHeejin Ahn         auto PrevI = std::prev(I);
6693fe6ea46SHeejin Ahn         if (PrevI->isTerminator()) {
6703fe6ea46SHeejin Ahn           assert(PrevI->getOpcode() == WebAssembly::BR);
6713fe6ea46SHeejin Ahn           PrevI->eraseFromParent();
6723fe6ea46SHeejin Ahn           ErasedUncondBr = true;
6733fe6ea46SHeejin Ahn           break;
6743fe6ea46SHeejin Ahn         }
6753fe6ea46SHeejin Ahn       }
6763fe6ea46SHeejin Ahn       assert(ErasedUncondBr && "Unconditional branch not erased!");
6773fe6ea46SHeejin Ahn     }
678cf699b45SHeejin Ahn   }
679cf699b45SHeejin Ahn 
680cf699b45SHeejin Ahn   // When there are block / end_block markers that overlap with try / end_try
681cf699b45SHeejin Ahn   // markers, and the block and try markers' return types are the same, the
682cf699b45SHeejin Ahn   // block /end_block markers are not necessary, because try / end_try markers
683cf699b45SHeejin Ahn   // also can serve as boundaries for branches.
684cf699b45SHeejin Ahn   // block         <- Not necessary
685cf699b45SHeejin Ahn   //   try
686cf699b45SHeejin Ahn   //     ...
687cf699b45SHeejin Ahn   //   catch
688cf699b45SHeejin Ahn   //     ...
689cf699b45SHeejin Ahn   //   end
690cf699b45SHeejin Ahn   // end           <- Not necessary
691cf699b45SHeejin Ahn   SmallVector<MachineInstr *, 32> ToDelete;
692cf699b45SHeejin Ahn   for (auto &MBB : MF) {
693cf699b45SHeejin Ahn     for (auto &MI : MBB) {
694cf699b45SHeejin Ahn       if (MI.getOpcode() != WebAssembly::TRY)
695cf699b45SHeejin Ahn         continue;
696cf699b45SHeejin Ahn 
697cf699b45SHeejin Ahn       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
698cf699b45SHeejin Ahn       MachineBasicBlock *TryBB = Try->getParent();
699cf699b45SHeejin Ahn       MachineBasicBlock *Cont = EndTry->getParent();
700cf699b45SHeejin Ahn       int64_t RetType = Try->getOperand(0).getImm();
7015c644c9bSHeejin Ahn       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
702cf699b45SHeejin Ahn            B != TryBB->begin() && E != Cont->end() &&
703cf699b45SHeejin Ahn            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
704cf699b45SHeejin Ahn            E->getOpcode() == WebAssembly::END_BLOCK &&
705cf699b45SHeejin Ahn            std::prev(B)->getOperand(0).getImm() == RetType;
706cf699b45SHeejin Ahn            --B, ++E) {
707cf699b45SHeejin Ahn         ToDelete.push_back(&*std::prev(B));
708cf699b45SHeejin Ahn         ToDelete.push_back(&*E);
709cf699b45SHeejin Ahn       }
710cf699b45SHeejin Ahn     }
711cf699b45SHeejin Ahn   }
712cf699b45SHeejin Ahn   for (auto *MI : ToDelete) {
713cf699b45SHeejin Ahn     if (MI->getOpcode() == WebAssembly::BLOCK)
714cf699b45SHeejin Ahn       unregisterScope(MI);
715cf699b45SHeejin Ahn     MI->eraseFromParent();
716cf699b45SHeejin Ahn   }
717cf699b45SHeejin Ahn }
718cf699b45SHeejin Ahn 
71983c26eaeSHeejin Ahn // Get the appropriate copy opcode for the given register class.
72083c26eaeSHeejin Ahn static unsigned getCopyOpcode(const TargetRegisterClass *RC) {
72183c26eaeSHeejin Ahn   if (RC == &WebAssembly::I32RegClass)
72283c26eaeSHeejin Ahn     return WebAssembly::COPY_I32;
72383c26eaeSHeejin Ahn   if (RC == &WebAssembly::I64RegClass)
72483c26eaeSHeejin Ahn     return WebAssembly::COPY_I64;
72583c26eaeSHeejin Ahn   if (RC == &WebAssembly::F32RegClass)
72683c26eaeSHeejin Ahn     return WebAssembly::COPY_F32;
72783c26eaeSHeejin Ahn   if (RC == &WebAssembly::F64RegClass)
72883c26eaeSHeejin Ahn     return WebAssembly::COPY_F64;
72983c26eaeSHeejin Ahn   if (RC == &WebAssembly::V128RegClass)
73083c26eaeSHeejin Ahn     return WebAssembly::COPY_V128;
73160653e24SHeejin Ahn   if (RC == &WebAssembly::FUNCREFRegClass)
73260653e24SHeejin Ahn     return WebAssembly::COPY_FUNCREF;
73360653e24SHeejin Ahn   if (RC == &WebAssembly::EXTERNREFRegClass)
73460653e24SHeejin Ahn     return WebAssembly::COPY_EXTERNREF;
73583c26eaeSHeejin Ahn   llvm_unreachable("Unexpected register class");
73683c26eaeSHeejin Ahn }
73783c26eaeSHeejin Ahn 
73861d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that
73961d5c76aSHeejin Ahn // have their uses in Split.
7409e4eadebSHeejin Ahn // FIXME This function will be used when fixing unwind mismatches, but the old
7419e4eadebSHeejin Ahn // version of that function was removed for the moment and the new version has
7429e4eadebSHeejin Ahn // not yet been added. So 'LLVM_ATTRIBUTE_UNUSED' is added to suppress the
7439e4eadebSHeejin Ahn // warning. Remove the attribute after the new functionality is added.
7449e4eadebSHeejin Ahn LLVM_ATTRIBUTE_UNUSED static void
7459e4eadebSHeejin Ahn unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, MachineBasicBlock &Split,
74661d5c76aSHeejin Ahn                              WebAssemblyFunctionInfo &MFI,
74783c26eaeSHeejin Ahn                              MachineRegisterInfo &MRI,
74883c26eaeSHeejin Ahn                              const WebAssemblyInstrInfo &TII) {
74961d5c76aSHeejin Ahn   for (auto &MI : Split) {
75061d5c76aSHeejin Ahn     for (auto &MO : MI.explicit_uses()) {
75161d5c76aSHeejin Ahn       if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg()))
75261d5c76aSHeejin Ahn         continue;
75361d5c76aSHeejin Ahn       if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
75461d5c76aSHeejin Ahn         if (Def->getParent() == &MBB)
75561d5c76aSHeejin Ahn           MFI.unstackifyVReg(MO.getReg());
75661d5c76aSHeejin Ahn     }
75761d5c76aSHeejin Ahn   }
75883c26eaeSHeejin Ahn 
75983c26eaeSHeejin Ahn   // In RegStackify, when a register definition is used multiple times,
76083c26eaeSHeejin Ahn   //    Reg = INST ...
76183c26eaeSHeejin Ahn   //    INST ..., Reg, ...
76283c26eaeSHeejin Ahn   //    INST ..., Reg, ...
76383c26eaeSHeejin Ahn   //    INST ..., Reg, ...
76483c26eaeSHeejin Ahn   //
76583c26eaeSHeejin Ahn   // we introduce a TEE, which has the following form:
76683c26eaeSHeejin Ahn   //    DefReg = INST ...
76783c26eaeSHeejin Ahn   //    TeeReg, Reg = TEE_... DefReg
76883c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
76983c26eaeSHeejin Ahn   //    INST ..., Reg, ...
77083c26eaeSHeejin Ahn   //    INST ..., Reg, ...
77183c26eaeSHeejin Ahn   // with DefReg and TeeReg stackified but Reg not stackified.
77283c26eaeSHeejin Ahn   //
77383c26eaeSHeejin Ahn   // But the invariant that TeeReg should be stackified can be violated while we
77483c26eaeSHeejin Ahn   // unstackify registers in the split BB above. In this case, we convert TEEs
77583c26eaeSHeejin Ahn   // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
77683c26eaeSHeejin Ahn   //    DefReg = INST ...
77783c26eaeSHeejin Ahn   //    TeeReg = COPY DefReg
77883c26eaeSHeejin Ahn   //    Reg = COPY DefReg
77983c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
78083c26eaeSHeejin Ahn   //    INST ..., Reg, ...
78183c26eaeSHeejin Ahn   //    INST ..., Reg, ...
78283c26eaeSHeejin Ahn   for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
78383c26eaeSHeejin Ahn     MachineInstr &MI = *I++;
78483c26eaeSHeejin Ahn     if (!WebAssembly::isTee(MI.getOpcode()))
78583c26eaeSHeejin Ahn       continue;
78683c26eaeSHeejin Ahn     Register TeeReg = MI.getOperand(0).getReg();
78783c26eaeSHeejin Ahn     Register Reg = MI.getOperand(1).getReg();
78883c26eaeSHeejin Ahn     Register DefReg = MI.getOperand(2).getReg();
78983c26eaeSHeejin Ahn     if (!MFI.isVRegStackified(TeeReg)) {
79083c26eaeSHeejin Ahn       // Now we are not using TEE anymore, so unstackify DefReg too
79183c26eaeSHeejin Ahn       MFI.unstackifyVReg(DefReg);
79283c26eaeSHeejin Ahn       unsigned CopyOpc = getCopyOpcode(MRI.getRegClass(DefReg));
79383c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
79483c26eaeSHeejin Ahn           .addReg(DefReg);
79583c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
79683c26eaeSHeejin Ahn       MI.eraseFromParent();
79783c26eaeSHeejin Ahn     }
79883c26eaeSHeejin Ahn   }
79961d5c76aSHeejin Ahn }
80061d5c76aSHeejin Ahn 
801c4ac74fbSHeejin Ahn bool WebAssemblyCFGStackify::fixUnwindMismatches(MachineFunction &MF) {
8029e4eadebSHeejin Ahn   // TODO Implement this
803c4ac74fbSHeejin Ahn   return false;
804c4ac74fbSHeejin Ahn }
805c4ac74fbSHeejin Ahn 
8061d68e80fSDan Gohman static unsigned
80718c56a07SHeejin Ahn getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
8081d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
8091d68e80fSDan Gohman   unsigned Depth = 0;
8101d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
8111d68e80fSDan Gohman     if (X == MBB)
8121d68e80fSDan Gohman       break;
8131d68e80fSDan Gohman     ++Depth;
8141d68e80fSDan Gohman   }
8151d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
8161d68e80fSDan Gohman   return Depth;
8171d68e80fSDan Gohman }
8181d68e80fSDan Gohman 
8192726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
8202726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
8212726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
8222726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
8232726b88cSDan Gohman /// that end at the function end need to have a return type signature that
8242726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
8252726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
826e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
827e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
8282726b88cSDan Gohman 
8292726b88cSDan Gohman   if (MFI.getResults().empty())
8302726b88cSDan Gohman     return;
8312726b88cSDan Gohman 
8322cb27072SThomas Lively   // MCInstLower will add the proper types to multivalue signatures based on the
8332cb27072SThomas Lively   // function return type
8342cb27072SThomas Lively   WebAssembly::BlockType RetType =
8352cb27072SThomas Lively       MFI.getResults().size() > 1
8362cb27072SThomas Lively           ? WebAssembly::BlockType::Multivalue
8372cb27072SThomas Lively           : WebAssembly::BlockType(
8382cb27072SThomas Lively                 WebAssembly::toValType(MFI.getResults().front()));
8392726b88cSDan Gohman 
840d25c17f3SHeejin Ahn   SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist;
841d25c17f3SHeejin Ahn   Worklist.push_back(MF.rbegin()->rbegin());
842d25c17f3SHeejin Ahn 
843d25c17f3SHeejin Ahn   auto Process = [&](MachineBasicBlock::reverse_iterator It) {
844d25c17f3SHeejin Ahn     auto *MBB = It->getParent();
845d25c17f3SHeejin Ahn     while (It != MBB->rend()) {
846d25c17f3SHeejin Ahn       MachineInstr &MI = *It++;
847801bf7ebSShiva Chen       if (MI.isPosition() || MI.isDebugInstr())
8482726b88cSDan Gohman         continue;
8492cb27072SThomas Lively       switch (MI.getOpcode()) {
850d25c17f3SHeejin Ahn       case WebAssembly::END_TRY: {
851d25c17f3SHeejin Ahn         // If a 'try''s return type is fixed, both its try body and catch body
852d25c17f3SHeejin Ahn         // should satisfy the return type, so we need to search 'end'
853d25c17f3SHeejin Ahn         // instructions before its corresponding 'catch' too.
854d25c17f3SHeejin Ahn         auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
855d25c17f3SHeejin Ahn         assert(EHPad);
856*9f8b2576SHeejin Ahn         auto NextIt =
857*9f8b2576SHeejin Ahn             std::next(WebAssembly::findCatch(EHPad)->getReverseIterator());
858*9f8b2576SHeejin Ahn         if (NextIt != EHPad->rend())
859*9f8b2576SHeejin Ahn           Worklist.push_back(NextIt);
860d25c17f3SHeejin Ahn         LLVM_FALLTHROUGH;
861d25c17f3SHeejin Ahn       }
8622cb27072SThomas Lively       case WebAssembly::END_BLOCK:
8632cb27072SThomas Lively       case WebAssembly::END_LOOP:
86418c56a07SHeejin Ahn         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
8652726b88cSDan Gohman         continue;
8662cb27072SThomas Lively       default:
867d25c17f3SHeejin Ahn         // Something other than an `end`. We're done for this BB.
8682726b88cSDan Gohman         return;
8692726b88cSDan Gohman       }
8702726b88cSDan Gohman     }
871d25c17f3SHeejin Ahn     // We've reached the beginning of a BB. Continue the search in the previous
872d25c17f3SHeejin Ahn     // BB.
873d25c17f3SHeejin Ahn     Worklist.push_back(MBB->getPrevNode()->rbegin());
874d25c17f3SHeejin Ahn   };
875d25c17f3SHeejin Ahn 
876d25c17f3SHeejin Ahn   while (!Worklist.empty())
877d25c17f3SHeejin Ahn     Process(Worklist.pop_back_val());
8782cb27072SThomas Lively }
8792726b88cSDan Gohman 
880d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
881d934cb88SDan Gohman // were a block.
88218c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF,
883d934cb88SDan Gohman                                 const WebAssemblyInstrInfo &TII) {
88410b31358SDerek Schuff   BuildMI(MF.back(), MF.back().end(),
88510b31358SDerek Schuff           MF.back().findPrevDebugLoc(MF.back().end()),
886d934cb88SDan Gohman           TII.get(WebAssembly::END_FUNCTION));
887d934cb88SDan Gohman }
888d934cb88SDan Gohman 
889e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places.
890e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
891e76fa9ecSHeejin Ahn   // We allocate one more than the number of blocks in the function to
892e76fa9ecSHeejin Ahn   // accommodate for the possible fake block we may insert at the end.
893e76fa9ecSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs() + 1);
8948fe7e86bSDan Gohman   // Place the LOOP for MBB if MBB is the header of a loop.
895e76fa9ecSHeejin Ahn   for (auto &MBB : MF)
896e76fa9ecSHeejin Ahn     placeLoopMarker(MBB);
89744a5a4b1SHeejin Ahn 
898d6f48786SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
89944a5a4b1SHeejin Ahn   for (auto &MBB : MF) {
90044a5a4b1SHeejin Ahn     if (MBB.isEHPad()) {
90144a5a4b1SHeejin Ahn       // Place the TRY for MBB if MBB is the EH pad of an exception.
902e76fa9ecSHeejin Ahn       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
903e76fa9ecSHeejin Ahn           MF.getFunction().hasPersonalityFn())
904e76fa9ecSHeejin Ahn         placeTryMarker(MBB);
90544a5a4b1SHeejin Ahn     } else {
90632807932SDan Gohman       // Place the BLOCK for MBB if MBB is branched to from above.
907e76fa9ecSHeejin Ahn       placeBlockMarker(MBB);
908950a13cfSDan Gohman     }
90944a5a4b1SHeejin Ahn   }
910c4ac74fbSHeejin Ahn   // Fix mismatches in unwind destinations induced by linearizing the code.
911daeead4bSHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
912daeead4bSHeejin Ahn       MF.getFunction().hasPersonalityFn())
913c4ac74fbSHeejin Ahn     fixUnwindMismatches(MF);
91444a5a4b1SHeejin Ahn }
915950a13cfSDan Gohman 
916e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
9171d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
9181d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
9191d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
920e76fa9ecSHeejin Ahn     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) {
921e76fa9ecSHeejin Ahn       MachineInstr &MI = *I;
9221d68e80fSDan Gohman       switch (MI.getOpcode()) {
9231d68e80fSDan Gohman       case WebAssembly::BLOCK:
924e76fa9ecSHeejin Ahn       case WebAssembly::TRY:
925e76fa9ecSHeejin Ahn         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <=
926e76fa9ecSHeejin Ahn                    MBB.getNumber() &&
927e76fa9ecSHeejin Ahn                "Block/try marker should be balanced");
928e76fa9ecSHeejin Ahn         Stack.pop_back();
929e76fa9ecSHeejin Ahn         break;
930e76fa9ecSHeejin Ahn 
9311d68e80fSDan Gohman       case WebAssembly::LOOP:
9321d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
9331d68e80fSDan Gohman         Stack.pop_back();
9341d68e80fSDan Gohman         break;
935e76fa9ecSHeejin Ahn 
9361d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
937e76fa9ecSHeejin Ahn       case WebAssembly::END_TRY:
9381d68e80fSDan Gohman         Stack.push_back(&MBB);
9391d68e80fSDan Gohman         break;
940e76fa9ecSHeejin Ahn 
9411d68e80fSDan Gohman       case WebAssembly::END_LOOP:
942e76fa9ecSHeejin Ahn         Stack.push_back(EndToBegin[&MI]->getParent());
9431d68e80fSDan Gohman         break;
944e76fa9ecSHeejin Ahn 
9451d68e80fSDan Gohman       default:
9461d68e80fSDan Gohman         if (MI.isTerminator()) {
9471d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
9481d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
9491d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
9501d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
9511d68e80fSDan Gohman           for (auto MO : Ops) {
9521d68e80fSDan Gohman             if (MO.isMBB())
95318c56a07SHeejin Ahn               MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB()));
9541d68e80fSDan Gohman             MI.addOperand(MF, MO);
95532807932SDan Gohman           }
9561d68e80fSDan Gohman         }
9571d68e80fSDan Gohman         break;
9581d68e80fSDan Gohman       }
9591d68e80fSDan Gohman     }
9601d68e80fSDan Gohman   }
9611d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
962e76fa9ecSHeejin Ahn }
9632726b88cSDan Gohman 
964e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() {
965e76fa9ecSHeejin Ahn   ScopeTops.clear();
966e76fa9ecSHeejin Ahn   BeginToEnd.clear();
967e76fa9ecSHeejin Ahn   EndToBegin.clear();
968e76fa9ecSHeejin Ahn   TryToEHPad.clear();
969e76fa9ecSHeejin Ahn   EHPadToTry.clear();
970c4ac74fbSHeejin Ahn   AppendixBB = nullptr;
9711d68e80fSDan Gohman }
97232807932SDan Gohman 
973950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
974d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
975950a13cfSDan Gohman                        "********** Function: "
976950a13cfSDan Gohman                     << MF.getName() << '\n');
977cf699b45SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
978950a13cfSDan Gohman 
979e76fa9ecSHeejin Ahn   releaseMemory();
980e76fa9ecSHeejin Ahn 
981e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
9829c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
983950a13cfSDan Gohman 
984e76fa9ecSHeejin Ahn   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
985e76fa9ecSHeejin Ahn   placeMarkers(MF);
986e76fa9ecSHeejin Ahn 
987c4ac74fbSHeejin Ahn   // Remove unnecessary instructions possibly introduced by try/end_trys.
988cf699b45SHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
989cf699b45SHeejin Ahn       MF.getFunction().hasPersonalityFn())
990cf699b45SHeejin Ahn     removeUnnecessaryInstrs(MF);
991cf699b45SHeejin Ahn 
992e76fa9ecSHeejin Ahn   // Convert MBB operands in terminators to relative depth immediates.
993e76fa9ecSHeejin Ahn   rewriteDepthImmediates(MF);
994e76fa9ecSHeejin Ahn 
995e76fa9ecSHeejin Ahn   // Fix up block/loop/try signatures at the end of the function to conform to
996e76fa9ecSHeejin Ahn   // WebAssembly's rules.
997e76fa9ecSHeejin Ahn   fixEndsAtEndOfFunction(MF);
998e76fa9ecSHeejin Ahn 
999e76fa9ecSHeejin Ahn   // Add an end instruction at the end of the function body.
1000e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1001e76fa9ecSHeejin Ahn   if (!MF.getSubtarget<WebAssemblySubtarget>()
1002e76fa9ecSHeejin Ahn            .getTargetTriple()
1003e76fa9ecSHeejin Ahn            .isOSBinFormatELF())
100418c56a07SHeejin Ahn     appendEndToFunction(MF, TII);
100532807932SDan Gohman 
10061aaa481fSHeejin Ahn   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1007950a13cfSDan Gohman   return true;
1008950a13cfSDan Gohman }
1009