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 
24950a13cfSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
256bda14b3SChandler Carruth #include "WebAssembly.h"
26e76fa9ecSHeejin Ahn #include "WebAssemblyExceptionInfo.h"
27ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
28950a13cfSDan Gohman #include "WebAssemblySubtarget.h"
294fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
3032807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
31950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h"
32950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
33950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h"
349c3bf318SDerek Schuff #include "llvm/CodeGen/MachineRegisterInfo.h"
35950a13cfSDan Gohman #include "llvm/CodeGen/Passes.h"
36e76fa9ecSHeejin Ahn #include "llvm/CodeGen/WasmEHFuncInfo.h"
37e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h"
38950a13cfSDan Gohman #include "llvm/Support/Debug.h"
39950a13cfSDan Gohman #include "llvm/Support/raw_ostream.h"
40d6f48786SHeejin Ahn #include <cstring>
41950a13cfSDan Gohman using namespace llvm;
42950a13cfSDan Gohman 
43950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify"
44950a13cfSDan Gohman 
45950a13cfSDan Gohman namespace {
46950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass {
47117296c0SMehdi Amini   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
48950a13cfSDan Gohman 
49950a13cfSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
5032807932SDan Gohman     AU.addRequired<MachineDominatorTree>();
51950a13cfSDan Gohman     AU.addRequired<MachineLoopInfo>();
52e76fa9ecSHeejin Ahn     AU.addRequired<WebAssemblyExceptionInfo>();
53950a13cfSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
54950a13cfSDan Gohman   }
55950a13cfSDan Gohman 
56950a13cfSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
57950a13cfSDan Gohman 
58e76fa9ecSHeejin Ahn   // For each block whose label represents the end of a scope, record the block
59e76fa9ecSHeejin Ahn   // which holds the beginning of the scope. This will allow us to quickly skip
60e76fa9ecSHeejin Ahn   // over scoped regions when walking blocks.
61e76fa9ecSHeejin Ahn   SmallVector<MachineBasicBlock *, 8> ScopeTops;
62e76fa9ecSHeejin Ahn 
63e76fa9ecSHeejin Ahn   void placeMarkers(MachineFunction &MF);
64e76fa9ecSHeejin Ahn   void placeBlockMarker(MachineBasicBlock &MBB);
65e76fa9ecSHeejin Ahn   void placeLoopMarker(MachineBasicBlock &MBB);
66e76fa9ecSHeejin Ahn   void placeTryMarker(MachineBasicBlock &MBB);
67*cf699b45SHeejin Ahn   void removeUnnecessaryInstrs(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 
80*cf699b45SHeejin Ahn   // Helper functions to register / unregister scope information created by
81*cf699b45SHeejin Ahn   // marker instructions.
82e76fa9ecSHeejin Ahn   void registerScope(MachineInstr *Begin, MachineInstr *End);
83e76fa9ecSHeejin Ahn   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
84e76fa9ecSHeejin Ahn                         MachineBasicBlock *EHPad);
85*cf699b45SHeejin Ahn   void unregisterScope(MachineInstr *Begin);
86e76fa9ecSHeejin Ahn 
87950a13cfSDan Gohman public:
88950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
89950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
90e76fa9ecSHeejin Ahn   ~WebAssemblyCFGStackify() override { releaseMemory(); }
91e76fa9ecSHeejin Ahn   void releaseMemory() override;
92950a13cfSDan Gohman };
93950a13cfSDan Gohman } // end anonymous namespace
94950a13cfSDan Gohman 
95950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
9640926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
97f208f631SHeejin Ahn                 "Insert BLOCK and LOOP markers for WebAssembly scopes", false,
98f208f631SHeejin Ahn                 false)
9940926451SJacob Gravelle 
100950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
101950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
102950a13cfSDan Gohman }
103950a13cfSDan Gohman 
104b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
105b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
106b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
107b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
108b3aa1ecaSDan Gohman /// explicit mentions.
10918c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
11035e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
111b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
112b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
113b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
114b3aa1ecaSDan Gohman         return true;
115b3aa1ecaSDan Gohman   return false;
116b3aa1ecaSDan Gohman }
117b3aa1ecaSDan Gohman 
118e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB,
119e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
120e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
121e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only
122e76fa9ecSHeejin Ahn // used for sanity checking.
123e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
12418c56a07SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB,
125e76fa9ecSHeejin Ahn                      const SmallPtrSet<const MachineInstr *, 4> &BeforeSet,
126e76fa9ecSHeejin Ahn                      const SmallPtrSet<const MachineInstr *, 4> &AfterSet) {
127e76fa9ecSHeejin Ahn   auto InsertPos = MBB->end();
128e76fa9ecSHeejin Ahn   while (InsertPos != MBB->begin()) {
129e76fa9ecSHeejin Ahn     if (BeforeSet.count(&*std::prev(InsertPos))) {
130e76fa9ecSHeejin Ahn #ifndef NDEBUG
131e76fa9ecSHeejin Ahn       // Sanity check
132e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
133e76fa9ecSHeejin Ahn         assert(!AfterSet.count(&*std::prev(Pos)));
134e76fa9ecSHeejin Ahn #endif
135e76fa9ecSHeejin Ahn       break;
136e76fa9ecSHeejin Ahn     }
137e76fa9ecSHeejin Ahn     --InsertPos;
138e76fa9ecSHeejin Ahn   }
139e76fa9ecSHeejin Ahn   return InsertPos;
140e76fa9ecSHeejin Ahn }
141e76fa9ecSHeejin Ahn 
142e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB,
143e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
144e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
145e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only
146e76fa9ecSHeejin Ahn // used for sanity checking.
147e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
14818c56a07SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB,
149e76fa9ecSHeejin Ahn                    const SmallPtrSet<const MachineInstr *, 4> &BeforeSet,
150e76fa9ecSHeejin Ahn                    const SmallPtrSet<const MachineInstr *, 4> &AfterSet) {
151e76fa9ecSHeejin Ahn   auto InsertPos = MBB->begin();
152e76fa9ecSHeejin Ahn   while (InsertPos != MBB->end()) {
153e76fa9ecSHeejin Ahn     if (AfterSet.count(&*InsertPos)) {
154e76fa9ecSHeejin Ahn #ifndef NDEBUG
155e76fa9ecSHeejin Ahn       // Sanity check
156e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
157e76fa9ecSHeejin Ahn         assert(!BeforeSet.count(&*Pos));
158e76fa9ecSHeejin Ahn #endif
159e76fa9ecSHeejin Ahn       break;
160e76fa9ecSHeejin Ahn     }
161e76fa9ecSHeejin Ahn     ++InsertPos;
162e76fa9ecSHeejin Ahn   }
163e76fa9ecSHeejin Ahn   return InsertPos;
164e76fa9ecSHeejin Ahn }
165e76fa9ecSHeejin Ahn 
166e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
167e76fa9ecSHeejin Ahn                                            MachineInstr *End) {
168e76fa9ecSHeejin Ahn   BeginToEnd[Begin] = End;
169e76fa9ecSHeejin Ahn   EndToBegin[End] = Begin;
170e76fa9ecSHeejin Ahn }
171e76fa9ecSHeejin Ahn 
172e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
173e76fa9ecSHeejin Ahn                                               MachineInstr *End,
174e76fa9ecSHeejin Ahn                                               MachineBasicBlock *EHPad) {
175e76fa9ecSHeejin Ahn   registerScope(Begin, End);
176e76fa9ecSHeejin Ahn   TryToEHPad[Begin] = EHPad;
177e76fa9ecSHeejin Ahn   EHPadToTry[EHPad] = Begin;
178e76fa9ecSHeejin Ahn }
179e76fa9ecSHeejin Ahn 
180*cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
181*cf699b45SHeejin Ahn   assert(BeginToEnd.count(Begin));
182*cf699b45SHeejin Ahn   MachineInstr *End = BeginToEnd[Begin];
183*cf699b45SHeejin Ahn   assert(EndToBegin.count(End));
184*cf699b45SHeejin Ahn   BeginToEnd.erase(Begin);
185*cf699b45SHeejin Ahn   EndToBegin.erase(End);
186*cf699b45SHeejin Ahn   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
187*cf699b45SHeejin Ahn   if (EHPad) {
188*cf699b45SHeejin Ahn     assert(EHPadToTry.count(EHPad));
189*cf699b45SHeejin Ahn     TryToEHPad.erase(Begin);
190*cf699b45SHeejin Ahn     EHPadToTry.erase(EHPad);
191*cf699b45SHeejin Ahn   }
192*cf699b45SHeejin Ahn }
193*cf699b45SHeejin Ahn 
19432807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
195e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
196e76fa9ecSHeejin Ahn   // This should have been handled in placeTryMarker.
197e76fa9ecSHeejin Ahn   if (MBB.isEHPad())
198e76fa9ecSHeejin Ahn     return;
199e76fa9ecSHeejin Ahn 
200e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
201e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
202e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
203e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
204e76fa9ecSHeejin Ahn 
2058fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
2068fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
2078fe7e86bSDan Gohman   // which reduces overall stack height.
20832807932SDan Gohman   MachineBasicBlock *Header = nullptr;
20932807932SDan Gohman   bool IsBranchedTo = false;
210d6f48786SHeejin Ahn   bool IsBrOnExn = false;
211d6f48786SHeejin Ahn   MachineInstr *BrOnExn = nullptr;
21232807932SDan Gohman   int MBBNumber = MBB.getNumber();
213e76fa9ecSHeejin Ahn   for (MachineBasicBlock *Pred : MBB.predecessors()) {
21432807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
21532807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
21618c56a07SHeejin Ahn       if (explicitlyBranchesTo(Pred, &MBB)) {
21732807932SDan Gohman         IsBranchedTo = true;
218d6f48786SHeejin Ahn         if (Pred->getFirstTerminator()->getOpcode() == WebAssembly::BR_ON_EXN) {
219d6f48786SHeejin Ahn           IsBrOnExn = true;
220d6f48786SHeejin Ahn           assert(!BrOnExn && "There should be only one br_on_exn per block");
221d6f48786SHeejin Ahn           BrOnExn = &*Pred->getFirstTerminator();
222d6f48786SHeejin Ahn         }
223d6f48786SHeejin Ahn       }
22432807932SDan Gohman     }
225e76fa9ecSHeejin Ahn   }
22632807932SDan Gohman   if (!Header)
22732807932SDan Gohman     return;
22832807932SDan Gohman   if (!IsBranchedTo)
22932807932SDan Gohman     return;
23032807932SDan Gohman 
2318fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
232ef0a45aaSBenjamin Kramer   MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB));
2338fe7e86bSDan Gohman 
2348fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
2358fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
2368fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
2378fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
2388fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
2398fe7e86bSDan Gohman         // Skip over an intervening scope.
240ef0a45aaSBenjamin Kramer         I = std::next(MachineFunction::iterator(ScopeTop));
2418fe7e86bSDan Gohman       } else {
2428fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
2438fe7e86bSDan Gohman         Header = ScopeTop;
2448fe7e86bSDan Gohman         break;
2458fe7e86bSDan Gohman       }
2468fe7e86bSDan Gohman     }
2478fe7e86bSDan Gohman   }
2488fe7e86bSDan Gohman 
2498fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
250e76fa9ecSHeejin Ahn 
251e76fa9ecSHeejin Ahn   // Instructions that should go before the BLOCK.
252e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
253e76fa9ecSHeejin Ahn   // Instructions that should go after the BLOCK.
254e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
255e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
256e76fa9ecSHeejin Ahn     // If there is a previously placed LOOP/TRY marker and the bottom block of
257e76fa9ecSHeejin Ahn     // the loop/exception is above MBB, it should be after the BLOCK, because
258e76fa9ecSHeejin Ahn     // the loop/exception is nested in this block. Otherwise it should be before
259e76fa9ecSHeejin Ahn     // the BLOCK.
260e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
261e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY) {
26285631d8bSHeejin Ahn       auto *BottomBB =
26385631d8bSHeejin Ahn           &*std::prev(MachineFunction::iterator(BeginToEnd[&MI]->getParent()));
26485631d8bSHeejin Ahn       if (MBB.getNumber() > BottomBB->getNumber())
265e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
266e76fa9ecSHeejin Ahn #ifndef NDEBUG
267e76fa9ecSHeejin Ahn       else
268e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
269e76fa9ecSHeejin Ahn #endif
270e76fa9ecSHeejin Ahn     }
271e76fa9ecSHeejin Ahn 
272e76fa9ecSHeejin Ahn     // All previously inserted BLOCK markers should be after the BLOCK because
273e76fa9ecSHeejin Ahn     // they are all nested blocks.
274e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK)
275e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
276e76fa9ecSHeejin Ahn 
277e76fa9ecSHeejin Ahn #ifndef NDEBUG
278e76fa9ecSHeejin Ahn     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
279e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
280e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
281e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
282e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
283e76fa9ecSHeejin Ahn #endif
284e76fa9ecSHeejin Ahn 
285e76fa9ecSHeejin Ahn     // Terminators should go after the BLOCK.
286e76fa9ecSHeejin Ahn     if (MI.isTerminator())
287e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
288e76fa9ecSHeejin Ahn   }
289e76fa9ecSHeejin Ahn 
290e76fa9ecSHeejin Ahn   // Local expression tree should go after the BLOCK.
291e76fa9ecSHeejin Ahn   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
292e76fa9ecSHeejin Ahn        --I) {
293409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
294409b4391SYury Delendik       continue;
295e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
296e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
297e76fa9ecSHeejin Ahn     else
298e76fa9ecSHeejin Ahn       break;
29932807932SDan Gohman   }
30032807932SDan Gohman 
3018fe7e86bSDan Gohman   // Add the BLOCK.
302d6f48786SHeejin Ahn 
303d6f48786SHeejin Ahn   // 'br_on_exn' extracts except_ref object and pushes variable number of values
304d6f48786SHeejin Ahn   // depending on its tag. For C++ exception, its a single i32 value, and the
305d6f48786SHeejin Ahn   // generated code will be in the form of:
306d6f48786SHeejin Ahn   // block i32
307d6f48786SHeejin Ahn   //   br_on_exn 0, $__cpp_exception
308d6f48786SHeejin Ahn   //   rethrow
309d6f48786SHeejin Ahn   // end_block
310d6f48786SHeejin Ahn   WebAssembly::ExprType ReturnType = WebAssembly::ExprType::Void;
311d6f48786SHeejin Ahn   if (IsBrOnExn) {
312d6f48786SHeejin Ahn     const char *TagName = BrOnExn->getOperand(1).getSymbolName();
313d6f48786SHeejin Ahn     if (std::strcmp(TagName, "__cpp_exception") != 0)
314d6f48786SHeejin Ahn       llvm_unreachable("Only C++ exception is supported");
315d6f48786SHeejin Ahn     ReturnType = WebAssembly::ExprType::I32;
316d6f48786SHeejin Ahn   }
317d6f48786SHeejin Ahn 
31818c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
31992401cc1SHeejin Ahn   MachineInstr *Begin =
32092401cc1SHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
3212726b88cSDan Gohman               TII.get(WebAssembly::BLOCK))
322d6f48786SHeejin Ahn           .addImm(int64_t(ReturnType));
3231d68e80fSDan Gohman 
324e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_BLOCK.
325e76fa9ecSHeejin Ahn   BeforeSet.clear();
326e76fa9ecSHeejin Ahn   AfterSet.clear();
327e76fa9ecSHeejin Ahn   for (auto &MI : MBB) {
328e76fa9ecSHeejin Ahn #ifndef NDEBUG
329e76fa9ecSHeejin Ahn     // END_BLOCK should precede existing LOOP and TRY markers.
330e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
331e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
332e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
333e76fa9ecSHeejin Ahn #endif
334e76fa9ecSHeejin Ahn 
335e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and the header of the
336e76fa9ecSHeejin Ahn     // loop is above this block's header, the END_LOOP should be placed after
337e76fa9ecSHeejin Ahn     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
338e76fa9ecSHeejin Ahn     // should be placed before the BLOCK. The same for END_TRY.
339e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP ||
340e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY) {
341e76fa9ecSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
342e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
343e76fa9ecSHeejin Ahn #ifndef NDEBUG
344e76fa9ecSHeejin Ahn       else
345e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
346e76fa9ecSHeejin Ahn #endif
347e76fa9ecSHeejin Ahn     }
348e76fa9ecSHeejin Ahn   }
349e76fa9ecSHeejin Ahn 
3501d68e80fSDan Gohman   // Mark the end of the block.
35118c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
35210b31358SDerek Schuff   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
3532726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
354e76fa9ecSHeejin Ahn   registerScope(Begin, End);
3558fe7e86bSDan Gohman 
3568fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
3578fe7e86bSDan Gohman   int Number = MBB.getNumber();
3588fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
3598fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
3608fe7e86bSDan Gohman     ScopeTops[Number] = Header;
361950a13cfSDan Gohman }
362950a13cfSDan Gohman 
3638fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
364e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
365e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
366e76fa9ecSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
367e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
368e76fa9ecSHeejin Ahn 
3698fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
3708fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
3718fe7e86bSDan Gohman     return;
3728fe7e86bSDan Gohman 
3738fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
3748fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
375817811caSHeejin Ahn   MachineBasicBlock *Bottom = WebAssembly::getBottom(Loop);
376ef0a45aaSBenjamin Kramer   auto Iter = std::next(MachineFunction::iterator(Bottom));
377e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
378f6857223SDan Gohman     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
379f6857223SDan Gohman     // Give it a fake predecessor so that AsmPrinter prints its label.
380f6857223SDan Gohman     Label->addSuccessor(Label);
381f6857223SDan Gohman     MF.push_back(Label);
382ef0a45aaSBenjamin Kramer     Iter = std::next(MachineFunction::iterator(Bottom));
383e3e4a5ffSDan Gohman   }
3848fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
385f6857223SDan Gohman 
386e76fa9ecSHeejin Ahn   // Decide where in Header to put the LOOP.
387e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
388e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
389e76fa9ecSHeejin Ahn   for (const auto &MI : MBB) {
390e76fa9ecSHeejin Ahn     // LOOP marker should be after any existing loop that ends here. Otherwise
391e76fa9ecSHeejin Ahn     // we assume the instruction belongs to the loop.
392e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
393e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
394e76fa9ecSHeejin Ahn #ifndef NDEBUG
395e76fa9ecSHeejin Ahn     else
396e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
397e76fa9ecSHeejin Ahn #endif
398e76fa9ecSHeejin Ahn   }
399e76fa9ecSHeejin Ahn 
400e76fa9ecSHeejin Ahn   // Mark the beginning of the loop.
40118c56a07SHeejin Ahn   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
40210b31358SDerek Schuff   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
4032726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
4044fc4e42dSDan Gohman                             .addImm(int64_t(WebAssembly::ExprType::Void));
4051d68e80fSDan Gohman 
406e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_LOOP.
407e76fa9ecSHeejin Ahn   BeforeSet.clear();
408e76fa9ecSHeejin Ahn   AfterSet.clear();
409e76fa9ecSHeejin Ahn #ifndef NDEBUG
410e76fa9ecSHeejin Ahn   for (const auto &MI : MBB)
411e76fa9ecSHeejin Ahn     // Existing END_LOOP markers belong to parent loops of this loop
412e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
413e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
414e76fa9ecSHeejin Ahn #endif
415e76fa9ecSHeejin Ahn 
416e76fa9ecSHeejin Ahn   // Mark the end of the loop (using arbitrary debug location that branched to
417e76fa9ecSHeejin Ahn   // the loop end as its location).
41818c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
41910b31358SDerek Schuff   DebugLoc EndDL = (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
420e76fa9ecSHeejin Ahn   MachineInstr *End =
421e76fa9ecSHeejin Ahn       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
422e76fa9ecSHeejin Ahn   registerScope(Begin, End);
4238fe7e86bSDan Gohman 
4248fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4258fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
426442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
4278fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
4288fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
429e3e4a5ffSDan Gohman }
430950a13cfSDan Gohman 
431e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
432e76fa9ecSHeejin Ahn   if (!MBB.isEHPad())
433e76fa9ecSHeejin Ahn     return;
434e76fa9ecSHeejin Ahn 
435e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
436e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
437e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
438e76fa9ecSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
439e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
440e76fa9ecSHeejin Ahn 
441e76fa9ecSHeejin Ahn   // Compute the nearest common dominator of all unwind predecessors
442e76fa9ecSHeejin Ahn   MachineBasicBlock *Header = nullptr;
443e76fa9ecSHeejin Ahn   int MBBNumber = MBB.getNumber();
444e76fa9ecSHeejin Ahn   for (auto *Pred : MBB.predecessors()) {
445e76fa9ecSHeejin Ahn     if (Pred->getNumber() < MBBNumber) {
446e76fa9ecSHeejin Ahn       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
44718c56a07SHeejin Ahn       assert(!explicitlyBranchesTo(Pred, &MBB) &&
448e76fa9ecSHeejin Ahn              "Explicit branch to an EH pad!");
449e76fa9ecSHeejin Ahn     }
450e76fa9ecSHeejin Ahn   }
451e76fa9ecSHeejin Ahn   if (!Header)
452e76fa9ecSHeejin Ahn     return;
453e76fa9ecSHeejin Ahn 
454e76fa9ecSHeejin Ahn   // If this try is at the bottom of the function, insert a dummy block at the
455e76fa9ecSHeejin Ahn   // end.
456e76fa9ecSHeejin Ahn   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
457e76fa9ecSHeejin Ahn   assert(WE);
458e76fa9ecSHeejin Ahn   MachineBasicBlock *Bottom = WebAssembly::getBottom(WE);
459e76fa9ecSHeejin Ahn 
460e76fa9ecSHeejin Ahn   auto Iter = std::next(MachineFunction::iterator(Bottom));
461e76fa9ecSHeejin Ahn   if (Iter == MF.end()) {
462e76fa9ecSHeejin Ahn     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
463e76fa9ecSHeejin Ahn     // Give it a fake predecessor so that AsmPrinter prints its label.
464e76fa9ecSHeejin Ahn     Label->addSuccessor(Label);
465e76fa9ecSHeejin Ahn     MF.push_back(Label);
466e76fa9ecSHeejin Ahn     Iter = std::next(MachineFunction::iterator(Bottom));
467e76fa9ecSHeejin Ahn   }
46820cf0749SHeejin Ahn   MachineBasicBlock *Cont = &*Iter;
469e76fa9ecSHeejin Ahn 
47020cf0749SHeejin Ahn   assert(Cont != &MF.front());
471e76fa9ecSHeejin Ahn   MachineBasicBlock *LayoutPred =
47220cf0749SHeejin Ahn       &*std::prev(MachineFunction::iterator(Cont));
473e76fa9ecSHeejin Ahn 
474e76fa9ecSHeejin Ahn   // If the nearest common dominator is inside a more deeply nested context,
475e76fa9ecSHeejin Ahn   // walk out to the nearest scope which isn't more deeply nested.
476e76fa9ecSHeejin Ahn   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
477e76fa9ecSHeejin Ahn     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
478e76fa9ecSHeejin Ahn       if (ScopeTop->getNumber() > Header->getNumber()) {
479e76fa9ecSHeejin Ahn         // Skip over an intervening scope.
480e76fa9ecSHeejin Ahn         I = std::next(MachineFunction::iterator(ScopeTop));
481e76fa9ecSHeejin Ahn       } else {
482e76fa9ecSHeejin Ahn         // We found a scope level at an appropriate depth.
483e76fa9ecSHeejin Ahn         Header = ScopeTop;
484e76fa9ecSHeejin Ahn         break;
485e76fa9ecSHeejin Ahn       }
486e76fa9ecSHeejin Ahn     }
487e76fa9ecSHeejin Ahn   }
488e76fa9ecSHeejin Ahn 
489e76fa9ecSHeejin Ahn   // Decide where in Header to put the TRY.
490e76fa9ecSHeejin Ahn 
491e76fa9ecSHeejin Ahn   // Instructions that should go before the BLOCK.
492e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
493e76fa9ecSHeejin Ahn   // Instructions that should go after the BLOCK.
494e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
495e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
496e76fa9ecSHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of
497e76fa9ecSHeejin Ahn     // the loop is above MBB, the LOOP should be after the TRY, because the
498e76fa9ecSHeejin Ahn     // loop is nested in this try. Otherwise it should be before the TRY.
499e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
500e76fa9ecSHeejin Ahn       if (MBB.getNumber() > Bottom->getNumber())
501e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
502e76fa9ecSHeejin Ahn #ifndef NDEBUG
503e76fa9ecSHeejin Ahn       else
504e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
505e76fa9ecSHeejin Ahn #endif
506e76fa9ecSHeejin Ahn     }
507e76fa9ecSHeejin Ahn 
508e76fa9ecSHeejin Ahn     // All previously inserted TRY markers should be after the TRY because they
509e76fa9ecSHeejin Ahn     // are all nested trys.
510e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::TRY)
511e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
512e76fa9ecSHeejin Ahn 
513e76fa9ecSHeejin Ahn #ifndef NDEBUG
514e76fa9ecSHeejin Ahn     // All END_(LOOP/TRY) markers should be before the TRY.
515e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP ||
516e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
517e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
518e76fa9ecSHeejin Ahn #endif
519e76fa9ecSHeejin Ahn 
520e76fa9ecSHeejin Ahn     // Terminators should go after the TRY.
521e76fa9ecSHeejin Ahn     if (MI.isTerminator())
522e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
523e76fa9ecSHeejin Ahn   }
524e76fa9ecSHeejin Ahn 
525e76fa9ecSHeejin Ahn   // Local expression tree should go after the TRY.
526e76fa9ecSHeejin Ahn   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
527e76fa9ecSHeejin Ahn        --I) {
528409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
529409b4391SYury Delendik       continue;
530e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
531e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
532e76fa9ecSHeejin Ahn     else
533e76fa9ecSHeejin Ahn       break;
534e76fa9ecSHeejin Ahn   }
535e76fa9ecSHeejin Ahn 
536e76fa9ecSHeejin Ahn   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
537e76fa9ecSHeejin Ahn   // contain the call within it. So the call should go after the TRY. The
538e76fa9ecSHeejin Ahn   // exception is when the header's terminator is a rethrow instruction, in
539e76fa9ecSHeejin Ahn   // which case that instruction, not a call instruction before it, is gonna
540e76fa9ecSHeejin Ahn   // throw.
541e76fa9ecSHeejin Ahn   if (MBB.isPredecessor(Header)) {
542e76fa9ecSHeejin Ahn     auto TermPos = Header->getFirstTerminator();
543d6f48786SHeejin Ahn     if (TermPos == Header->end() ||
544d6f48786SHeejin Ahn         TermPos->getOpcode() != WebAssembly::RETHROW) {
545e76fa9ecSHeejin Ahn       for (const auto &MI : reverse(*Header)) {
546e76fa9ecSHeejin Ahn         if (MI.isCall()) {
547e76fa9ecSHeejin Ahn           AfterSet.insert(&MI);
548e76fa9ecSHeejin Ahn           break;
549e76fa9ecSHeejin Ahn         }
550e76fa9ecSHeejin Ahn       }
551e76fa9ecSHeejin Ahn     }
552e76fa9ecSHeejin Ahn   }
553e76fa9ecSHeejin Ahn 
554e76fa9ecSHeejin Ahn   // Add the TRY.
55518c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
556e76fa9ecSHeejin Ahn   MachineInstr *Begin =
557e76fa9ecSHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
558e76fa9ecSHeejin Ahn               TII.get(WebAssembly::TRY))
559e76fa9ecSHeejin Ahn           .addImm(int64_t(WebAssembly::ExprType::Void));
560e76fa9ecSHeejin Ahn 
561e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_TRY.
562e76fa9ecSHeejin Ahn   BeforeSet.clear();
563e76fa9ecSHeejin Ahn   AfterSet.clear();
56420cf0749SHeejin Ahn   for (const auto &MI : *Cont) {
565e76fa9ecSHeejin Ahn #ifndef NDEBUG
566e76fa9ecSHeejin Ahn     // END_TRY should precede existing LOOP markers.
567e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP)
568e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
569e76fa9ecSHeejin Ahn 
570e76fa9ecSHeejin Ahn     // All END_TRY markers placed earlier belong to exceptions that contains
571e76fa9ecSHeejin Ahn     // this one.
572e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_TRY)
573e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
574e76fa9ecSHeejin Ahn #endif
575e76fa9ecSHeejin Ahn 
576e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and its header is after
577e76fa9ecSHeejin Ahn     // where TRY marker is, this loop is contained within the 'catch' part, so
578e76fa9ecSHeejin Ahn     // the END_TRY marker should go after that. Otherwise, the whole try-catch
579e76fa9ecSHeejin Ahn     // is contained within this loop, so the END_TRY should go before that.
580e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP) {
581e76fa9ecSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
582e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
583e76fa9ecSHeejin Ahn #ifndef NDEBUG
584e76fa9ecSHeejin Ahn       else
585e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
586e76fa9ecSHeejin Ahn #endif
587e76fa9ecSHeejin Ahn     }
588e76fa9ecSHeejin Ahn   }
589e76fa9ecSHeejin Ahn 
590e76fa9ecSHeejin Ahn   // Mark the end of the TRY.
59120cf0749SHeejin Ahn   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
592e76fa9ecSHeejin Ahn   MachineInstr *End =
59320cf0749SHeejin Ahn       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
594e76fa9ecSHeejin Ahn               TII.get(WebAssembly::END_TRY));
595e76fa9ecSHeejin Ahn   registerTryScope(Begin, End, &MBB);
596e76fa9ecSHeejin Ahn 
597e76fa9ecSHeejin Ahn   // Track the farthest-spanning scope that ends at this point.
59820cf0749SHeejin Ahn   int Number = Cont->getNumber();
599e76fa9ecSHeejin Ahn   if (!ScopeTops[Number] ||
600e76fa9ecSHeejin Ahn       ScopeTops[Number]->getNumber() > Header->getNumber())
601e76fa9ecSHeejin Ahn     ScopeTops[Number] = Header;
602e76fa9ecSHeejin Ahn }
603e76fa9ecSHeejin Ahn 
604*cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
605*cf699b45SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
606*cf699b45SHeejin Ahn 
607*cf699b45SHeejin Ahn   // When there is an unconditional branch right before a catch instruction and
608*cf699b45SHeejin Ahn   // it branches to the end of end_try marker, we don't need the branch, because
609*cf699b45SHeejin Ahn   // it there is no exception, the control flow transfers to that point anyway.
610*cf699b45SHeejin Ahn   // bb0:
611*cf699b45SHeejin Ahn   //   try
612*cf699b45SHeejin Ahn   //     ...
613*cf699b45SHeejin Ahn   //     br bb2      <- Not necessary
614*cf699b45SHeejin Ahn   // bb1:
615*cf699b45SHeejin Ahn   //   catch
616*cf699b45SHeejin Ahn   //     ...
617*cf699b45SHeejin Ahn   // bb2:
618*cf699b45SHeejin Ahn   //   end
619*cf699b45SHeejin Ahn   for (auto &MBB : MF) {
620*cf699b45SHeejin Ahn     if (!MBB.isEHPad())
621*cf699b45SHeejin Ahn       continue;
622*cf699b45SHeejin Ahn 
623*cf699b45SHeejin Ahn     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
624*cf699b45SHeejin Ahn     SmallVector<MachineOperand, 4> Cond;
625*cf699b45SHeejin Ahn     MachineBasicBlock *EHPadLayoutPred =
626*cf699b45SHeejin Ahn         &*std::prev(MachineFunction::iterator(&MBB));
627*cf699b45SHeejin Ahn     MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent();
628*cf699b45SHeejin Ahn     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
629*cf699b45SHeejin Ahn     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
630*cf699b45SHeejin Ahn                        (!Cond.empty() && FBB && FBB == Cont)))
631*cf699b45SHeejin Ahn       TII.removeBranch(*EHPadLayoutPred);
632*cf699b45SHeejin Ahn   }
633*cf699b45SHeejin Ahn 
634*cf699b45SHeejin Ahn   // When there are block / end_block markers that overlap with try / end_try
635*cf699b45SHeejin Ahn   // markers, and the block and try markers' return types are the same, the
636*cf699b45SHeejin Ahn   // block /end_block markers are not necessary, because try / end_try markers
637*cf699b45SHeejin Ahn   // also can serve as boundaries for branches.
638*cf699b45SHeejin Ahn   // block         <- Not necessary
639*cf699b45SHeejin Ahn   //   try
640*cf699b45SHeejin Ahn   //     ...
641*cf699b45SHeejin Ahn   //   catch
642*cf699b45SHeejin Ahn   //     ...
643*cf699b45SHeejin Ahn   //   end
644*cf699b45SHeejin Ahn   // end           <- Not necessary
645*cf699b45SHeejin Ahn   SmallVector<MachineInstr *, 32> ToDelete;
646*cf699b45SHeejin Ahn   for (auto &MBB : MF) {
647*cf699b45SHeejin Ahn     for (auto &MI : MBB) {
648*cf699b45SHeejin Ahn       if (MI.getOpcode() != WebAssembly::TRY)
649*cf699b45SHeejin Ahn         continue;
650*cf699b45SHeejin Ahn 
651*cf699b45SHeejin Ahn       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
652*cf699b45SHeejin Ahn       MachineBasicBlock *TryBB = Try->getParent();
653*cf699b45SHeejin Ahn       MachineBasicBlock *Cont = EndTry->getParent();
654*cf699b45SHeejin Ahn       int64_t RetType = Try->getOperand(0).getImm();
655*cf699b45SHeejin Ahn       for (auto B = MachineBasicBlock::iterator(Try),
656*cf699b45SHeejin Ahn                 E = std::next(MachineBasicBlock::iterator(EndTry));
657*cf699b45SHeejin Ahn            B != TryBB->begin() && E != Cont->end() &&
658*cf699b45SHeejin Ahn            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
659*cf699b45SHeejin Ahn            E->getOpcode() == WebAssembly::END_BLOCK &&
660*cf699b45SHeejin Ahn            std::prev(B)->getOperand(0).getImm() == RetType;
661*cf699b45SHeejin Ahn            --B, ++E) {
662*cf699b45SHeejin Ahn         ToDelete.push_back(&*std::prev(B));
663*cf699b45SHeejin Ahn         ToDelete.push_back(&*E);
664*cf699b45SHeejin Ahn       }
665*cf699b45SHeejin Ahn     }
666*cf699b45SHeejin Ahn   }
667*cf699b45SHeejin Ahn   for (auto *MI : ToDelete) {
668*cf699b45SHeejin Ahn     if (MI->getOpcode() == WebAssembly::BLOCK)
669*cf699b45SHeejin Ahn       unregisterScope(MI);
670*cf699b45SHeejin Ahn     MI->eraseFromParent();
671*cf699b45SHeejin Ahn   }
672*cf699b45SHeejin Ahn }
673*cf699b45SHeejin Ahn 
6741d68e80fSDan Gohman static unsigned
67518c56a07SHeejin Ahn getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
6761d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
6771d68e80fSDan Gohman   unsigned Depth = 0;
6781d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
6791d68e80fSDan Gohman     if (X == MBB)
6801d68e80fSDan Gohman       break;
6811d68e80fSDan Gohman     ++Depth;
6821d68e80fSDan Gohman   }
6831d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
6841d68e80fSDan Gohman   return Depth;
6851d68e80fSDan Gohman }
6861d68e80fSDan Gohman 
6872726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
6882726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
6892726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
6902726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
6912726b88cSDan Gohman /// that end at the function end need to have a return type signature that
6922726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
6932726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
694e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
695e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
6962726b88cSDan Gohman   assert(MFI.getResults().size() <= 1);
6972726b88cSDan Gohman 
6982726b88cSDan Gohman   if (MFI.getResults().empty())
6992726b88cSDan Gohman     return;
7002726b88cSDan Gohman 
70118c56a07SHeejin Ahn   WebAssembly::ExprType RetType;
7022726b88cSDan Gohman   switch (MFI.getResults().front().SimpleTy) {
703f208f631SHeejin Ahn   case MVT::i32:
70418c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::I32;
705f208f631SHeejin Ahn     break;
706f208f631SHeejin Ahn   case MVT::i64:
70718c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::I64;
708f208f631SHeejin Ahn     break;
709f208f631SHeejin Ahn   case MVT::f32:
71018c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::F32;
711f208f631SHeejin Ahn     break;
712f208f631SHeejin Ahn   case MVT::f64:
71318c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::F64;
714f208f631SHeejin Ahn     break;
7152c783859SDerek Schuff   case MVT::v16i8:
7162c783859SDerek Schuff   case MVT::v8i16:
7172c783859SDerek Schuff   case MVT::v4i32:
71851ed131eSDerek Schuff   case MVT::v2i64:
7192c783859SDerek Schuff   case MVT::v4f32:
72051ed131eSDerek Schuff   case MVT::v2f64:
72118c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::V128;
7222c783859SDerek Schuff     break;
723f208f631SHeejin Ahn   case MVT::ExceptRef:
72418c56a07SHeejin Ahn     RetType = WebAssembly::ExprType::ExceptRef;
725f208f631SHeejin Ahn     break;
726f208f631SHeejin Ahn   default:
727f208f631SHeejin Ahn     llvm_unreachable("unexpected return type");
7282726b88cSDan Gohman   }
7292726b88cSDan Gohman 
7302726b88cSDan Gohman   for (MachineBasicBlock &MBB : reverse(MF)) {
7312726b88cSDan Gohman     for (MachineInstr &MI : reverse(MBB)) {
732801bf7ebSShiva Chen       if (MI.isPosition() || MI.isDebugInstr())
7332726b88cSDan Gohman         continue;
7342726b88cSDan Gohman       if (MI.getOpcode() == WebAssembly::END_BLOCK) {
73518c56a07SHeejin Ahn         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
7362726b88cSDan Gohman         continue;
7372726b88cSDan Gohman       }
7382726b88cSDan Gohman       if (MI.getOpcode() == WebAssembly::END_LOOP) {
73918c56a07SHeejin Ahn         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
7402726b88cSDan Gohman         continue;
7412726b88cSDan Gohman       }
7422726b88cSDan Gohman       // Something other than an `end`. We're done.
7432726b88cSDan Gohman       return;
7442726b88cSDan Gohman     }
7452726b88cSDan Gohman   }
7462726b88cSDan Gohman }
7472726b88cSDan Gohman 
748d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
749d934cb88SDan Gohman // were a block.
75018c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF,
751d934cb88SDan Gohman                                 const WebAssemblyInstrInfo &TII) {
75210b31358SDerek Schuff   BuildMI(MF.back(), MF.back().end(),
75310b31358SDerek Schuff           MF.back().findPrevDebugLoc(MF.back().end()),
754d934cb88SDan Gohman           TII.get(WebAssembly::END_FUNCTION));
755d934cb88SDan Gohman }
756d934cb88SDan Gohman 
757e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places.
758e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
759e76fa9ecSHeejin Ahn   // We allocate one more than the number of blocks in the function to
760e76fa9ecSHeejin Ahn   // accommodate for the possible fake block we may insert at the end.
761e76fa9ecSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs() + 1);
7628fe7e86bSDan Gohman   // Place the LOOP for MBB if MBB is the header of a loop.
763e76fa9ecSHeejin Ahn   for (auto &MBB : MF)
764e76fa9ecSHeejin Ahn     placeLoopMarker(MBB);
765e76fa9ecSHeejin Ahn   // Place the TRY for MBB if MBB is the EH pad of an exception.
766d6f48786SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
767e76fa9ecSHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
768e76fa9ecSHeejin Ahn       MF.getFunction().hasPersonalityFn())
769e76fa9ecSHeejin Ahn     for (auto &MBB : MF)
770e76fa9ecSHeejin Ahn       placeTryMarker(MBB);
77132807932SDan Gohman   // Place the BLOCK for MBB if MBB is branched to from above.
772e76fa9ecSHeejin Ahn   for (auto &MBB : MF)
773e76fa9ecSHeejin Ahn     placeBlockMarker(MBB);
774950a13cfSDan Gohman }
775950a13cfSDan Gohman 
776e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
7771d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
7781d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
7791d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
780e76fa9ecSHeejin Ahn     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) {
781e76fa9ecSHeejin Ahn       MachineInstr &MI = *I;
7821d68e80fSDan Gohman       switch (MI.getOpcode()) {
7831d68e80fSDan Gohman       case WebAssembly::BLOCK:
784e76fa9ecSHeejin Ahn       case WebAssembly::TRY:
785e76fa9ecSHeejin Ahn         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <=
786e76fa9ecSHeejin Ahn                    MBB.getNumber() &&
787e76fa9ecSHeejin Ahn                "Block/try marker should be balanced");
788e76fa9ecSHeejin Ahn         Stack.pop_back();
789e76fa9ecSHeejin Ahn         break;
790e76fa9ecSHeejin Ahn 
7911d68e80fSDan Gohman       case WebAssembly::LOOP:
7921d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
7931d68e80fSDan Gohman         Stack.pop_back();
7941d68e80fSDan Gohman         break;
795e76fa9ecSHeejin Ahn 
7961d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
797e76fa9ecSHeejin Ahn       case WebAssembly::END_TRY:
7981d68e80fSDan Gohman         Stack.push_back(&MBB);
7991d68e80fSDan Gohman         break;
800e76fa9ecSHeejin Ahn 
8011d68e80fSDan Gohman       case WebAssembly::END_LOOP:
802e76fa9ecSHeejin Ahn         Stack.push_back(EndToBegin[&MI]->getParent());
8031d68e80fSDan Gohman         break;
804e76fa9ecSHeejin Ahn 
8051d68e80fSDan Gohman       default:
8061d68e80fSDan Gohman         if (MI.isTerminator()) {
8071d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
8081d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
8091d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
8101d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
8111d68e80fSDan Gohman           for (auto MO : Ops) {
8121d68e80fSDan Gohman             if (MO.isMBB())
81318c56a07SHeejin Ahn               MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB()));
8141d68e80fSDan Gohman             MI.addOperand(MF, MO);
81532807932SDan Gohman           }
8161d68e80fSDan Gohman         }
8171d68e80fSDan Gohman         break;
8181d68e80fSDan Gohman       }
8191d68e80fSDan Gohman     }
8201d68e80fSDan Gohman   }
8211d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
822e76fa9ecSHeejin Ahn }
8232726b88cSDan Gohman 
824e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() {
825e76fa9ecSHeejin Ahn   ScopeTops.clear();
826e76fa9ecSHeejin Ahn   BeginToEnd.clear();
827e76fa9ecSHeejin Ahn   EndToBegin.clear();
828e76fa9ecSHeejin Ahn   TryToEHPad.clear();
829e76fa9ecSHeejin Ahn   EHPadToTry.clear();
8301d68e80fSDan Gohman }
83132807932SDan Gohman 
832950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
833d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
834950a13cfSDan Gohman                        "********** Function: "
835950a13cfSDan Gohman                     << MF.getName() << '\n');
836*cf699b45SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
837950a13cfSDan Gohman 
838e76fa9ecSHeejin Ahn   releaseMemory();
839e76fa9ecSHeejin Ahn 
840e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
8419c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
842950a13cfSDan Gohman 
843e76fa9ecSHeejin Ahn   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
844e76fa9ecSHeejin Ahn   placeMarkers(MF);
845e76fa9ecSHeejin Ahn 
846*cf699b45SHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
847*cf699b45SHeejin Ahn       MF.getFunction().hasPersonalityFn())
848*cf699b45SHeejin Ahn     // Remove unnecessary instructions.
849*cf699b45SHeejin Ahn     removeUnnecessaryInstrs(MF);
850*cf699b45SHeejin Ahn 
851e76fa9ecSHeejin Ahn   // Convert MBB operands in terminators to relative depth immediates.
852e76fa9ecSHeejin Ahn   rewriteDepthImmediates(MF);
853e76fa9ecSHeejin Ahn 
854e76fa9ecSHeejin Ahn   // Fix up block/loop/try signatures at the end of the function to conform to
855e76fa9ecSHeejin Ahn   // WebAssembly's rules.
856e76fa9ecSHeejin Ahn   fixEndsAtEndOfFunction(MF);
857e76fa9ecSHeejin Ahn 
858e76fa9ecSHeejin Ahn   // Add an end instruction at the end of the function body.
859e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
860e76fa9ecSHeejin Ahn   if (!MF.getSubtarget<WebAssemblySubtarget>()
861e76fa9ecSHeejin Ahn            .getTargetTriple()
862e76fa9ecSHeejin Ahn            .isOSBinFormatELF())
86318c56a07SHeejin Ahn     appendEndToFunction(MF, TII);
86432807932SDan Gohman 
865950a13cfSDan Gohman   return true;
866950a13cfSDan Gohman }
867