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) {
186*9e4eadebSHeejin 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;
245d6f48786SHeejin Ahn   bool IsBrOnExn = false;
246d6f48786SHeejin Ahn   MachineInstr *BrOnExn = nullptr;
24732807932SDan Gohman   int MBBNumber = MBB.getNumber();
248e76fa9ecSHeejin Ahn   for (MachineBasicBlock *Pred : MBB.predecessors()) {
24932807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
25032807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
25118c56a07SHeejin Ahn       if (explicitlyBranchesTo(Pred, &MBB)) {
25232807932SDan Gohman         IsBranchedTo = true;
253d6f48786SHeejin Ahn         if (Pred->getFirstTerminator()->getOpcode() == WebAssembly::BR_ON_EXN) {
254d6f48786SHeejin Ahn           IsBrOnExn = true;
255d6f48786SHeejin Ahn           assert(!BrOnExn && "There should be only one br_on_exn per block");
256d6f48786SHeejin Ahn           BrOnExn = &*Pred->getFirstTerminator();
257d6f48786SHeejin Ahn         }
258d6f48786SHeejin Ahn       }
25932807932SDan Gohman     }
260e76fa9ecSHeejin Ahn   }
26132807932SDan Gohman   if (!Header)
26232807932SDan Gohman     return;
26332807932SDan Gohman   if (!IsBranchedTo)
26432807932SDan Gohman     return;
26532807932SDan Gohman 
2668fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
2675c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
2688fe7e86bSDan Gohman 
2698fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
2708fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
2718fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
2728fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
2738fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
2748fe7e86bSDan Gohman         // Skip over an intervening scope.
2755c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
2768fe7e86bSDan Gohman       } else {
2778fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
2788fe7e86bSDan Gohman         Header = ScopeTop;
2798fe7e86bSDan Gohman         break;
2808fe7e86bSDan Gohman       }
2818fe7e86bSDan Gohman     }
2828fe7e86bSDan Gohman   }
2838fe7e86bSDan Gohman 
2848fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
285e76fa9ecSHeejin Ahn 
286e76fa9ecSHeejin Ahn   // Instructions that should go before the BLOCK.
287e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
288e76fa9ecSHeejin Ahn   // Instructions that should go after the BLOCK.
289e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
290e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
29144a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
29244a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the BLOCK, because the loop is
29344a5a4b1SHeejin Ahn     // nested in this BLOCK. Otherwise it should be before the BLOCK.
29444a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
29544a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
29644a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
297e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
298e76fa9ecSHeejin Ahn #ifndef NDEBUG
299e76fa9ecSHeejin Ahn       else
300e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
301e76fa9ecSHeejin Ahn #endif
302e76fa9ecSHeejin Ahn     }
303e76fa9ecSHeejin Ahn 
304834debffSHeejin Ahn     // If there is a previously placed BLOCK/TRY marker and its corresponding
305834debffSHeejin Ahn     // END marker is before the current BLOCK's END marker, that should be
306834debffSHeejin Ahn     // placed after this BLOCK. Otherwise it should be placed before this BLOCK
307834debffSHeejin Ahn     // marker.
30844a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
309834debffSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY) {
310834debffSHeejin Ahn       if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
311e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
312834debffSHeejin Ahn #ifndef NDEBUG
313834debffSHeejin Ahn       else
314834debffSHeejin Ahn         BeforeSet.insert(&MI);
315834debffSHeejin Ahn #endif
316834debffSHeejin Ahn     }
317e76fa9ecSHeejin Ahn 
318e76fa9ecSHeejin Ahn #ifndef NDEBUG
319e76fa9ecSHeejin Ahn     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
320e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
321e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
322e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
323e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
324e76fa9ecSHeejin Ahn #endif
325e76fa9ecSHeejin Ahn 
326e76fa9ecSHeejin Ahn     // Terminators should go after the BLOCK.
327e76fa9ecSHeejin Ahn     if (MI.isTerminator())
328e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
329e76fa9ecSHeejin Ahn   }
330e76fa9ecSHeejin Ahn 
331e76fa9ecSHeejin Ahn   // Local expression tree should go after the BLOCK.
332e76fa9ecSHeejin Ahn   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
333e76fa9ecSHeejin Ahn        --I) {
334409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
335409b4391SYury Delendik       continue;
336e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
337e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
338e76fa9ecSHeejin Ahn     else
339e76fa9ecSHeejin Ahn       break;
34032807932SDan Gohman   }
34132807932SDan Gohman 
3428fe7e86bSDan Gohman   // Add the BLOCK.
343d6f48786SHeejin Ahn 
3449f96a58cSHeejin Ahn   // 'br_on_exn' extracts exnref object and pushes variable number of values
345d6f48786SHeejin Ahn   // depending on its tag. For C++ exception, its a single i32 value, and the
346d6f48786SHeejin Ahn   // generated code will be in the form of:
347d6f48786SHeejin Ahn   // block i32
348d6f48786SHeejin Ahn   //   br_on_exn 0, $__cpp_exception
349d6f48786SHeejin Ahn   //   rethrow
350d6f48786SHeejin Ahn   // end_block
3512cb27072SThomas Lively   WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
352d6f48786SHeejin Ahn   if (IsBrOnExn) {
353d6f48786SHeejin Ahn     const char *TagName = BrOnExn->getOperand(1).getSymbolName();
354d6f48786SHeejin Ahn     if (std::strcmp(TagName, "__cpp_exception") != 0)
355d6f48786SHeejin Ahn       llvm_unreachable("Only C++ exception is supported");
3562cb27072SThomas Lively     ReturnType = WebAssembly::BlockType::I32;
357d6f48786SHeejin Ahn   }
358d6f48786SHeejin Ahn 
35918c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
36092401cc1SHeejin Ahn   MachineInstr *Begin =
36192401cc1SHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
3622726b88cSDan Gohman               TII.get(WebAssembly::BLOCK))
363d6f48786SHeejin Ahn           .addImm(int64_t(ReturnType));
3641d68e80fSDan Gohman 
365e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_BLOCK.
366e76fa9ecSHeejin Ahn   BeforeSet.clear();
367e76fa9ecSHeejin Ahn   AfterSet.clear();
368e76fa9ecSHeejin Ahn   for (auto &MI : MBB) {
369e76fa9ecSHeejin Ahn #ifndef NDEBUG
370e76fa9ecSHeejin Ahn     // END_BLOCK should precede existing LOOP and TRY markers.
371e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
372e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
373e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
374e76fa9ecSHeejin Ahn #endif
375e76fa9ecSHeejin Ahn 
376e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and the header of the
377e76fa9ecSHeejin Ahn     // loop is above this block's header, the END_LOOP should be placed after
378e76fa9ecSHeejin Ahn     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
379e76fa9ecSHeejin Ahn     // should be placed before the BLOCK. The same for END_TRY.
380e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP ||
381e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY) {
382e76fa9ecSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
383e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
384e76fa9ecSHeejin Ahn #ifndef NDEBUG
385e76fa9ecSHeejin Ahn       else
386e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
387e76fa9ecSHeejin Ahn #endif
388e76fa9ecSHeejin Ahn     }
389e76fa9ecSHeejin Ahn   }
390e76fa9ecSHeejin Ahn 
3911d68e80fSDan Gohman   // Mark the end of the block.
39218c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
39310b31358SDerek Schuff   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
3942726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
395e76fa9ecSHeejin Ahn   registerScope(Begin, End);
3968fe7e86bSDan Gohman 
3978fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
3988fe7e86bSDan Gohman   int Number = MBB.getNumber();
3998fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
4008fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
4018fe7e86bSDan Gohman     ScopeTops[Number] = Header;
402950a13cfSDan Gohman }
403950a13cfSDan Gohman 
4048fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
405e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
406e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
407e76fa9ecSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
408276f9e8cSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
409276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
410e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
411e76fa9ecSHeejin Ahn 
4128fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
4138fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
4148fe7e86bSDan Gohman     return;
4158fe7e86bSDan Gohman 
4168fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
4178fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
418276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(Loop);
4195c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
420e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
421c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
4225c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
423e3e4a5ffSDan Gohman   }
4248fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
425f6857223SDan Gohman 
426e76fa9ecSHeejin Ahn   // Decide where in Header to put the LOOP.
427e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
428e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
429e76fa9ecSHeejin Ahn   for (const auto &MI : MBB) {
430e76fa9ecSHeejin Ahn     // LOOP marker should be after any existing loop that ends here. Otherwise
431e76fa9ecSHeejin Ahn     // we assume the instruction belongs to the loop.
432e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
433e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
434e76fa9ecSHeejin Ahn #ifndef NDEBUG
435e76fa9ecSHeejin Ahn     else
436e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
437e76fa9ecSHeejin Ahn #endif
438e76fa9ecSHeejin Ahn   }
439e76fa9ecSHeejin Ahn 
440e76fa9ecSHeejin Ahn   // Mark the beginning of the loop.
44118c56a07SHeejin Ahn   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
44210b31358SDerek Schuff   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
4432726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
4442cb27072SThomas Lively                             .addImm(int64_t(WebAssembly::BlockType::Void));
4451d68e80fSDan Gohman 
446e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_LOOP.
447e76fa9ecSHeejin Ahn   BeforeSet.clear();
448e76fa9ecSHeejin Ahn   AfterSet.clear();
449e76fa9ecSHeejin Ahn #ifndef NDEBUG
450e76fa9ecSHeejin Ahn   for (const auto &MI : MBB)
451e76fa9ecSHeejin Ahn     // Existing END_LOOP markers belong to parent loops of this loop
452e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
453e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
454e76fa9ecSHeejin Ahn #endif
455e76fa9ecSHeejin Ahn 
456e76fa9ecSHeejin Ahn   // Mark the end of the loop (using arbitrary debug location that branched to
457e76fa9ecSHeejin Ahn   // the loop end as its location).
45818c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
45967f74aceSHeejin Ahn   DebugLoc EndDL = AfterLoop->pred_empty()
46067f74aceSHeejin Ahn                        ? DebugLoc()
46167f74aceSHeejin Ahn                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
462e76fa9ecSHeejin Ahn   MachineInstr *End =
463e76fa9ecSHeejin Ahn       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
464e76fa9ecSHeejin Ahn   registerScope(Begin, End);
4658fe7e86bSDan Gohman 
4668fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4678fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
468442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
4698fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
4708fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
471e3e4a5ffSDan Gohman }
472950a13cfSDan Gohman 
473e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
47444a5a4b1SHeejin Ahn   assert(MBB.isEHPad());
475e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
476e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
477e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
478276f9e8cSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
479e76fa9ecSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
480276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
481e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
482e76fa9ecSHeejin Ahn 
483e76fa9ecSHeejin Ahn   // Compute the nearest common dominator of all unwind predecessors
484e76fa9ecSHeejin Ahn   MachineBasicBlock *Header = nullptr;
485e76fa9ecSHeejin Ahn   int MBBNumber = MBB.getNumber();
486e76fa9ecSHeejin Ahn   for (auto *Pred : MBB.predecessors()) {
487e76fa9ecSHeejin Ahn     if (Pred->getNumber() < MBBNumber) {
488e76fa9ecSHeejin Ahn       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
48918c56a07SHeejin Ahn       assert(!explicitlyBranchesTo(Pred, &MBB) &&
490e76fa9ecSHeejin Ahn              "Explicit branch to an EH pad!");
491e76fa9ecSHeejin Ahn     }
492e76fa9ecSHeejin Ahn   }
493e76fa9ecSHeejin Ahn   if (!Header)
494e76fa9ecSHeejin Ahn     return;
495e76fa9ecSHeejin Ahn 
496e76fa9ecSHeejin Ahn   // If this try is at the bottom of the function, insert a dummy block at the
497e76fa9ecSHeejin Ahn   // end.
498e76fa9ecSHeejin Ahn   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
499e76fa9ecSHeejin Ahn   assert(WE);
500276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(WE);
501e76fa9ecSHeejin Ahn 
5025c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
503e76fa9ecSHeejin Ahn   if (Iter == MF.end()) {
504c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
5055c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
506e76fa9ecSHeejin Ahn   }
50720cf0749SHeejin Ahn   MachineBasicBlock *Cont = &*Iter;
508e76fa9ecSHeejin Ahn 
50920cf0749SHeejin Ahn   assert(Cont != &MF.front());
5105c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
511e76fa9ecSHeejin Ahn 
512e76fa9ecSHeejin Ahn   // If the nearest common dominator is inside a more deeply nested context,
513e76fa9ecSHeejin Ahn   // walk out to the nearest scope which isn't more deeply nested.
514e76fa9ecSHeejin Ahn   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
515e76fa9ecSHeejin Ahn     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
516e76fa9ecSHeejin Ahn       if (ScopeTop->getNumber() > Header->getNumber()) {
517e76fa9ecSHeejin Ahn         // Skip over an intervening scope.
5185c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
519e76fa9ecSHeejin Ahn       } else {
520e76fa9ecSHeejin Ahn         // We found a scope level at an appropriate depth.
521e76fa9ecSHeejin Ahn         Header = ScopeTop;
522e76fa9ecSHeejin Ahn         break;
523e76fa9ecSHeejin Ahn       }
524e76fa9ecSHeejin Ahn     }
525e76fa9ecSHeejin Ahn   }
526e76fa9ecSHeejin Ahn 
527e76fa9ecSHeejin Ahn   // Decide where in Header to put the TRY.
528e76fa9ecSHeejin Ahn 
52944a5a4b1SHeejin Ahn   // Instructions that should go before the TRY.
530e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
53144a5a4b1SHeejin Ahn   // Instructions that should go after the TRY.
532e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
533e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
53444a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
53544a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the TRY, because the loop is nested
53644a5a4b1SHeejin Ahn     // in this TRY. Otherwise it should be before the TRY.
537e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
53844a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
53944a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
540e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
541e76fa9ecSHeejin Ahn #ifndef NDEBUG
542e76fa9ecSHeejin Ahn       else
543e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
544e76fa9ecSHeejin Ahn #endif
545e76fa9ecSHeejin Ahn     }
546e76fa9ecSHeejin Ahn 
54744a5a4b1SHeejin Ahn     // All previously inserted BLOCK/TRY markers should be after the TRY because
54844a5a4b1SHeejin Ahn     // they are all nested trys.
54944a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
55044a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
551e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
552e76fa9ecSHeejin Ahn 
553e76fa9ecSHeejin Ahn #ifndef NDEBUG
55444a5a4b1SHeejin Ahn     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
55544a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
55644a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
557e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
558e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
559e76fa9ecSHeejin Ahn #endif
560e76fa9ecSHeejin Ahn 
561e76fa9ecSHeejin Ahn     // Terminators should go after the TRY.
562e76fa9ecSHeejin Ahn     if (MI.isTerminator())
563e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
564e76fa9ecSHeejin Ahn   }
565e76fa9ecSHeejin Ahn 
5666a37c5d6SHeejin Ahn   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
5676a37c5d6SHeejin Ahn   // contain the call within it. So the call should go after the TRY. The
5686a37c5d6SHeejin Ahn   // exception is when the header's terminator is a rethrow instruction, in
5696a37c5d6SHeejin Ahn   // which case that instruction, not a call instruction before it, is gonna
5706a37c5d6SHeejin Ahn   // throw.
5716a37c5d6SHeejin Ahn   MachineInstr *ThrowingCall = nullptr;
5726a37c5d6SHeejin Ahn   if (MBB.isPredecessor(Header)) {
5736a37c5d6SHeejin Ahn     auto TermPos = Header->getFirstTerminator();
5746a37c5d6SHeejin Ahn     if (TermPos == Header->end() ||
5756a37c5d6SHeejin Ahn         TermPos->getOpcode() != WebAssembly::RETHROW) {
5766a37c5d6SHeejin Ahn       for (auto &MI : reverse(*Header)) {
5776a37c5d6SHeejin Ahn         if (MI.isCall()) {
5786a37c5d6SHeejin Ahn           AfterSet.insert(&MI);
5796a37c5d6SHeejin Ahn           ThrowingCall = &MI;
5806a37c5d6SHeejin Ahn           // Possibly throwing calls are usually wrapped by EH_LABEL
5816a37c5d6SHeejin Ahn           // instructions. We don't want to split them and the call.
5826a37c5d6SHeejin Ahn           if (MI.getIterator() != Header->begin() &&
5836a37c5d6SHeejin Ahn               std::prev(MI.getIterator())->isEHLabel()) {
5846a37c5d6SHeejin Ahn             AfterSet.insert(&*std::prev(MI.getIterator()));
5856a37c5d6SHeejin Ahn             ThrowingCall = &*std::prev(MI.getIterator());
5866a37c5d6SHeejin Ahn           }
5876a37c5d6SHeejin Ahn           break;
5886a37c5d6SHeejin Ahn         }
5896a37c5d6SHeejin Ahn       }
5906a37c5d6SHeejin Ahn     }
5916a37c5d6SHeejin Ahn   }
5926a37c5d6SHeejin Ahn 
593e76fa9ecSHeejin Ahn   // Local expression tree should go after the TRY.
5946a37c5d6SHeejin Ahn   // For BLOCK placement, we start the search from the previous instruction of a
5956a37c5d6SHeejin Ahn   // BB's terminator, but in TRY's case, we should start from the previous
5966a37c5d6SHeejin Ahn   // instruction of a call that can throw, or a EH_LABEL that precedes the call,
5976a37c5d6SHeejin Ahn   // because the return values of the call's previous instructions can be
5986a37c5d6SHeejin Ahn   // stackified and consumed by the throwing call.
5996a37c5d6SHeejin Ahn   auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
6006a37c5d6SHeejin Ahn                                     : Header->getFirstTerminator();
6016a37c5d6SHeejin Ahn   for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
602409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
603409b4391SYury Delendik       continue;
604e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
605e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
606e76fa9ecSHeejin Ahn     else
607e76fa9ecSHeejin Ahn       break;
608e76fa9ecSHeejin Ahn   }
609e76fa9ecSHeejin Ahn 
610e76fa9ecSHeejin Ahn   // Add the TRY.
61118c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
612e76fa9ecSHeejin Ahn   MachineInstr *Begin =
613e76fa9ecSHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
614e76fa9ecSHeejin Ahn               TII.get(WebAssembly::TRY))
6152cb27072SThomas Lively           .addImm(int64_t(WebAssembly::BlockType::Void));
616e76fa9ecSHeejin Ahn 
617e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_TRY.
618e76fa9ecSHeejin Ahn   BeforeSet.clear();
619e76fa9ecSHeejin Ahn   AfterSet.clear();
62020cf0749SHeejin Ahn   for (const auto &MI : *Cont) {
621e76fa9ecSHeejin Ahn #ifndef NDEBUG
62244a5a4b1SHeejin Ahn     // END_TRY should precede existing LOOP and BLOCK markers.
62344a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
62444a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::BLOCK)
625e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
626e76fa9ecSHeejin Ahn 
627e76fa9ecSHeejin Ahn     // All END_TRY markers placed earlier belong to exceptions that contains
628e76fa9ecSHeejin Ahn     // this one.
629e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_TRY)
630e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
631e76fa9ecSHeejin Ahn #endif
632e76fa9ecSHeejin Ahn 
633e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and its header is after
634e76fa9ecSHeejin Ahn     // where TRY marker is, this loop is contained within the 'catch' part, so
635e76fa9ecSHeejin Ahn     // the END_TRY marker should go after that. Otherwise, the whole try-catch
636e76fa9ecSHeejin Ahn     // is contained within this loop, so the END_TRY should go before that.
637e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP) {
638222718fdSHeejin Ahn       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
639222718fdSHeejin Ahn       // are in the same BB, LOOP is always before TRY.
640222718fdSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
641e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
642e76fa9ecSHeejin Ahn #ifndef NDEBUG
643e76fa9ecSHeejin Ahn       else
644e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
645e76fa9ecSHeejin Ahn #endif
646e76fa9ecSHeejin Ahn     }
64744a5a4b1SHeejin Ahn 
64844a5a4b1SHeejin Ahn     // It is not possible for an END_BLOCK to be already in this block.
649e76fa9ecSHeejin Ahn   }
650e76fa9ecSHeejin Ahn 
651e76fa9ecSHeejin Ahn   // Mark the end of the TRY.
65220cf0749SHeejin Ahn   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
653e76fa9ecSHeejin Ahn   MachineInstr *End =
65420cf0749SHeejin Ahn       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
655e76fa9ecSHeejin Ahn               TII.get(WebAssembly::END_TRY));
656e76fa9ecSHeejin Ahn   registerTryScope(Begin, End, &MBB);
657e76fa9ecSHeejin Ahn 
65882da1ffcSHeejin Ahn   // Track the farthest-spanning scope that ends at this point. We create two
65982da1ffcSHeejin Ahn   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
66082da1ffcSHeejin Ahn   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
66182da1ffcSHeejin Ahn   // markers should not span across 'catch'. For example, this should not
66282da1ffcSHeejin Ahn   // happen:
66382da1ffcSHeejin Ahn   //
66482da1ffcSHeejin Ahn   // try
66582da1ffcSHeejin Ahn   //   block     --|  (X)
66682da1ffcSHeejin Ahn   // catch         |
66782da1ffcSHeejin Ahn   //   end_block --|
66882da1ffcSHeejin Ahn   // end_try
66982da1ffcSHeejin Ahn   for (int Number : {Cont->getNumber(), MBB.getNumber()}) {
670e76fa9ecSHeejin Ahn     if (!ScopeTops[Number] ||
671e76fa9ecSHeejin Ahn         ScopeTops[Number]->getNumber() > Header->getNumber())
672e76fa9ecSHeejin Ahn       ScopeTops[Number] = Header;
673e76fa9ecSHeejin Ahn   }
67482da1ffcSHeejin Ahn }
675e76fa9ecSHeejin Ahn 
676cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
677cf699b45SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
678cf699b45SHeejin Ahn 
679cf699b45SHeejin Ahn   // When there is an unconditional branch right before a catch instruction and
680cf699b45SHeejin Ahn   // it branches to the end of end_try marker, we don't need the branch, because
681cf699b45SHeejin Ahn   // it there is no exception, the control flow transfers to that point anyway.
682cf699b45SHeejin Ahn   // bb0:
683cf699b45SHeejin Ahn   //   try
684cf699b45SHeejin Ahn   //     ...
685cf699b45SHeejin Ahn   //     br bb2      <- Not necessary
686cf699b45SHeejin Ahn   // bb1:
687cf699b45SHeejin Ahn   //   catch
688cf699b45SHeejin Ahn   //     ...
689cf699b45SHeejin Ahn   // bb2:
690cf699b45SHeejin Ahn   //   end
691cf699b45SHeejin Ahn   for (auto &MBB : MF) {
692cf699b45SHeejin Ahn     if (!MBB.isEHPad())
693cf699b45SHeejin Ahn       continue;
694cf699b45SHeejin Ahn 
695cf699b45SHeejin Ahn     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
696cf699b45SHeejin Ahn     SmallVector<MachineOperand, 4> Cond;
6975c644c9bSHeejin Ahn     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
698cf699b45SHeejin Ahn     MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent();
699cf699b45SHeejin Ahn     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
7003fe6ea46SHeejin Ahn     // This condition means either
7013fe6ea46SHeejin Ahn     // 1. This BB ends with a single unconditional branch whose destinaion is
7023fe6ea46SHeejin Ahn     //    Cont.
7033fe6ea46SHeejin Ahn     // 2. This BB ends with a conditional branch followed by an unconditional
7043fe6ea46SHeejin Ahn     //    branch, and the unconditional branch's destination is Cont.
7053fe6ea46SHeejin Ahn     // In both cases, we want to remove the last (= unconditional) branch.
706cf699b45SHeejin Ahn     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
7073fe6ea46SHeejin Ahn                        (!Cond.empty() && FBB && FBB == Cont))) {
7083fe6ea46SHeejin Ahn       bool ErasedUncondBr = false;
709a5099ad9SHeejin Ahn       (void)ErasedUncondBr;
7103fe6ea46SHeejin Ahn       for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
7113fe6ea46SHeejin Ahn            I != E; --I) {
7123fe6ea46SHeejin Ahn         auto PrevI = std::prev(I);
7133fe6ea46SHeejin Ahn         if (PrevI->isTerminator()) {
7143fe6ea46SHeejin Ahn           assert(PrevI->getOpcode() == WebAssembly::BR);
7153fe6ea46SHeejin Ahn           PrevI->eraseFromParent();
7163fe6ea46SHeejin Ahn           ErasedUncondBr = true;
7173fe6ea46SHeejin Ahn           break;
7183fe6ea46SHeejin Ahn         }
7193fe6ea46SHeejin Ahn       }
7203fe6ea46SHeejin Ahn       assert(ErasedUncondBr && "Unconditional branch not erased!");
7213fe6ea46SHeejin Ahn     }
722cf699b45SHeejin Ahn   }
723cf699b45SHeejin Ahn 
724cf699b45SHeejin Ahn   // When there are block / end_block markers that overlap with try / end_try
725cf699b45SHeejin Ahn   // markers, and the block and try markers' return types are the same, the
726cf699b45SHeejin Ahn   // block /end_block markers are not necessary, because try / end_try markers
727cf699b45SHeejin Ahn   // also can serve as boundaries for branches.
728cf699b45SHeejin Ahn   // block         <- Not necessary
729cf699b45SHeejin Ahn   //   try
730cf699b45SHeejin Ahn   //     ...
731cf699b45SHeejin Ahn   //   catch
732cf699b45SHeejin Ahn   //     ...
733cf699b45SHeejin Ahn   //   end
734cf699b45SHeejin Ahn   // end           <- Not necessary
735cf699b45SHeejin Ahn   SmallVector<MachineInstr *, 32> ToDelete;
736cf699b45SHeejin Ahn   for (auto &MBB : MF) {
737cf699b45SHeejin Ahn     for (auto &MI : MBB) {
738cf699b45SHeejin Ahn       if (MI.getOpcode() != WebAssembly::TRY)
739cf699b45SHeejin Ahn         continue;
740cf699b45SHeejin Ahn 
741cf699b45SHeejin Ahn       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
742cf699b45SHeejin Ahn       MachineBasicBlock *TryBB = Try->getParent();
743cf699b45SHeejin Ahn       MachineBasicBlock *Cont = EndTry->getParent();
744cf699b45SHeejin Ahn       int64_t RetType = Try->getOperand(0).getImm();
7455c644c9bSHeejin Ahn       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
746cf699b45SHeejin Ahn            B != TryBB->begin() && E != Cont->end() &&
747cf699b45SHeejin Ahn            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
748cf699b45SHeejin Ahn            E->getOpcode() == WebAssembly::END_BLOCK &&
749cf699b45SHeejin Ahn            std::prev(B)->getOperand(0).getImm() == RetType;
750cf699b45SHeejin Ahn            --B, ++E) {
751cf699b45SHeejin Ahn         ToDelete.push_back(&*std::prev(B));
752cf699b45SHeejin Ahn         ToDelete.push_back(&*E);
753cf699b45SHeejin Ahn       }
754cf699b45SHeejin Ahn     }
755cf699b45SHeejin Ahn   }
756cf699b45SHeejin Ahn   for (auto *MI : ToDelete) {
757cf699b45SHeejin Ahn     if (MI->getOpcode() == WebAssembly::BLOCK)
758cf699b45SHeejin Ahn       unregisterScope(MI);
759cf699b45SHeejin Ahn     MI->eraseFromParent();
760cf699b45SHeejin Ahn   }
761cf699b45SHeejin Ahn }
762cf699b45SHeejin Ahn 
76383c26eaeSHeejin Ahn // Get the appropriate copy opcode for the given register class.
76483c26eaeSHeejin Ahn static unsigned getCopyOpcode(const TargetRegisterClass *RC) {
76583c26eaeSHeejin Ahn   if (RC == &WebAssembly::I32RegClass)
76683c26eaeSHeejin Ahn     return WebAssembly::COPY_I32;
76783c26eaeSHeejin Ahn   if (RC == &WebAssembly::I64RegClass)
76883c26eaeSHeejin Ahn     return WebAssembly::COPY_I64;
76983c26eaeSHeejin Ahn   if (RC == &WebAssembly::F32RegClass)
77083c26eaeSHeejin Ahn     return WebAssembly::COPY_F32;
77183c26eaeSHeejin Ahn   if (RC == &WebAssembly::F64RegClass)
77283c26eaeSHeejin Ahn     return WebAssembly::COPY_F64;
77383c26eaeSHeejin Ahn   if (RC == &WebAssembly::V128RegClass)
77483c26eaeSHeejin Ahn     return WebAssembly::COPY_V128;
77560653e24SHeejin Ahn   if (RC == &WebAssembly::FUNCREFRegClass)
77660653e24SHeejin Ahn     return WebAssembly::COPY_FUNCREF;
77760653e24SHeejin Ahn   if (RC == &WebAssembly::EXTERNREFRegClass)
77860653e24SHeejin Ahn     return WebAssembly::COPY_EXTERNREF;
77983c26eaeSHeejin Ahn   if (RC == &WebAssembly::EXNREFRegClass)
78083c26eaeSHeejin Ahn     return WebAssembly::COPY_EXNREF;
78183c26eaeSHeejin Ahn   llvm_unreachable("Unexpected register class");
78283c26eaeSHeejin Ahn }
78383c26eaeSHeejin Ahn 
78461d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that
78561d5c76aSHeejin Ahn // have their uses in Split.
786*9e4eadebSHeejin Ahn // FIXME This function will be used when fixing unwind mismatches, but the old
787*9e4eadebSHeejin Ahn // version of that function was removed for the moment and the new version has
788*9e4eadebSHeejin Ahn // not yet been added. So 'LLVM_ATTRIBUTE_UNUSED' is added to suppress the
789*9e4eadebSHeejin Ahn // warning. Remove the attribute after the new functionality is added.
790*9e4eadebSHeejin Ahn LLVM_ATTRIBUTE_UNUSED static void
791*9e4eadebSHeejin Ahn unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, MachineBasicBlock &Split,
79261d5c76aSHeejin Ahn                              WebAssemblyFunctionInfo &MFI,
79383c26eaeSHeejin Ahn                              MachineRegisterInfo &MRI,
79483c26eaeSHeejin Ahn                              const WebAssemblyInstrInfo &TII) {
79561d5c76aSHeejin Ahn   for (auto &MI : Split) {
79661d5c76aSHeejin Ahn     for (auto &MO : MI.explicit_uses()) {
79761d5c76aSHeejin Ahn       if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg()))
79861d5c76aSHeejin Ahn         continue;
79961d5c76aSHeejin Ahn       if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
80061d5c76aSHeejin Ahn         if (Def->getParent() == &MBB)
80161d5c76aSHeejin Ahn           MFI.unstackifyVReg(MO.getReg());
80261d5c76aSHeejin Ahn     }
80361d5c76aSHeejin Ahn   }
80483c26eaeSHeejin Ahn 
80583c26eaeSHeejin Ahn   // In RegStackify, when a register definition is used multiple times,
80683c26eaeSHeejin Ahn   //    Reg = INST ...
80783c26eaeSHeejin Ahn   //    INST ..., Reg, ...
80883c26eaeSHeejin Ahn   //    INST ..., Reg, ...
80983c26eaeSHeejin Ahn   //    INST ..., Reg, ...
81083c26eaeSHeejin Ahn   //
81183c26eaeSHeejin Ahn   // we introduce a TEE, which has the following form:
81283c26eaeSHeejin Ahn   //    DefReg = INST ...
81383c26eaeSHeejin Ahn   //    TeeReg, Reg = TEE_... DefReg
81483c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
81583c26eaeSHeejin Ahn   //    INST ..., Reg, ...
81683c26eaeSHeejin Ahn   //    INST ..., Reg, ...
81783c26eaeSHeejin Ahn   // with DefReg and TeeReg stackified but Reg not stackified.
81883c26eaeSHeejin Ahn   //
81983c26eaeSHeejin Ahn   // But the invariant that TeeReg should be stackified can be violated while we
82083c26eaeSHeejin Ahn   // unstackify registers in the split BB above. In this case, we convert TEEs
82183c26eaeSHeejin Ahn   // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
82283c26eaeSHeejin Ahn   //    DefReg = INST ...
82383c26eaeSHeejin Ahn   //    TeeReg = COPY DefReg
82483c26eaeSHeejin Ahn   //    Reg = COPY DefReg
82583c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
82683c26eaeSHeejin Ahn   //    INST ..., Reg, ...
82783c26eaeSHeejin Ahn   //    INST ..., Reg, ...
82883c26eaeSHeejin Ahn   for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
82983c26eaeSHeejin Ahn     MachineInstr &MI = *I++;
83083c26eaeSHeejin Ahn     if (!WebAssembly::isTee(MI.getOpcode()))
83183c26eaeSHeejin Ahn       continue;
83283c26eaeSHeejin Ahn     Register TeeReg = MI.getOperand(0).getReg();
83383c26eaeSHeejin Ahn     Register Reg = MI.getOperand(1).getReg();
83483c26eaeSHeejin Ahn     Register DefReg = MI.getOperand(2).getReg();
83583c26eaeSHeejin Ahn     if (!MFI.isVRegStackified(TeeReg)) {
83683c26eaeSHeejin Ahn       // Now we are not using TEE anymore, so unstackify DefReg too
83783c26eaeSHeejin Ahn       MFI.unstackifyVReg(DefReg);
83883c26eaeSHeejin Ahn       unsigned CopyOpc = getCopyOpcode(MRI.getRegClass(DefReg));
83983c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
84083c26eaeSHeejin Ahn           .addReg(DefReg);
84183c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
84283c26eaeSHeejin Ahn       MI.eraseFromParent();
84383c26eaeSHeejin Ahn     }
84483c26eaeSHeejin Ahn   }
84561d5c76aSHeejin Ahn }
84661d5c76aSHeejin Ahn 
847c4ac74fbSHeejin Ahn bool WebAssemblyCFGStackify::fixUnwindMismatches(MachineFunction &MF) {
848*9e4eadebSHeejin Ahn   // TODO Implement this
849c4ac74fbSHeejin Ahn   return false;
850c4ac74fbSHeejin Ahn }
851c4ac74fbSHeejin Ahn 
8521d68e80fSDan Gohman static unsigned
85318c56a07SHeejin Ahn getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
8541d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
8551d68e80fSDan Gohman   unsigned Depth = 0;
8561d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
8571d68e80fSDan Gohman     if (X == MBB)
8581d68e80fSDan Gohman       break;
8591d68e80fSDan Gohman     ++Depth;
8601d68e80fSDan Gohman   }
8611d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
8621d68e80fSDan Gohman   return Depth;
8631d68e80fSDan Gohman }
8641d68e80fSDan Gohman 
8652726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
8662726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
8672726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
8682726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
8692726b88cSDan Gohman /// that end at the function end need to have a return type signature that
8702726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
8712726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
872e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
873e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
8742726b88cSDan Gohman 
8752726b88cSDan Gohman   if (MFI.getResults().empty())
8762726b88cSDan Gohman     return;
8772726b88cSDan Gohman 
8782cb27072SThomas Lively   // MCInstLower will add the proper types to multivalue signatures based on the
8792cb27072SThomas Lively   // function return type
8802cb27072SThomas Lively   WebAssembly::BlockType RetType =
8812cb27072SThomas Lively       MFI.getResults().size() > 1
8822cb27072SThomas Lively           ? WebAssembly::BlockType::Multivalue
8832cb27072SThomas Lively           : WebAssembly::BlockType(
8842cb27072SThomas Lively                 WebAssembly::toValType(MFI.getResults().front()));
8852726b88cSDan Gohman 
886d25c17f3SHeejin Ahn   SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist;
887d25c17f3SHeejin Ahn   Worklist.push_back(MF.rbegin()->rbegin());
888d25c17f3SHeejin Ahn 
889d25c17f3SHeejin Ahn   auto Process = [&](MachineBasicBlock::reverse_iterator It) {
890d25c17f3SHeejin Ahn     auto *MBB = It->getParent();
891d25c17f3SHeejin Ahn     while (It != MBB->rend()) {
892d25c17f3SHeejin Ahn       MachineInstr &MI = *It++;
893801bf7ebSShiva Chen       if (MI.isPosition() || MI.isDebugInstr())
8942726b88cSDan Gohman         continue;
8952cb27072SThomas Lively       switch (MI.getOpcode()) {
896d25c17f3SHeejin Ahn       case WebAssembly::END_TRY: {
897d25c17f3SHeejin Ahn         // If a 'try''s return type is fixed, both its try body and catch body
898d25c17f3SHeejin Ahn         // should satisfy the return type, so we need to search 'end'
899d25c17f3SHeejin Ahn         // instructions before its corresponding 'catch' too.
900d25c17f3SHeejin Ahn         auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
901d25c17f3SHeejin Ahn         assert(EHPad);
902d25c17f3SHeejin Ahn         Worklist.push_back(std::next(findCatch(EHPad)->getReverseIterator()));
903d25c17f3SHeejin Ahn         LLVM_FALLTHROUGH;
904d25c17f3SHeejin Ahn       }
9052cb27072SThomas Lively       case WebAssembly::END_BLOCK:
9062cb27072SThomas Lively       case WebAssembly::END_LOOP:
90718c56a07SHeejin Ahn         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
9082726b88cSDan Gohman         continue;
9092cb27072SThomas Lively       default:
910d25c17f3SHeejin Ahn         // Something other than an `end`. We're done for this BB.
9112726b88cSDan Gohman         return;
9122726b88cSDan Gohman       }
9132726b88cSDan Gohman     }
914d25c17f3SHeejin Ahn     // We've reached the beginning of a BB. Continue the search in the previous
915d25c17f3SHeejin Ahn     // BB.
916d25c17f3SHeejin Ahn     Worklist.push_back(MBB->getPrevNode()->rbegin());
917d25c17f3SHeejin Ahn   };
918d25c17f3SHeejin Ahn 
919d25c17f3SHeejin Ahn   while (!Worklist.empty())
920d25c17f3SHeejin Ahn     Process(Worklist.pop_back_val());
9212cb27072SThomas Lively }
9222726b88cSDan Gohman 
923d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
924d934cb88SDan Gohman // were a block.
92518c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF,
926d934cb88SDan Gohman                                 const WebAssemblyInstrInfo &TII) {
92710b31358SDerek Schuff   BuildMI(MF.back(), MF.back().end(),
92810b31358SDerek Schuff           MF.back().findPrevDebugLoc(MF.back().end()),
929d934cb88SDan Gohman           TII.get(WebAssembly::END_FUNCTION));
930d934cb88SDan Gohman }
931d934cb88SDan Gohman 
932e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places.
933e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
934e76fa9ecSHeejin Ahn   // We allocate one more than the number of blocks in the function to
935e76fa9ecSHeejin Ahn   // accommodate for the possible fake block we may insert at the end.
936e76fa9ecSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs() + 1);
9378fe7e86bSDan Gohman   // Place the LOOP for MBB if MBB is the header of a loop.
938e76fa9ecSHeejin Ahn   for (auto &MBB : MF)
939e76fa9ecSHeejin Ahn     placeLoopMarker(MBB);
94044a5a4b1SHeejin Ahn 
941d6f48786SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
94244a5a4b1SHeejin Ahn   for (auto &MBB : MF) {
94344a5a4b1SHeejin Ahn     if (MBB.isEHPad()) {
94444a5a4b1SHeejin Ahn       // Place the TRY for MBB if MBB is the EH pad of an exception.
945e76fa9ecSHeejin Ahn       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
946e76fa9ecSHeejin Ahn           MF.getFunction().hasPersonalityFn())
947e76fa9ecSHeejin Ahn         placeTryMarker(MBB);
94844a5a4b1SHeejin Ahn     } else {
94932807932SDan Gohman       // Place the BLOCK for MBB if MBB is branched to from above.
950e76fa9ecSHeejin Ahn       placeBlockMarker(MBB);
951950a13cfSDan Gohman     }
95244a5a4b1SHeejin Ahn   }
953c4ac74fbSHeejin Ahn   // Fix mismatches in unwind destinations induced by linearizing the code.
954daeead4bSHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
955daeead4bSHeejin Ahn       MF.getFunction().hasPersonalityFn())
956c4ac74fbSHeejin Ahn     fixUnwindMismatches(MF);
95744a5a4b1SHeejin Ahn }
958950a13cfSDan Gohman 
959e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
9601d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
9611d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
9621d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
963e76fa9ecSHeejin Ahn     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) {
964e76fa9ecSHeejin Ahn       MachineInstr &MI = *I;
9651d68e80fSDan Gohman       switch (MI.getOpcode()) {
9661d68e80fSDan Gohman       case WebAssembly::BLOCK:
967e76fa9ecSHeejin Ahn       case WebAssembly::TRY:
968e76fa9ecSHeejin Ahn         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <=
969e76fa9ecSHeejin Ahn                    MBB.getNumber() &&
970e76fa9ecSHeejin Ahn                "Block/try marker should be balanced");
971e76fa9ecSHeejin Ahn         Stack.pop_back();
972e76fa9ecSHeejin Ahn         break;
973e76fa9ecSHeejin Ahn 
9741d68e80fSDan Gohman       case WebAssembly::LOOP:
9751d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
9761d68e80fSDan Gohman         Stack.pop_back();
9771d68e80fSDan Gohman         break;
978e76fa9ecSHeejin Ahn 
9791d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
980e76fa9ecSHeejin Ahn       case WebAssembly::END_TRY:
9811d68e80fSDan Gohman         Stack.push_back(&MBB);
9821d68e80fSDan Gohman         break;
983e76fa9ecSHeejin Ahn 
9841d68e80fSDan Gohman       case WebAssembly::END_LOOP:
985e76fa9ecSHeejin Ahn         Stack.push_back(EndToBegin[&MI]->getParent());
9861d68e80fSDan Gohman         break;
987e76fa9ecSHeejin Ahn 
9881d68e80fSDan Gohman       default:
9891d68e80fSDan Gohman         if (MI.isTerminator()) {
9901d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
9911d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
9921d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
9931d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
9941d68e80fSDan Gohman           for (auto MO : Ops) {
9951d68e80fSDan Gohman             if (MO.isMBB())
99618c56a07SHeejin Ahn               MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB()));
9971d68e80fSDan Gohman             MI.addOperand(MF, MO);
99832807932SDan Gohman           }
9991d68e80fSDan Gohman         }
10001d68e80fSDan Gohman         break;
10011d68e80fSDan Gohman       }
10021d68e80fSDan Gohman     }
10031d68e80fSDan Gohman   }
10041d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
1005e76fa9ecSHeejin Ahn }
10062726b88cSDan Gohman 
1007e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() {
1008e76fa9ecSHeejin Ahn   ScopeTops.clear();
1009e76fa9ecSHeejin Ahn   BeginToEnd.clear();
1010e76fa9ecSHeejin Ahn   EndToBegin.clear();
1011e76fa9ecSHeejin Ahn   TryToEHPad.clear();
1012e76fa9ecSHeejin Ahn   EHPadToTry.clear();
1013c4ac74fbSHeejin Ahn   AppendixBB = nullptr;
10141d68e80fSDan Gohman }
101532807932SDan Gohman 
1016950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
1017d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
1018950a13cfSDan Gohman                        "********** Function: "
1019950a13cfSDan Gohman                     << MF.getName() << '\n');
1020cf699b45SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1021950a13cfSDan Gohman 
1022e76fa9ecSHeejin Ahn   releaseMemory();
1023e76fa9ecSHeejin Ahn 
1024e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
10259c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
1026950a13cfSDan Gohman 
1027e76fa9ecSHeejin Ahn   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
1028e76fa9ecSHeejin Ahn   placeMarkers(MF);
1029e76fa9ecSHeejin Ahn 
1030c4ac74fbSHeejin Ahn   // Remove unnecessary instructions possibly introduced by try/end_trys.
1031cf699b45SHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1032cf699b45SHeejin Ahn       MF.getFunction().hasPersonalityFn())
1033cf699b45SHeejin Ahn     removeUnnecessaryInstrs(MF);
1034cf699b45SHeejin Ahn 
1035e76fa9ecSHeejin Ahn   // Convert MBB operands in terminators to relative depth immediates.
1036e76fa9ecSHeejin Ahn   rewriteDepthImmediates(MF);
1037e76fa9ecSHeejin Ahn 
1038e76fa9ecSHeejin Ahn   // Fix up block/loop/try signatures at the end of the function to conform to
1039e76fa9ecSHeejin Ahn   // WebAssembly's rules.
1040e76fa9ecSHeejin Ahn   fixEndsAtEndOfFunction(MF);
1041e76fa9ecSHeejin Ahn 
1042e76fa9ecSHeejin Ahn   // Add an end instruction at the end of the function body.
1043e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1044e76fa9ecSHeejin Ahn   if (!MF.getSubtarget<WebAssemblySubtarget>()
1045e76fa9ecSHeejin Ahn            .getTargetTriple()
1046e76fa9ecSHeejin Ahn            .isOSBinFormatELF())
104718c56a07SHeejin Ahn     appendEndToFunction(MF, TII);
104832807932SDan Gohman 
10491aaa481fSHeejin Ahn   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1050950a13cfSDan Gohman   return true;
1051950a13cfSDan Gohman }
1052