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 
181d25c17f3SHeejin Ahn // Find a catch instruction and its destination register within an EH pad.
182d25c17f3SHeejin Ahn static MachineInstr *findCatch(MachineBasicBlock *EHPad, Register &ExnReg) {
183d25c17f3SHeejin Ahn   assert(EHPad->isEHPad());
184d25c17f3SHeejin Ahn   MachineInstr *Catch = nullptr;
185d25c17f3SHeejin Ahn   for (auto &MI : *EHPad) {
1869e4eadebSHeejin Ahn     if (WebAssembly::isCatch(MI.getOpcode())) {
187d25c17f3SHeejin Ahn       Catch = &MI;
188d25c17f3SHeejin Ahn       ExnReg = Catch->getOperand(0).getReg();
189d25c17f3SHeejin Ahn       break;
190d25c17f3SHeejin Ahn     }
191d25c17f3SHeejin Ahn   }
192d25c17f3SHeejin Ahn   assert(Catch && "EH pad does not have a catch");
193d25c17f3SHeejin Ahn   assert(ExnReg != 0 && "Invalid register");
194d25c17f3SHeejin Ahn   return Catch;
195d25c17f3SHeejin Ahn }
196d25c17f3SHeejin Ahn 
197d25c17f3SHeejin Ahn static MachineInstr *findCatch(MachineBasicBlock *EHPad) {
198d25c17f3SHeejin Ahn   Register Dummy;
199d25c17f3SHeejin Ahn   return findCatch(EHPad, Dummy);
200d25c17f3SHeejin Ahn }
201d25c17f3SHeejin Ahn 
202e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
203e76fa9ecSHeejin Ahn                                            MachineInstr *End) {
204e76fa9ecSHeejin Ahn   BeginToEnd[Begin] = End;
205e76fa9ecSHeejin Ahn   EndToBegin[End] = Begin;
206e76fa9ecSHeejin Ahn }
207e76fa9ecSHeejin Ahn 
208e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
209e76fa9ecSHeejin Ahn                                               MachineInstr *End,
210e76fa9ecSHeejin Ahn                                               MachineBasicBlock *EHPad) {
211e76fa9ecSHeejin Ahn   registerScope(Begin, End);
212e76fa9ecSHeejin Ahn   TryToEHPad[Begin] = EHPad;
213e76fa9ecSHeejin Ahn   EHPadToTry[EHPad] = Begin;
214e76fa9ecSHeejin Ahn }
215e76fa9ecSHeejin Ahn 
216cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
217cf699b45SHeejin Ahn   assert(BeginToEnd.count(Begin));
218cf699b45SHeejin Ahn   MachineInstr *End = BeginToEnd[Begin];
219cf699b45SHeejin Ahn   assert(EndToBegin.count(End));
220cf699b45SHeejin Ahn   BeginToEnd.erase(Begin);
221cf699b45SHeejin Ahn   EndToBegin.erase(End);
222cf699b45SHeejin Ahn   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
223cf699b45SHeejin Ahn   if (EHPad) {
224cf699b45SHeejin Ahn     assert(EHPadToTry.count(EHPad));
225cf699b45SHeejin Ahn     TryToEHPad.erase(Begin);
226cf699b45SHeejin Ahn     EHPadToTry.erase(EHPad);
227cf699b45SHeejin Ahn   }
228cf699b45SHeejin Ahn }
229cf699b45SHeejin Ahn 
23032807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
231c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and
232c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later.
233e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
23444a5a4b1SHeejin Ahn   assert(!MBB.isEHPad());
235e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
236e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
237e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
238e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
239e76fa9ecSHeejin Ahn 
2408fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
2418fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
2428fe7e86bSDan Gohman   // which reduces overall stack height.
24332807932SDan Gohman   MachineBasicBlock *Header = nullptr;
24432807932SDan Gohman   bool IsBranchedTo = false;
24532807932SDan Gohman   int MBBNumber = MBB.getNumber();
246e76fa9ecSHeejin Ahn   for (MachineBasicBlock *Pred : MBB.predecessors()) {
24732807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
24832807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
249*52e240a0SHeejin Ahn       if (explicitlyBranchesTo(Pred, &MBB))
25032807932SDan Gohman         IsBranchedTo = true;
25132807932SDan Gohman     }
252e76fa9ecSHeejin Ahn   }
25332807932SDan Gohman   if (!Header)
25432807932SDan Gohman     return;
25532807932SDan Gohman   if (!IsBranchedTo)
25632807932SDan Gohman     return;
25732807932SDan Gohman 
2588fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
2595c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
2608fe7e86bSDan Gohman 
2618fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
2628fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
2638fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
2648fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
2658fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
2668fe7e86bSDan Gohman         // Skip over an intervening scope.
2675c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
2688fe7e86bSDan Gohman       } else {
2698fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
2708fe7e86bSDan Gohman         Header = ScopeTop;
2718fe7e86bSDan Gohman         break;
2728fe7e86bSDan Gohman       }
2738fe7e86bSDan Gohman     }
2748fe7e86bSDan Gohman   }
2758fe7e86bSDan Gohman 
2768fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
277e76fa9ecSHeejin Ahn 
278e76fa9ecSHeejin Ahn   // Instructions that should go before the BLOCK.
279e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
280e76fa9ecSHeejin Ahn   // Instructions that should go after the BLOCK.
281e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
282e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
28344a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
28444a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the BLOCK, because the loop is
28544a5a4b1SHeejin Ahn     // nested in this BLOCK. Otherwise it should be before the BLOCK.
28644a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
28744a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
28844a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
289e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
290e76fa9ecSHeejin Ahn #ifndef NDEBUG
291e76fa9ecSHeejin Ahn       else
292e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
293e76fa9ecSHeejin Ahn #endif
294e76fa9ecSHeejin Ahn     }
295e76fa9ecSHeejin Ahn 
296834debffSHeejin Ahn     // If there is a previously placed BLOCK/TRY marker and its corresponding
297834debffSHeejin Ahn     // END marker is before the current BLOCK's END marker, that should be
298834debffSHeejin Ahn     // placed after this BLOCK. Otherwise it should be placed before this BLOCK
299834debffSHeejin Ahn     // marker.
30044a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
301834debffSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY) {
302834debffSHeejin Ahn       if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
303e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
304834debffSHeejin Ahn #ifndef NDEBUG
305834debffSHeejin Ahn       else
306834debffSHeejin Ahn         BeforeSet.insert(&MI);
307834debffSHeejin Ahn #endif
308834debffSHeejin Ahn     }
309e76fa9ecSHeejin Ahn 
310e76fa9ecSHeejin Ahn #ifndef NDEBUG
311e76fa9ecSHeejin Ahn     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
312e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
313e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
314e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
315e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
316e76fa9ecSHeejin Ahn #endif
317e76fa9ecSHeejin Ahn 
318e76fa9ecSHeejin Ahn     // Terminators should go after the BLOCK.
319e76fa9ecSHeejin Ahn     if (MI.isTerminator())
320e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
321e76fa9ecSHeejin Ahn   }
322e76fa9ecSHeejin Ahn 
323e76fa9ecSHeejin Ahn   // Local expression tree should go after the BLOCK.
324e76fa9ecSHeejin Ahn   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
325e76fa9ecSHeejin Ahn        --I) {
326409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
327409b4391SYury Delendik       continue;
328e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
329e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
330e76fa9ecSHeejin Ahn     else
331e76fa9ecSHeejin Ahn       break;
33232807932SDan Gohman   }
33332807932SDan Gohman 
3348fe7e86bSDan Gohman   // Add the BLOCK.
3352cb27072SThomas Lively   WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
33618c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
33792401cc1SHeejin Ahn   MachineInstr *Begin =
33892401cc1SHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
3392726b88cSDan Gohman               TII.get(WebAssembly::BLOCK))
340d6f48786SHeejin Ahn           .addImm(int64_t(ReturnType));
3411d68e80fSDan Gohman 
342e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_BLOCK.
343e76fa9ecSHeejin Ahn   BeforeSet.clear();
344e76fa9ecSHeejin Ahn   AfterSet.clear();
345e76fa9ecSHeejin Ahn   for (auto &MI : MBB) {
346e76fa9ecSHeejin Ahn #ifndef NDEBUG
347e76fa9ecSHeejin Ahn     // END_BLOCK should precede existing LOOP and TRY markers.
348e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
349e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
350e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
351e76fa9ecSHeejin Ahn #endif
352e76fa9ecSHeejin Ahn 
353e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and the header of the
354e76fa9ecSHeejin Ahn     // loop is above this block's header, the END_LOOP should be placed after
355e76fa9ecSHeejin Ahn     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
356e76fa9ecSHeejin Ahn     // should be placed before the BLOCK. The same for END_TRY.
357e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP ||
358e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY) {
359e76fa9ecSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
360e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
361e76fa9ecSHeejin Ahn #ifndef NDEBUG
362e76fa9ecSHeejin Ahn       else
363e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
364e76fa9ecSHeejin Ahn #endif
365e76fa9ecSHeejin Ahn     }
366e76fa9ecSHeejin Ahn   }
367e76fa9ecSHeejin Ahn 
3681d68e80fSDan Gohman   // Mark the end of the block.
36918c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
37010b31358SDerek Schuff   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
3712726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
372e76fa9ecSHeejin Ahn   registerScope(Begin, End);
3738fe7e86bSDan Gohman 
3748fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
3758fe7e86bSDan Gohman   int Number = MBB.getNumber();
3768fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
3778fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
3788fe7e86bSDan Gohman     ScopeTops[Number] = Header;
379950a13cfSDan Gohman }
380950a13cfSDan Gohman 
3818fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
382e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
383e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
384e76fa9ecSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
385276f9e8cSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
386276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
387e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
388e76fa9ecSHeejin Ahn 
3898fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
3908fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
3918fe7e86bSDan Gohman     return;
3928fe7e86bSDan Gohman 
3938fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
3948fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
395276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(Loop);
3965c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
397e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
398c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
3995c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
400e3e4a5ffSDan Gohman   }
4018fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
402f6857223SDan Gohman 
403e76fa9ecSHeejin Ahn   // Decide where in Header to put the LOOP.
404e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
405e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
406e76fa9ecSHeejin Ahn   for (const auto &MI : MBB) {
407e76fa9ecSHeejin Ahn     // LOOP marker should be after any existing loop that ends here. Otherwise
408e76fa9ecSHeejin Ahn     // we assume the instruction belongs to the loop.
409e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
410e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
411e76fa9ecSHeejin Ahn #ifndef NDEBUG
412e76fa9ecSHeejin Ahn     else
413e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
414e76fa9ecSHeejin Ahn #endif
415e76fa9ecSHeejin Ahn   }
416e76fa9ecSHeejin Ahn 
417e76fa9ecSHeejin Ahn   // Mark the beginning of the loop.
41818c56a07SHeejin Ahn   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
41910b31358SDerek Schuff   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
4202726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
4212cb27072SThomas Lively                             .addImm(int64_t(WebAssembly::BlockType::Void));
4221d68e80fSDan Gohman 
423e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_LOOP.
424e76fa9ecSHeejin Ahn   BeforeSet.clear();
425e76fa9ecSHeejin Ahn   AfterSet.clear();
426e76fa9ecSHeejin Ahn #ifndef NDEBUG
427e76fa9ecSHeejin Ahn   for (const auto &MI : MBB)
428e76fa9ecSHeejin Ahn     // Existing END_LOOP markers belong to parent loops of this loop
429e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
430e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
431e76fa9ecSHeejin Ahn #endif
432e76fa9ecSHeejin Ahn 
433e76fa9ecSHeejin Ahn   // Mark the end of the loop (using arbitrary debug location that branched to
434e76fa9ecSHeejin Ahn   // the loop end as its location).
43518c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
43667f74aceSHeejin Ahn   DebugLoc EndDL = AfterLoop->pred_empty()
43767f74aceSHeejin Ahn                        ? DebugLoc()
43867f74aceSHeejin Ahn                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
439e76fa9ecSHeejin Ahn   MachineInstr *End =
440e76fa9ecSHeejin Ahn       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
441e76fa9ecSHeejin Ahn   registerScope(Begin, End);
4428fe7e86bSDan Gohman 
4438fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4448fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
445442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
4468fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
4478fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
448e3e4a5ffSDan Gohman }
449950a13cfSDan Gohman 
450e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
45144a5a4b1SHeejin Ahn   assert(MBB.isEHPad());
452e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
453e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
454e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
455276f9e8cSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
456e76fa9ecSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
457276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
458e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
459e76fa9ecSHeejin Ahn 
460e76fa9ecSHeejin Ahn   // Compute the nearest common dominator of all unwind predecessors
461e76fa9ecSHeejin Ahn   MachineBasicBlock *Header = nullptr;
462e76fa9ecSHeejin Ahn   int MBBNumber = MBB.getNumber();
463e76fa9ecSHeejin Ahn   for (auto *Pred : MBB.predecessors()) {
464e76fa9ecSHeejin Ahn     if (Pred->getNumber() < MBBNumber) {
465e76fa9ecSHeejin Ahn       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
46618c56a07SHeejin Ahn       assert(!explicitlyBranchesTo(Pred, &MBB) &&
467e76fa9ecSHeejin Ahn              "Explicit branch to an EH pad!");
468e76fa9ecSHeejin Ahn     }
469e76fa9ecSHeejin Ahn   }
470e76fa9ecSHeejin Ahn   if (!Header)
471e76fa9ecSHeejin Ahn     return;
472e76fa9ecSHeejin Ahn 
473e76fa9ecSHeejin Ahn   // If this try is at the bottom of the function, insert a dummy block at the
474e76fa9ecSHeejin Ahn   // end.
475e76fa9ecSHeejin Ahn   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
476e76fa9ecSHeejin Ahn   assert(WE);
477276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(WE);
478e76fa9ecSHeejin Ahn 
4795c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
480e76fa9ecSHeejin Ahn   if (Iter == MF.end()) {
481c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
4825c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
483e76fa9ecSHeejin Ahn   }
48420cf0749SHeejin Ahn   MachineBasicBlock *Cont = &*Iter;
485e76fa9ecSHeejin Ahn 
48620cf0749SHeejin Ahn   assert(Cont != &MF.front());
4875c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
488e76fa9ecSHeejin Ahn 
489e76fa9ecSHeejin Ahn   // If the nearest common dominator is inside a more deeply nested context,
490e76fa9ecSHeejin Ahn   // walk out to the nearest scope which isn't more deeply nested.
491e76fa9ecSHeejin Ahn   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
492e76fa9ecSHeejin Ahn     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
493e76fa9ecSHeejin Ahn       if (ScopeTop->getNumber() > Header->getNumber()) {
494e76fa9ecSHeejin Ahn         // Skip over an intervening scope.
4955c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
496e76fa9ecSHeejin Ahn       } else {
497e76fa9ecSHeejin Ahn         // We found a scope level at an appropriate depth.
498e76fa9ecSHeejin Ahn         Header = ScopeTop;
499e76fa9ecSHeejin Ahn         break;
500e76fa9ecSHeejin Ahn       }
501e76fa9ecSHeejin Ahn     }
502e76fa9ecSHeejin Ahn   }
503e76fa9ecSHeejin Ahn 
504e76fa9ecSHeejin Ahn   // Decide where in Header to put the TRY.
505e76fa9ecSHeejin Ahn 
50644a5a4b1SHeejin Ahn   // Instructions that should go before the TRY.
507e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
50844a5a4b1SHeejin Ahn   // Instructions that should go after the TRY.
509e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
510e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
51144a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
51244a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the TRY, because the loop is nested
51344a5a4b1SHeejin Ahn     // in this TRY. Otherwise it should be before the TRY.
514e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
51544a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
51644a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
517e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
518e76fa9ecSHeejin Ahn #ifndef NDEBUG
519e76fa9ecSHeejin Ahn       else
520e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
521e76fa9ecSHeejin Ahn #endif
522e76fa9ecSHeejin Ahn     }
523e76fa9ecSHeejin Ahn 
52444a5a4b1SHeejin Ahn     // All previously inserted BLOCK/TRY markers should be after the TRY because
52544a5a4b1SHeejin Ahn     // they are all nested trys.
52644a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
52744a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
528e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
529e76fa9ecSHeejin Ahn 
530e76fa9ecSHeejin Ahn #ifndef NDEBUG
53144a5a4b1SHeejin Ahn     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
53244a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
53344a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
534e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
535e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
536e76fa9ecSHeejin Ahn #endif
537e76fa9ecSHeejin Ahn 
538e76fa9ecSHeejin Ahn     // Terminators should go after the TRY.
539e76fa9ecSHeejin Ahn     if (MI.isTerminator())
540e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
541e76fa9ecSHeejin Ahn   }
542e76fa9ecSHeejin Ahn 
5436a37c5d6SHeejin Ahn   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
5446a37c5d6SHeejin Ahn   // contain the call within it. So the call should go after the TRY. The
5456a37c5d6SHeejin Ahn   // exception is when the header's terminator is a rethrow instruction, in
5466a37c5d6SHeejin Ahn   // which case that instruction, not a call instruction before it, is gonna
5476a37c5d6SHeejin Ahn   // throw.
5486a37c5d6SHeejin Ahn   MachineInstr *ThrowingCall = nullptr;
5496a37c5d6SHeejin Ahn   if (MBB.isPredecessor(Header)) {
5506a37c5d6SHeejin Ahn     auto TermPos = Header->getFirstTerminator();
5516a37c5d6SHeejin Ahn     if (TermPos == Header->end() ||
5526a37c5d6SHeejin Ahn         TermPos->getOpcode() != WebAssembly::RETHROW) {
5536a37c5d6SHeejin Ahn       for (auto &MI : reverse(*Header)) {
5546a37c5d6SHeejin Ahn         if (MI.isCall()) {
5556a37c5d6SHeejin Ahn           AfterSet.insert(&MI);
5566a37c5d6SHeejin Ahn           ThrowingCall = &MI;
5576a37c5d6SHeejin Ahn           // Possibly throwing calls are usually wrapped by EH_LABEL
5586a37c5d6SHeejin Ahn           // instructions. We don't want to split them and the call.
5596a37c5d6SHeejin Ahn           if (MI.getIterator() != Header->begin() &&
5606a37c5d6SHeejin Ahn               std::prev(MI.getIterator())->isEHLabel()) {
5616a37c5d6SHeejin Ahn             AfterSet.insert(&*std::prev(MI.getIterator()));
5626a37c5d6SHeejin Ahn             ThrowingCall = &*std::prev(MI.getIterator());
5636a37c5d6SHeejin Ahn           }
5646a37c5d6SHeejin Ahn           break;
5656a37c5d6SHeejin Ahn         }
5666a37c5d6SHeejin Ahn       }
5676a37c5d6SHeejin Ahn     }
5686a37c5d6SHeejin Ahn   }
5696a37c5d6SHeejin Ahn 
570e76fa9ecSHeejin Ahn   // Local expression tree should go after the TRY.
5716a37c5d6SHeejin Ahn   // For BLOCK placement, we start the search from the previous instruction of a
5726a37c5d6SHeejin Ahn   // BB's terminator, but in TRY's case, we should start from the previous
5736a37c5d6SHeejin Ahn   // instruction of a call that can throw, or a EH_LABEL that precedes the call,
5746a37c5d6SHeejin Ahn   // because the return values of the call's previous instructions can be
5756a37c5d6SHeejin Ahn   // stackified and consumed by the throwing call.
5766a37c5d6SHeejin Ahn   auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
5776a37c5d6SHeejin Ahn                                     : Header->getFirstTerminator();
5786a37c5d6SHeejin Ahn   for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
579409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
580409b4391SYury Delendik       continue;
581e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
582e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
583e76fa9ecSHeejin Ahn     else
584e76fa9ecSHeejin Ahn       break;
585e76fa9ecSHeejin Ahn   }
586e76fa9ecSHeejin Ahn 
587e76fa9ecSHeejin Ahn   // Add the TRY.
58818c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
589e76fa9ecSHeejin Ahn   MachineInstr *Begin =
590e76fa9ecSHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
591e76fa9ecSHeejin Ahn               TII.get(WebAssembly::TRY))
5922cb27072SThomas Lively           .addImm(int64_t(WebAssembly::BlockType::Void));
593e76fa9ecSHeejin Ahn 
594e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_TRY.
595e76fa9ecSHeejin Ahn   BeforeSet.clear();
596e76fa9ecSHeejin Ahn   AfterSet.clear();
59720cf0749SHeejin Ahn   for (const auto &MI : *Cont) {
598e76fa9ecSHeejin Ahn #ifndef NDEBUG
59944a5a4b1SHeejin Ahn     // END_TRY should precede existing LOOP and BLOCK markers.
60044a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
60144a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::BLOCK)
602e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
603e76fa9ecSHeejin Ahn 
604e76fa9ecSHeejin Ahn     // All END_TRY markers placed earlier belong to exceptions that contains
605e76fa9ecSHeejin Ahn     // this one.
606e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_TRY)
607e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
608e76fa9ecSHeejin Ahn #endif
609e76fa9ecSHeejin Ahn 
610e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and its header is after
611e76fa9ecSHeejin Ahn     // where TRY marker is, this loop is contained within the 'catch' part, so
612e76fa9ecSHeejin Ahn     // the END_TRY marker should go after that. Otherwise, the whole try-catch
613e76fa9ecSHeejin Ahn     // is contained within this loop, so the END_TRY should go before that.
614e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP) {
615222718fdSHeejin Ahn       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
616222718fdSHeejin Ahn       // are in the same BB, LOOP is always before TRY.
617222718fdSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
618e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
619e76fa9ecSHeejin Ahn #ifndef NDEBUG
620e76fa9ecSHeejin Ahn       else
621e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
622e76fa9ecSHeejin Ahn #endif
623e76fa9ecSHeejin Ahn     }
62444a5a4b1SHeejin Ahn 
62544a5a4b1SHeejin Ahn     // It is not possible for an END_BLOCK to be already in this block.
626e76fa9ecSHeejin Ahn   }
627e76fa9ecSHeejin Ahn 
628e76fa9ecSHeejin Ahn   // Mark the end of the TRY.
62920cf0749SHeejin Ahn   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
630e76fa9ecSHeejin Ahn   MachineInstr *End =
63120cf0749SHeejin Ahn       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
632e76fa9ecSHeejin Ahn               TII.get(WebAssembly::END_TRY));
633e76fa9ecSHeejin Ahn   registerTryScope(Begin, End, &MBB);
634e76fa9ecSHeejin Ahn 
63582da1ffcSHeejin Ahn   // Track the farthest-spanning scope that ends at this point. We create two
63682da1ffcSHeejin Ahn   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
63782da1ffcSHeejin Ahn   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
63882da1ffcSHeejin Ahn   // markers should not span across 'catch'. For example, this should not
63982da1ffcSHeejin Ahn   // happen:
64082da1ffcSHeejin Ahn   //
64182da1ffcSHeejin Ahn   // try
64282da1ffcSHeejin Ahn   //   block     --|  (X)
64382da1ffcSHeejin Ahn   // catch         |
64482da1ffcSHeejin Ahn   //   end_block --|
64582da1ffcSHeejin Ahn   // end_try
64682da1ffcSHeejin Ahn   for (int Number : {Cont->getNumber(), MBB.getNumber()}) {
647e76fa9ecSHeejin Ahn     if (!ScopeTops[Number] ||
648e76fa9ecSHeejin Ahn         ScopeTops[Number]->getNumber() > Header->getNumber())
649e76fa9ecSHeejin Ahn       ScopeTops[Number] = Header;
650e76fa9ecSHeejin Ahn   }
65182da1ffcSHeejin Ahn }
652e76fa9ecSHeejin Ahn 
653cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
654cf699b45SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
655cf699b45SHeejin Ahn 
656cf699b45SHeejin Ahn   // When there is an unconditional branch right before a catch instruction and
657cf699b45SHeejin Ahn   // it branches to the end of end_try marker, we don't need the branch, because
658cf699b45SHeejin Ahn   // it there is no exception, the control flow transfers to that point anyway.
659cf699b45SHeejin Ahn   // bb0:
660cf699b45SHeejin Ahn   //   try
661cf699b45SHeejin Ahn   //     ...
662cf699b45SHeejin Ahn   //     br bb2      <- Not necessary
663cf699b45SHeejin Ahn   // bb1:
664cf699b45SHeejin Ahn   //   catch
665cf699b45SHeejin Ahn   //     ...
666cf699b45SHeejin Ahn   // bb2:
667cf699b45SHeejin Ahn   //   end
668cf699b45SHeejin Ahn   for (auto &MBB : MF) {
669cf699b45SHeejin Ahn     if (!MBB.isEHPad())
670cf699b45SHeejin Ahn       continue;
671cf699b45SHeejin Ahn 
672cf699b45SHeejin Ahn     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
673cf699b45SHeejin Ahn     SmallVector<MachineOperand, 4> Cond;
6745c644c9bSHeejin Ahn     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
675cf699b45SHeejin Ahn     MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent();
676cf699b45SHeejin Ahn     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
6773fe6ea46SHeejin Ahn     // This condition means either
6783fe6ea46SHeejin Ahn     // 1. This BB ends with a single unconditional branch whose destinaion is
6793fe6ea46SHeejin Ahn     //    Cont.
6803fe6ea46SHeejin Ahn     // 2. This BB ends with a conditional branch followed by an unconditional
6813fe6ea46SHeejin Ahn     //    branch, and the unconditional branch's destination is Cont.
6823fe6ea46SHeejin Ahn     // In both cases, we want to remove the last (= unconditional) branch.
683cf699b45SHeejin Ahn     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
6843fe6ea46SHeejin Ahn                        (!Cond.empty() && FBB && FBB == Cont))) {
6853fe6ea46SHeejin Ahn       bool ErasedUncondBr = false;
686a5099ad9SHeejin Ahn       (void)ErasedUncondBr;
6873fe6ea46SHeejin Ahn       for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
6883fe6ea46SHeejin Ahn            I != E; --I) {
6893fe6ea46SHeejin Ahn         auto PrevI = std::prev(I);
6903fe6ea46SHeejin Ahn         if (PrevI->isTerminator()) {
6913fe6ea46SHeejin Ahn           assert(PrevI->getOpcode() == WebAssembly::BR);
6923fe6ea46SHeejin Ahn           PrevI->eraseFromParent();
6933fe6ea46SHeejin Ahn           ErasedUncondBr = true;
6943fe6ea46SHeejin Ahn           break;
6953fe6ea46SHeejin Ahn         }
6963fe6ea46SHeejin Ahn       }
6973fe6ea46SHeejin Ahn       assert(ErasedUncondBr && "Unconditional branch not erased!");
6983fe6ea46SHeejin Ahn     }
699cf699b45SHeejin Ahn   }
700cf699b45SHeejin Ahn 
701cf699b45SHeejin Ahn   // When there are block / end_block markers that overlap with try / end_try
702cf699b45SHeejin Ahn   // markers, and the block and try markers' return types are the same, the
703cf699b45SHeejin Ahn   // block /end_block markers are not necessary, because try / end_try markers
704cf699b45SHeejin Ahn   // also can serve as boundaries for branches.
705cf699b45SHeejin Ahn   // block         <- Not necessary
706cf699b45SHeejin Ahn   //   try
707cf699b45SHeejin Ahn   //     ...
708cf699b45SHeejin Ahn   //   catch
709cf699b45SHeejin Ahn   //     ...
710cf699b45SHeejin Ahn   //   end
711cf699b45SHeejin Ahn   // end           <- Not necessary
712cf699b45SHeejin Ahn   SmallVector<MachineInstr *, 32> ToDelete;
713cf699b45SHeejin Ahn   for (auto &MBB : MF) {
714cf699b45SHeejin Ahn     for (auto &MI : MBB) {
715cf699b45SHeejin Ahn       if (MI.getOpcode() != WebAssembly::TRY)
716cf699b45SHeejin Ahn         continue;
717cf699b45SHeejin Ahn 
718cf699b45SHeejin Ahn       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
719cf699b45SHeejin Ahn       MachineBasicBlock *TryBB = Try->getParent();
720cf699b45SHeejin Ahn       MachineBasicBlock *Cont = EndTry->getParent();
721cf699b45SHeejin Ahn       int64_t RetType = Try->getOperand(0).getImm();
7225c644c9bSHeejin Ahn       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
723cf699b45SHeejin Ahn            B != TryBB->begin() && E != Cont->end() &&
724cf699b45SHeejin Ahn            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
725cf699b45SHeejin Ahn            E->getOpcode() == WebAssembly::END_BLOCK &&
726cf699b45SHeejin Ahn            std::prev(B)->getOperand(0).getImm() == RetType;
727cf699b45SHeejin Ahn            --B, ++E) {
728cf699b45SHeejin Ahn         ToDelete.push_back(&*std::prev(B));
729cf699b45SHeejin Ahn         ToDelete.push_back(&*E);
730cf699b45SHeejin Ahn       }
731cf699b45SHeejin Ahn     }
732cf699b45SHeejin Ahn   }
733cf699b45SHeejin Ahn   for (auto *MI : ToDelete) {
734cf699b45SHeejin Ahn     if (MI->getOpcode() == WebAssembly::BLOCK)
735cf699b45SHeejin Ahn       unregisterScope(MI);
736cf699b45SHeejin Ahn     MI->eraseFromParent();
737cf699b45SHeejin Ahn   }
738cf699b45SHeejin Ahn }
739cf699b45SHeejin Ahn 
74083c26eaeSHeejin Ahn // Get the appropriate copy opcode for the given register class.
74183c26eaeSHeejin Ahn static unsigned getCopyOpcode(const TargetRegisterClass *RC) {
74283c26eaeSHeejin Ahn   if (RC == &WebAssembly::I32RegClass)
74383c26eaeSHeejin Ahn     return WebAssembly::COPY_I32;
74483c26eaeSHeejin Ahn   if (RC == &WebAssembly::I64RegClass)
74583c26eaeSHeejin Ahn     return WebAssembly::COPY_I64;
74683c26eaeSHeejin Ahn   if (RC == &WebAssembly::F32RegClass)
74783c26eaeSHeejin Ahn     return WebAssembly::COPY_F32;
74883c26eaeSHeejin Ahn   if (RC == &WebAssembly::F64RegClass)
74983c26eaeSHeejin Ahn     return WebAssembly::COPY_F64;
75083c26eaeSHeejin Ahn   if (RC == &WebAssembly::V128RegClass)
75183c26eaeSHeejin Ahn     return WebAssembly::COPY_V128;
75260653e24SHeejin Ahn   if (RC == &WebAssembly::FUNCREFRegClass)
75360653e24SHeejin Ahn     return WebAssembly::COPY_FUNCREF;
75460653e24SHeejin Ahn   if (RC == &WebAssembly::EXTERNREFRegClass)
75560653e24SHeejin Ahn     return WebAssembly::COPY_EXTERNREF;
75683c26eaeSHeejin Ahn   llvm_unreachable("Unexpected register class");
75783c26eaeSHeejin Ahn }
75883c26eaeSHeejin Ahn 
75961d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that
76061d5c76aSHeejin Ahn // have their uses in Split.
7619e4eadebSHeejin Ahn // FIXME This function will be used when fixing unwind mismatches, but the old
7629e4eadebSHeejin Ahn // version of that function was removed for the moment and the new version has
7639e4eadebSHeejin Ahn // not yet been added. So 'LLVM_ATTRIBUTE_UNUSED' is added to suppress the
7649e4eadebSHeejin Ahn // warning. Remove the attribute after the new functionality is added.
7659e4eadebSHeejin Ahn LLVM_ATTRIBUTE_UNUSED static void
7669e4eadebSHeejin Ahn unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, MachineBasicBlock &Split,
76761d5c76aSHeejin Ahn                              WebAssemblyFunctionInfo &MFI,
76883c26eaeSHeejin Ahn                              MachineRegisterInfo &MRI,
76983c26eaeSHeejin Ahn                              const WebAssemblyInstrInfo &TII) {
77061d5c76aSHeejin Ahn   for (auto &MI : Split) {
77161d5c76aSHeejin Ahn     for (auto &MO : MI.explicit_uses()) {
77261d5c76aSHeejin Ahn       if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg()))
77361d5c76aSHeejin Ahn         continue;
77461d5c76aSHeejin Ahn       if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
77561d5c76aSHeejin Ahn         if (Def->getParent() == &MBB)
77661d5c76aSHeejin Ahn           MFI.unstackifyVReg(MO.getReg());
77761d5c76aSHeejin Ahn     }
77861d5c76aSHeejin Ahn   }
77983c26eaeSHeejin Ahn 
78083c26eaeSHeejin Ahn   // In RegStackify, when a register definition is used multiple times,
78183c26eaeSHeejin Ahn   //    Reg = INST ...
78283c26eaeSHeejin Ahn   //    INST ..., Reg, ...
78383c26eaeSHeejin Ahn   //    INST ..., Reg, ...
78483c26eaeSHeejin Ahn   //    INST ..., Reg, ...
78583c26eaeSHeejin Ahn   //
78683c26eaeSHeejin Ahn   // we introduce a TEE, which has the following form:
78783c26eaeSHeejin Ahn   //    DefReg = INST ...
78883c26eaeSHeejin Ahn   //    TeeReg, Reg = TEE_... DefReg
78983c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
79083c26eaeSHeejin Ahn   //    INST ..., Reg, ...
79183c26eaeSHeejin Ahn   //    INST ..., Reg, ...
79283c26eaeSHeejin Ahn   // with DefReg and TeeReg stackified but Reg not stackified.
79383c26eaeSHeejin Ahn   //
79483c26eaeSHeejin Ahn   // But the invariant that TeeReg should be stackified can be violated while we
79583c26eaeSHeejin Ahn   // unstackify registers in the split BB above. In this case, we convert TEEs
79683c26eaeSHeejin Ahn   // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
79783c26eaeSHeejin Ahn   //    DefReg = INST ...
79883c26eaeSHeejin Ahn   //    TeeReg = COPY DefReg
79983c26eaeSHeejin Ahn   //    Reg = COPY DefReg
80083c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
80183c26eaeSHeejin Ahn   //    INST ..., Reg, ...
80283c26eaeSHeejin Ahn   //    INST ..., Reg, ...
80383c26eaeSHeejin Ahn   for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
80483c26eaeSHeejin Ahn     MachineInstr &MI = *I++;
80583c26eaeSHeejin Ahn     if (!WebAssembly::isTee(MI.getOpcode()))
80683c26eaeSHeejin Ahn       continue;
80783c26eaeSHeejin Ahn     Register TeeReg = MI.getOperand(0).getReg();
80883c26eaeSHeejin Ahn     Register Reg = MI.getOperand(1).getReg();
80983c26eaeSHeejin Ahn     Register DefReg = MI.getOperand(2).getReg();
81083c26eaeSHeejin Ahn     if (!MFI.isVRegStackified(TeeReg)) {
81183c26eaeSHeejin Ahn       // Now we are not using TEE anymore, so unstackify DefReg too
81283c26eaeSHeejin Ahn       MFI.unstackifyVReg(DefReg);
81383c26eaeSHeejin Ahn       unsigned CopyOpc = getCopyOpcode(MRI.getRegClass(DefReg));
81483c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
81583c26eaeSHeejin Ahn           .addReg(DefReg);
81683c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
81783c26eaeSHeejin Ahn       MI.eraseFromParent();
81883c26eaeSHeejin Ahn     }
81983c26eaeSHeejin Ahn   }
82061d5c76aSHeejin Ahn }
82161d5c76aSHeejin Ahn 
822c4ac74fbSHeejin Ahn bool WebAssemblyCFGStackify::fixUnwindMismatches(MachineFunction &MF) {
8239e4eadebSHeejin Ahn   // TODO Implement this
824c4ac74fbSHeejin Ahn   return false;
825c4ac74fbSHeejin Ahn }
826c4ac74fbSHeejin Ahn 
8271d68e80fSDan Gohman static unsigned
82818c56a07SHeejin Ahn getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
8291d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
8301d68e80fSDan Gohman   unsigned Depth = 0;
8311d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
8321d68e80fSDan Gohman     if (X == MBB)
8331d68e80fSDan Gohman       break;
8341d68e80fSDan Gohman     ++Depth;
8351d68e80fSDan Gohman   }
8361d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
8371d68e80fSDan Gohman   return Depth;
8381d68e80fSDan Gohman }
8391d68e80fSDan Gohman 
8402726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
8412726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
8422726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
8432726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
8442726b88cSDan Gohman /// that end at the function end need to have a return type signature that
8452726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
8462726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
847e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
848e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
8492726b88cSDan Gohman 
8502726b88cSDan Gohman   if (MFI.getResults().empty())
8512726b88cSDan Gohman     return;
8522726b88cSDan Gohman 
8532cb27072SThomas Lively   // MCInstLower will add the proper types to multivalue signatures based on the
8542cb27072SThomas Lively   // function return type
8552cb27072SThomas Lively   WebAssembly::BlockType RetType =
8562cb27072SThomas Lively       MFI.getResults().size() > 1
8572cb27072SThomas Lively           ? WebAssembly::BlockType::Multivalue
8582cb27072SThomas Lively           : WebAssembly::BlockType(
8592cb27072SThomas Lively                 WebAssembly::toValType(MFI.getResults().front()));
8602726b88cSDan Gohman 
861d25c17f3SHeejin Ahn   SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist;
862d25c17f3SHeejin Ahn   Worklist.push_back(MF.rbegin()->rbegin());
863d25c17f3SHeejin Ahn 
864d25c17f3SHeejin Ahn   auto Process = [&](MachineBasicBlock::reverse_iterator It) {
865d25c17f3SHeejin Ahn     auto *MBB = It->getParent();
866d25c17f3SHeejin Ahn     while (It != MBB->rend()) {
867d25c17f3SHeejin Ahn       MachineInstr &MI = *It++;
868801bf7ebSShiva Chen       if (MI.isPosition() || MI.isDebugInstr())
8692726b88cSDan Gohman         continue;
8702cb27072SThomas Lively       switch (MI.getOpcode()) {
871d25c17f3SHeejin Ahn       case WebAssembly::END_TRY: {
872d25c17f3SHeejin Ahn         // If a 'try''s return type is fixed, both its try body and catch body
873d25c17f3SHeejin Ahn         // should satisfy the return type, so we need to search 'end'
874d25c17f3SHeejin Ahn         // instructions before its corresponding 'catch' too.
875d25c17f3SHeejin Ahn         auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
876d25c17f3SHeejin Ahn         assert(EHPad);
877d25c17f3SHeejin Ahn         Worklist.push_back(std::next(findCatch(EHPad)->getReverseIterator()));
878d25c17f3SHeejin Ahn         LLVM_FALLTHROUGH;
879d25c17f3SHeejin Ahn       }
8802cb27072SThomas Lively       case WebAssembly::END_BLOCK:
8812cb27072SThomas Lively       case WebAssembly::END_LOOP:
88218c56a07SHeejin Ahn         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
8832726b88cSDan Gohman         continue;
8842cb27072SThomas Lively       default:
885d25c17f3SHeejin Ahn         // Something other than an `end`. We're done for this BB.
8862726b88cSDan Gohman         return;
8872726b88cSDan Gohman       }
8882726b88cSDan Gohman     }
889d25c17f3SHeejin Ahn     // We've reached the beginning of a BB. Continue the search in the previous
890d25c17f3SHeejin Ahn     // BB.
891d25c17f3SHeejin Ahn     Worklist.push_back(MBB->getPrevNode()->rbegin());
892d25c17f3SHeejin Ahn   };
893d25c17f3SHeejin Ahn 
894d25c17f3SHeejin Ahn   while (!Worklist.empty())
895d25c17f3SHeejin Ahn     Process(Worklist.pop_back_val());
8962cb27072SThomas Lively }
8972726b88cSDan Gohman 
898d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
899d934cb88SDan Gohman // were a block.
90018c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF,
901d934cb88SDan Gohman                                 const WebAssemblyInstrInfo &TII) {
90210b31358SDerek Schuff   BuildMI(MF.back(), MF.back().end(),
90310b31358SDerek Schuff           MF.back().findPrevDebugLoc(MF.back().end()),
904d934cb88SDan Gohman           TII.get(WebAssembly::END_FUNCTION));
905d934cb88SDan Gohman }
906d934cb88SDan Gohman 
907e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places.
908e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
909e76fa9ecSHeejin Ahn   // We allocate one more than the number of blocks in the function to
910e76fa9ecSHeejin Ahn   // accommodate for the possible fake block we may insert at the end.
911e76fa9ecSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs() + 1);
9128fe7e86bSDan Gohman   // Place the LOOP for MBB if MBB is the header of a loop.
913e76fa9ecSHeejin Ahn   for (auto &MBB : MF)
914e76fa9ecSHeejin Ahn     placeLoopMarker(MBB);
91544a5a4b1SHeejin Ahn 
916d6f48786SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
91744a5a4b1SHeejin Ahn   for (auto &MBB : MF) {
91844a5a4b1SHeejin Ahn     if (MBB.isEHPad()) {
91944a5a4b1SHeejin Ahn       // Place the TRY for MBB if MBB is the EH pad of an exception.
920e76fa9ecSHeejin Ahn       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
921e76fa9ecSHeejin Ahn           MF.getFunction().hasPersonalityFn())
922e76fa9ecSHeejin Ahn         placeTryMarker(MBB);
92344a5a4b1SHeejin Ahn     } else {
92432807932SDan Gohman       // Place the BLOCK for MBB if MBB is branched to from above.
925e76fa9ecSHeejin Ahn       placeBlockMarker(MBB);
926950a13cfSDan Gohman     }
92744a5a4b1SHeejin Ahn   }
928c4ac74fbSHeejin Ahn   // Fix mismatches in unwind destinations induced by linearizing the code.
929daeead4bSHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
930daeead4bSHeejin Ahn       MF.getFunction().hasPersonalityFn())
931c4ac74fbSHeejin Ahn     fixUnwindMismatches(MF);
93244a5a4b1SHeejin Ahn }
933950a13cfSDan Gohman 
934e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
9351d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
9361d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
9371d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
938e76fa9ecSHeejin Ahn     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) {
939e76fa9ecSHeejin Ahn       MachineInstr &MI = *I;
9401d68e80fSDan Gohman       switch (MI.getOpcode()) {
9411d68e80fSDan Gohman       case WebAssembly::BLOCK:
942e76fa9ecSHeejin Ahn       case WebAssembly::TRY:
943e76fa9ecSHeejin Ahn         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <=
944e76fa9ecSHeejin Ahn                    MBB.getNumber() &&
945e76fa9ecSHeejin Ahn                "Block/try marker should be balanced");
946e76fa9ecSHeejin Ahn         Stack.pop_back();
947e76fa9ecSHeejin Ahn         break;
948e76fa9ecSHeejin Ahn 
9491d68e80fSDan Gohman       case WebAssembly::LOOP:
9501d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
9511d68e80fSDan Gohman         Stack.pop_back();
9521d68e80fSDan Gohman         break;
953e76fa9ecSHeejin Ahn 
9541d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
955e76fa9ecSHeejin Ahn       case WebAssembly::END_TRY:
9561d68e80fSDan Gohman         Stack.push_back(&MBB);
9571d68e80fSDan Gohman         break;
958e76fa9ecSHeejin Ahn 
9591d68e80fSDan Gohman       case WebAssembly::END_LOOP:
960e76fa9ecSHeejin Ahn         Stack.push_back(EndToBegin[&MI]->getParent());
9611d68e80fSDan Gohman         break;
962e76fa9ecSHeejin Ahn 
9631d68e80fSDan Gohman       default:
9641d68e80fSDan Gohman         if (MI.isTerminator()) {
9651d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
9661d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
9671d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
9681d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
9691d68e80fSDan Gohman           for (auto MO : Ops) {
9701d68e80fSDan Gohman             if (MO.isMBB())
97118c56a07SHeejin Ahn               MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB()));
9721d68e80fSDan Gohman             MI.addOperand(MF, MO);
97332807932SDan Gohman           }
9741d68e80fSDan Gohman         }
9751d68e80fSDan Gohman         break;
9761d68e80fSDan Gohman       }
9771d68e80fSDan Gohman     }
9781d68e80fSDan Gohman   }
9791d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
980e76fa9ecSHeejin Ahn }
9812726b88cSDan Gohman 
982e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() {
983e76fa9ecSHeejin Ahn   ScopeTops.clear();
984e76fa9ecSHeejin Ahn   BeginToEnd.clear();
985e76fa9ecSHeejin Ahn   EndToBegin.clear();
986e76fa9ecSHeejin Ahn   TryToEHPad.clear();
987e76fa9ecSHeejin Ahn   EHPadToTry.clear();
988c4ac74fbSHeejin Ahn   AppendixBB = nullptr;
9891d68e80fSDan Gohman }
99032807932SDan Gohman 
991950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
992d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
993950a13cfSDan Gohman                        "********** Function: "
994950a13cfSDan Gohman                     << MF.getName() << '\n');
995cf699b45SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
996950a13cfSDan Gohman 
997e76fa9ecSHeejin Ahn   releaseMemory();
998e76fa9ecSHeejin Ahn 
999e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
10009c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
1001950a13cfSDan Gohman 
1002e76fa9ecSHeejin Ahn   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
1003e76fa9ecSHeejin Ahn   placeMarkers(MF);
1004e76fa9ecSHeejin Ahn 
1005c4ac74fbSHeejin Ahn   // Remove unnecessary instructions possibly introduced by try/end_trys.
1006cf699b45SHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1007cf699b45SHeejin Ahn       MF.getFunction().hasPersonalityFn())
1008cf699b45SHeejin Ahn     removeUnnecessaryInstrs(MF);
1009cf699b45SHeejin Ahn 
1010e76fa9ecSHeejin Ahn   // Convert MBB operands in terminators to relative depth immediates.
1011e76fa9ecSHeejin Ahn   rewriteDepthImmediates(MF);
1012e76fa9ecSHeejin Ahn 
1013e76fa9ecSHeejin Ahn   // Fix up block/loop/try signatures at the end of the function to conform to
1014e76fa9ecSHeejin Ahn   // WebAssembly's rules.
1015e76fa9ecSHeejin Ahn   fixEndsAtEndOfFunction(MF);
1016e76fa9ecSHeejin Ahn 
1017e76fa9ecSHeejin Ahn   // Add an end instruction at the end of the function body.
1018e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1019e76fa9ecSHeejin Ahn   if (!MF.getSubtarget<WebAssemblySubtarget>()
1020e76fa9ecSHeejin Ahn            .getTargetTriple()
1021e76fa9ecSHeejin Ahn            .isOSBinFormatELF())
102218c56a07SHeejin Ahn     appendEndToFunction(MF, TII);
102332807932SDan Gohman 
10241aaa481fSHeejin Ahn   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1025950a13cfSDan Gohman   return true;
1026950a13cfSDan Gohman }
1027