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"
34*9f770b36SHeejin Ahn #include "llvm/CodeGen/WasmEHFuncInfo.h"
35e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h"
36fe0006c8SSimon Pilgrim #include "llvm/Target/TargetMachine.h"
37950a13cfSDan Gohman using namespace llvm;
38276f9e8cSHeejin Ahn using WebAssembly::SortRegionInfo;
39950a13cfSDan Gohman 
40950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify"
41950a13cfSDan Gohman 
42ed41945fSHeejin Ahn STATISTIC(NumCallUnwindMismatches, "Number of call unwind mismatches found");
43*9f770b36SHeejin Ahn STATISTIC(NumCatchUnwindMismatches, "Number of catch unwind mismatches found");
44c4ac74fbSHeejin Ahn 
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;
621cc52357SHeejin Ahn   void updateScopeTops(MachineBasicBlock *Begin, MachineBasicBlock *End) {
631cc52357SHeejin Ahn     int EndNo = End->getNumber();
641cc52357SHeejin Ahn     if (!ScopeTops[EndNo] || ScopeTops[EndNo]->getNumber() > Begin->getNumber())
651cc52357SHeejin Ahn       ScopeTops[EndNo] = Begin;
661cc52357SHeejin Ahn   }
67e76fa9ecSHeejin Ahn 
68c4ac74fbSHeejin Ahn   // Placing markers.
69e76fa9ecSHeejin Ahn   void placeMarkers(MachineFunction &MF);
70e76fa9ecSHeejin Ahn   void placeBlockMarker(MachineBasicBlock &MBB);
71e76fa9ecSHeejin Ahn   void placeLoopMarker(MachineBasicBlock &MBB);
72e76fa9ecSHeejin Ahn   void placeTryMarker(MachineBasicBlock &MBB);
73ed41945fSHeejin Ahn 
74ed41945fSHeejin Ahn   // Exception handling related functions
75ed41945fSHeejin Ahn   bool fixCallUnwindMismatches(MachineFunction &MF);
76ed41945fSHeejin Ahn   bool fixCatchUnwindMismatches(MachineFunction &MF);
77ed41945fSHeejin Ahn   void addTryDelegate(MachineInstr *RangeBegin, MachineInstr *RangeEnd,
78ed41945fSHeejin Ahn                       MachineBasicBlock *DelegateDest);
79ed41945fSHeejin Ahn   void recalculateScopeTops(MachineFunction &MF);
80cf699b45SHeejin Ahn   void removeUnnecessaryInstrs(MachineFunction &MF);
81ed41945fSHeejin Ahn 
82ed41945fSHeejin Ahn   // Wrap-up
83ed41945fSHeejin Ahn   unsigned getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
84ed41945fSHeejin Ahn                     const MachineBasicBlock *MBB);
85e76fa9ecSHeejin Ahn   void rewriteDepthImmediates(MachineFunction &MF);
86e76fa9ecSHeejin Ahn   void fixEndsAtEndOfFunction(MachineFunction &MF);
87ed41945fSHeejin Ahn   void cleanupFunctionData(MachineFunction &MF);
88e76fa9ecSHeejin Ahn 
89ed41945fSHeejin Ahn   // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY) or DELEGATE
90ed41945fSHeejin Ahn   // (in case of TRY).
91e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
92ed41945fSHeejin Ahn   // For each END_(BLOCK|LOOP|TRY) or DELEGATE, the corresponding
93ed41945fSHeejin Ahn   // BLOCK|LOOP|TRY.
94e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
95e76fa9ecSHeejin Ahn   // <TRY marker, EH pad> map
96e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
97e76fa9ecSHeejin Ahn   // <EH pad, TRY marker> map
98e76fa9ecSHeejin Ahn   DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
99e76fa9ecSHeejin Ahn 
100ed41945fSHeejin Ahn   // We need an appendix block to place 'end_loop' or 'end_try' marker when the
101ed41945fSHeejin Ahn   // loop / exception bottom block is the last block in a function
102c4ac74fbSHeejin Ahn   MachineBasicBlock *AppendixBB = nullptr;
103c4ac74fbSHeejin Ahn   MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
104c4ac74fbSHeejin Ahn     if (!AppendixBB) {
105c4ac74fbSHeejin Ahn       AppendixBB = MF.CreateMachineBasicBlock();
106c4ac74fbSHeejin Ahn       // Give it a fake predecessor so that AsmPrinter prints its label.
107c4ac74fbSHeejin Ahn       AppendixBB->addSuccessor(AppendixBB);
108c4ac74fbSHeejin Ahn       MF.push_back(AppendixBB);
109c4ac74fbSHeejin Ahn     }
110c4ac74fbSHeejin Ahn     return AppendixBB;
111c4ac74fbSHeejin Ahn   }
112c4ac74fbSHeejin Ahn 
113ed41945fSHeejin Ahn   // Before running rewriteDepthImmediates function, 'delegate' has a BB as its
114ed41945fSHeejin Ahn   // destination operand. getFakeCallerBlock() returns a fake BB that will be
115ed41945fSHeejin Ahn   // used for the operand when 'delegate' needs to rethrow to the caller. This
116ed41945fSHeejin Ahn   // will be rewritten as an immediate value that is the number of block depths
117ed41945fSHeejin Ahn   // + 1 in rewriteDepthImmediates, and this fake BB will be removed at the end
118ed41945fSHeejin Ahn   // of the pass.
119ed41945fSHeejin Ahn   MachineBasicBlock *FakeCallerBB = nullptr;
120ed41945fSHeejin Ahn   MachineBasicBlock *getFakeCallerBlock(MachineFunction &MF) {
121ed41945fSHeejin Ahn     if (!FakeCallerBB)
122ed41945fSHeejin Ahn       FakeCallerBB = MF.CreateMachineBasicBlock();
123ed41945fSHeejin Ahn     return FakeCallerBB;
124ed41945fSHeejin Ahn   }
125ed41945fSHeejin Ahn 
126cf699b45SHeejin Ahn   // Helper functions to register / unregister scope information created by
127cf699b45SHeejin Ahn   // marker instructions.
128e76fa9ecSHeejin Ahn   void registerScope(MachineInstr *Begin, MachineInstr *End);
129e76fa9ecSHeejin Ahn   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
130e76fa9ecSHeejin Ahn                         MachineBasicBlock *EHPad);
131cf699b45SHeejin Ahn   void unregisterScope(MachineInstr *Begin);
132e76fa9ecSHeejin Ahn 
133950a13cfSDan Gohman public:
134950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
135950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
136e76fa9ecSHeejin Ahn   ~WebAssemblyCFGStackify() override { releaseMemory(); }
137e76fa9ecSHeejin Ahn   void releaseMemory() override;
138950a13cfSDan Gohman };
139950a13cfSDan Gohman } // end anonymous namespace
140950a13cfSDan Gohman 
141950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
14240926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
143c4ac74fbSHeejin Ahn                 "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false,
144f208f631SHeejin Ahn                 false)
14540926451SJacob Gravelle 
146950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
147950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
148950a13cfSDan Gohman }
149950a13cfSDan Gohman 
150b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
151b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
152b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
153b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
154b3aa1ecaSDan Gohman /// explicit mentions.
15518c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
15635e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
157b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
158b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
159b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
160b3aa1ecaSDan Gohman         return true;
161b3aa1ecaSDan Gohman   return false;
162b3aa1ecaSDan Gohman }
163b3aa1ecaSDan Gohman 
164e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB,
165e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
166e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
167e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only
168e76fa9ecSHeejin Ahn // used for sanity checking.
1691cc52357SHeejin Ahn template <typename Container>
170e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
1711cc52357SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
1721cc52357SHeejin Ahn                      const Container &AfterSet) {
173e76fa9ecSHeejin Ahn   auto InsertPos = MBB->end();
174e76fa9ecSHeejin Ahn   while (InsertPos != MBB->begin()) {
175e76fa9ecSHeejin Ahn     if (BeforeSet.count(&*std::prev(InsertPos))) {
176e76fa9ecSHeejin Ahn #ifndef NDEBUG
177e76fa9ecSHeejin Ahn       // Sanity check
178e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
179e76fa9ecSHeejin Ahn         assert(!AfterSet.count(&*std::prev(Pos)));
180e76fa9ecSHeejin Ahn #endif
181e76fa9ecSHeejin Ahn       break;
182e76fa9ecSHeejin Ahn     }
183e76fa9ecSHeejin Ahn     --InsertPos;
184e76fa9ecSHeejin Ahn   }
185e76fa9ecSHeejin Ahn   return InsertPos;
186e76fa9ecSHeejin Ahn }
187e76fa9ecSHeejin Ahn 
188e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB,
189e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
190e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
191e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only
192e76fa9ecSHeejin Ahn // used for sanity checking.
1931cc52357SHeejin Ahn template <typename Container>
194e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
1951cc52357SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
1961cc52357SHeejin Ahn                    const Container &AfterSet) {
197e76fa9ecSHeejin Ahn   auto InsertPos = MBB->begin();
198e76fa9ecSHeejin Ahn   while (InsertPos != MBB->end()) {
199e76fa9ecSHeejin Ahn     if (AfterSet.count(&*InsertPos)) {
200e76fa9ecSHeejin Ahn #ifndef NDEBUG
201e76fa9ecSHeejin Ahn       // Sanity check
202e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
203e76fa9ecSHeejin Ahn         assert(!BeforeSet.count(&*Pos));
204e76fa9ecSHeejin Ahn #endif
205e76fa9ecSHeejin Ahn       break;
206e76fa9ecSHeejin Ahn     }
207e76fa9ecSHeejin Ahn     ++InsertPos;
208e76fa9ecSHeejin Ahn   }
209e76fa9ecSHeejin Ahn   return InsertPos;
210e76fa9ecSHeejin Ahn }
211e76fa9ecSHeejin Ahn 
212e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
213e76fa9ecSHeejin Ahn                                            MachineInstr *End) {
214e76fa9ecSHeejin Ahn   BeginToEnd[Begin] = End;
215e76fa9ecSHeejin Ahn   EndToBegin[End] = Begin;
216e76fa9ecSHeejin Ahn }
217e76fa9ecSHeejin Ahn 
218ed41945fSHeejin Ahn // When 'End' is not an 'end_try' but 'delegate, EHPad is nullptr.
219e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
220e76fa9ecSHeejin Ahn                                               MachineInstr *End,
221e76fa9ecSHeejin Ahn                                               MachineBasicBlock *EHPad) {
222e76fa9ecSHeejin Ahn   registerScope(Begin, End);
223e76fa9ecSHeejin Ahn   TryToEHPad[Begin] = EHPad;
224e76fa9ecSHeejin Ahn   EHPadToTry[EHPad] = Begin;
225e76fa9ecSHeejin Ahn }
226e76fa9ecSHeejin Ahn 
227cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
228cf699b45SHeejin Ahn   assert(BeginToEnd.count(Begin));
229cf699b45SHeejin Ahn   MachineInstr *End = BeginToEnd[Begin];
230cf699b45SHeejin Ahn   assert(EndToBegin.count(End));
231cf699b45SHeejin Ahn   BeginToEnd.erase(Begin);
232cf699b45SHeejin Ahn   EndToBegin.erase(End);
233cf699b45SHeejin Ahn   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
234cf699b45SHeejin Ahn   if (EHPad) {
235cf699b45SHeejin Ahn     assert(EHPadToTry.count(EHPad));
236cf699b45SHeejin Ahn     TryToEHPad.erase(Begin);
237cf699b45SHeejin Ahn     EHPadToTry.erase(EHPad);
238cf699b45SHeejin Ahn   }
239cf699b45SHeejin Ahn }
240cf699b45SHeejin Ahn 
24132807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
242c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and
243c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later.
244e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
24544a5a4b1SHeejin Ahn   assert(!MBB.isEHPad());
246e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
247e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
248e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
249e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
250e76fa9ecSHeejin Ahn 
2518fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
2528fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
2538fe7e86bSDan Gohman   // which reduces overall stack height.
25432807932SDan Gohman   MachineBasicBlock *Header = nullptr;
25532807932SDan Gohman   bool IsBranchedTo = false;
25632807932SDan Gohman   int MBBNumber = MBB.getNumber();
257e76fa9ecSHeejin Ahn   for (MachineBasicBlock *Pred : MBB.predecessors()) {
25832807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
25932807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
26052e240a0SHeejin Ahn       if (explicitlyBranchesTo(Pred, &MBB))
26132807932SDan Gohman         IsBranchedTo = true;
26232807932SDan Gohman     }
263e76fa9ecSHeejin Ahn   }
26432807932SDan Gohman   if (!Header)
26532807932SDan Gohman     return;
26632807932SDan Gohman   if (!IsBranchedTo)
26732807932SDan Gohman     return;
26832807932SDan Gohman 
2698fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
2705c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
2718fe7e86bSDan Gohman 
2728fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
2738fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
2748fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
2758fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
2768fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
2778fe7e86bSDan Gohman         // Skip over an intervening scope.
2785c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
2798fe7e86bSDan Gohman       } else {
2808fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
2818fe7e86bSDan Gohman         Header = ScopeTop;
2828fe7e86bSDan Gohman         break;
2838fe7e86bSDan Gohman       }
2848fe7e86bSDan Gohman     }
2858fe7e86bSDan Gohman   }
2868fe7e86bSDan Gohman 
2878fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
288e76fa9ecSHeejin Ahn 
289e76fa9ecSHeejin Ahn   // Instructions that should go before the BLOCK.
290e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
291e76fa9ecSHeejin Ahn   // Instructions that should go after the BLOCK.
292e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
293e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
29444a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
29544a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the BLOCK, because the loop is
29644a5a4b1SHeejin Ahn     // nested in this BLOCK. Otherwise it should be before the BLOCK.
29744a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
29844a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
29944a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
300e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
301e76fa9ecSHeejin Ahn #ifndef NDEBUG
302e76fa9ecSHeejin Ahn       else
303e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
304e76fa9ecSHeejin Ahn #endif
305e76fa9ecSHeejin Ahn     }
306e76fa9ecSHeejin Ahn 
307834debffSHeejin Ahn     // If there is a previously placed BLOCK/TRY marker and its corresponding
308834debffSHeejin Ahn     // END marker is before the current BLOCK's END marker, that should be
309834debffSHeejin Ahn     // placed after this BLOCK. Otherwise it should be placed before this BLOCK
310834debffSHeejin Ahn     // marker.
31144a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
312834debffSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY) {
313834debffSHeejin Ahn       if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
314e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
315834debffSHeejin Ahn #ifndef NDEBUG
316834debffSHeejin Ahn       else
317834debffSHeejin Ahn         BeforeSet.insert(&MI);
318834debffSHeejin Ahn #endif
319834debffSHeejin Ahn     }
320e76fa9ecSHeejin Ahn 
321e76fa9ecSHeejin Ahn #ifndef NDEBUG
322e76fa9ecSHeejin Ahn     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
323e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
324e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
325e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
326e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
327e76fa9ecSHeejin Ahn #endif
328e76fa9ecSHeejin Ahn 
329e76fa9ecSHeejin Ahn     // Terminators should go after the BLOCK.
330e76fa9ecSHeejin Ahn     if (MI.isTerminator())
331e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
332e76fa9ecSHeejin Ahn   }
333e76fa9ecSHeejin Ahn 
334e76fa9ecSHeejin Ahn   // Local expression tree should go after the BLOCK.
335e76fa9ecSHeejin Ahn   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
336e76fa9ecSHeejin Ahn        --I) {
337409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
338409b4391SYury Delendik       continue;
339e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
340e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
341e76fa9ecSHeejin Ahn     else
342e76fa9ecSHeejin Ahn       break;
34332807932SDan Gohman   }
34432807932SDan Gohman 
3458fe7e86bSDan Gohman   // Add the BLOCK.
3462cb27072SThomas Lively   WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
34718c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
34892401cc1SHeejin Ahn   MachineInstr *Begin =
34992401cc1SHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
3502726b88cSDan Gohman               TII.get(WebAssembly::BLOCK))
351d6f48786SHeejin Ahn           .addImm(int64_t(ReturnType));
3521d68e80fSDan Gohman 
353e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_BLOCK.
354e76fa9ecSHeejin Ahn   BeforeSet.clear();
355e76fa9ecSHeejin Ahn   AfterSet.clear();
356e76fa9ecSHeejin Ahn   for (auto &MI : MBB) {
357e76fa9ecSHeejin Ahn #ifndef NDEBUG
358e76fa9ecSHeejin Ahn     // END_BLOCK should precede existing LOOP and TRY markers.
359e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
360e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
361e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
362e76fa9ecSHeejin Ahn #endif
363e76fa9ecSHeejin Ahn 
364e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and the header of the
365e76fa9ecSHeejin Ahn     // loop is above this block's header, the END_LOOP should be placed after
366e76fa9ecSHeejin Ahn     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
367e76fa9ecSHeejin Ahn     // should be placed before the BLOCK. The same for END_TRY.
368e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP ||
369e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY) {
370e76fa9ecSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
371e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
372e76fa9ecSHeejin Ahn #ifndef NDEBUG
373e76fa9ecSHeejin Ahn       else
374e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
375e76fa9ecSHeejin Ahn #endif
376e76fa9ecSHeejin Ahn     }
377e76fa9ecSHeejin Ahn   }
378e76fa9ecSHeejin Ahn 
3791d68e80fSDan Gohman   // Mark the end of the block.
38018c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
38110b31358SDerek Schuff   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
3822726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
383e76fa9ecSHeejin Ahn   registerScope(Begin, End);
3848fe7e86bSDan Gohman 
3858fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
3861cc52357SHeejin Ahn   updateScopeTops(Header, &MBB);
387950a13cfSDan Gohman }
388950a13cfSDan Gohman 
3898fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
390e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
391e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
392e76fa9ecSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
393276f9e8cSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
394276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
395e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
396e76fa9ecSHeejin Ahn 
3978fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
3988fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
3998fe7e86bSDan Gohman     return;
4008fe7e86bSDan Gohman 
4018fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
4028fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
403276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(Loop);
4045c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
405e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
406c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
4075c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
408e3e4a5ffSDan Gohman   }
4098fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
410f6857223SDan Gohman 
411e76fa9ecSHeejin Ahn   // Decide where in Header to put the LOOP.
412e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
413e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
414e76fa9ecSHeejin Ahn   for (const auto &MI : MBB) {
415e76fa9ecSHeejin Ahn     // LOOP marker should be after any existing loop that ends here. Otherwise
416e76fa9ecSHeejin Ahn     // we assume the instruction belongs to the loop.
417e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
418e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
419e76fa9ecSHeejin Ahn #ifndef NDEBUG
420e76fa9ecSHeejin Ahn     else
421e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
422e76fa9ecSHeejin Ahn #endif
423e76fa9ecSHeejin Ahn   }
424e76fa9ecSHeejin Ahn 
425e76fa9ecSHeejin Ahn   // Mark the beginning of the loop.
42618c56a07SHeejin Ahn   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
42710b31358SDerek Schuff   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
4282726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
4292cb27072SThomas Lively                             .addImm(int64_t(WebAssembly::BlockType::Void));
4301d68e80fSDan Gohman 
431e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_LOOP.
432e76fa9ecSHeejin Ahn   BeforeSet.clear();
433e76fa9ecSHeejin Ahn   AfterSet.clear();
434e76fa9ecSHeejin Ahn #ifndef NDEBUG
435e76fa9ecSHeejin Ahn   for (const auto &MI : MBB)
436e76fa9ecSHeejin Ahn     // Existing END_LOOP markers belong to parent loops of this loop
437e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
438e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
439e76fa9ecSHeejin Ahn #endif
440e76fa9ecSHeejin Ahn 
441e76fa9ecSHeejin Ahn   // Mark the end of the loop (using arbitrary debug location that branched to
442e76fa9ecSHeejin Ahn   // the loop end as its location).
44318c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
44467f74aceSHeejin Ahn   DebugLoc EndDL = AfterLoop->pred_empty()
44567f74aceSHeejin Ahn                        ? DebugLoc()
44667f74aceSHeejin Ahn                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
447e76fa9ecSHeejin Ahn   MachineInstr *End =
448e76fa9ecSHeejin Ahn       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
449e76fa9ecSHeejin Ahn   registerScope(Begin, End);
4508fe7e86bSDan Gohman 
4518fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4528fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
453442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
4541cc52357SHeejin Ahn   updateScopeTops(&MBB, AfterLoop);
455e3e4a5ffSDan Gohman }
456950a13cfSDan Gohman 
457e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
45844a5a4b1SHeejin Ahn   assert(MBB.isEHPad());
459e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
460e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
461e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
462276f9e8cSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
463e76fa9ecSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
464276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
465e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
466e76fa9ecSHeejin Ahn 
467e76fa9ecSHeejin Ahn   // Compute the nearest common dominator of all unwind predecessors
468e76fa9ecSHeejin Ahn   MachineBasicBlock *Header = nullptr;
469e76fa9ecSHeejin Ahn   int MBBNumber = MBB.getNumber();
470e76fa9ecSHeejin Ahn   for (auto *Pred : MBB.predecessors()) {
471e76fa9ecSHeejin Ahn     if (Pred->getNumber() < MBBNumber) {
472e76fa9ecSHeejin Ahn       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
47318c56a07SHeejin Ahn       assert(!explicitlyBranchesTo(Pred, &MBB) &&
474e76fa9ecSHeejin Ahn              "Explicit branch to an EH pad!");
475e76fa9ecSHeejin Ahn     }
476e76fa9ecSHeejin Ahn   }
477e76fa9ecSHeejin Ahn   if (!Header)
478e76fa9ecSHeejin Ahn     return;
479e76fa9ecSHeejin Ahn 
480e76fa9ecSHeejin Ahn   // If this try is at the bottom of the function, insert a dummy block at the
481e76fa9ecSHeejin Ahn   // end.
482e76fa9ecSHeejin Ahn   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
483e76fa9ecSHeejin Ahn   assert(WE);
484276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(WE);
485e76fa9ecSHeejin Ahn 
4865c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
487e76fa9ecSHeejin Ahn   if (Iter == MF.end()) {
488c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
4895c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
490e76fa9ecSHeejin Ahn   }
49120cf0749SHeejin Ahn   MachineBasicBlock *Cont = &*Iter;
492e76fa9ecSHeejin Ahn 
49320cf0749SHeejin Ahn   assert(Cont != &MF.front());
4945c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
495e76fa9ecSHeejin Ahn 
496e76fa9ecSHeejin Ahn   // If the nearest common dominator is inside a more deeply nested context,
497e76fa9ecSHeejin Ahn   // walk out to the nearest scope which isn't more deeply nested.
498e76fa9ecSHeejin Ahn   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
499e76fa9ecSHeejin Ahn     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
500e76fa9ecSHeejin Ahn       if (ScopeTop->getNumber() > Header->getNumber()) {
501e76fa9ecSHeejin Ahn         // Skip over an intervening scope.
5025c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
503e76fa9ecSHeejin Ahn       } else {
504e76fa9ecSHeejin Ahn         // We found a scope level at an appropriate depth.
505e76fa9ecSHeejin Ahn         Header = ScopeTop;
506e76fa9ecSHeejin Ahn         break;
507e76fa9ecSHeejin Ahn       }
508e76fa9ecSHeejin Ahn     }
509e76fa9ecSHeejin Ahn   }
510e76fa9ecSHeejin Ahn 
511e76fa9ecSHeejin Ahn   // Decide where in Header to put the TRY.
512e76fa9ecSHeejin Ahn 
51344a5a4b1SHeejin Ahn   // Instructions that should go before the TRY.
514e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
51544a5a4b1SHeejin Ahn   // Instructions that should go after the TRY.
516e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
517e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
51844a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
51944a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the TRY, because the loop is nested
52044a5a4b1SHeejin Ahn     // in this TRY. Otherwise it should be before the TRY.
521e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
52244a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
52344a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
524e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
525e76fa9ecSHeejin Ahn #ifndef NDEBUG
526e76fa9ecSHeejin Ahn       else
527e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
528e76fa9ecSHeejin Ahn #endif
529e76fa9ecSHeejin Ahn     }
530e76fa9ecSHeejin Ahn 
53144a5a4b1SHeejin Ahn     // All previously inserted BLOCK/TRY markers should be after the TRY because
53244a5a4b1SHeejin Ahn     // they are all nested trys.
53344a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
53444a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
535e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
536e76fa9ecSHeejin Ahn 
537e76fa9ecSHeejin Ahn #ifndef NDEBUG
53844a5a4b1SHeejin Ahn     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
53944a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
54044a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
541e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
542e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
543e76fa9ecSHeejin Ahn #endif
544e76fa9ecSHeejin Ahn 
545e76fa9ecSHeejin Ahn     // Terminators should go after the TRY.
546e76fa9ecSHeejin Ahn     if (MI.isTerminator())
547e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
548e76fa9ecSHeejin Ahn   }
549e76fa9ecSHeejin Ahn 
5506a37c5d6SHeejin Ahn   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
5516a37c5d6SHeejin Ahn   // contain the call within it. So the call should go after the TRY. The
5526a37c5d6SHeejin Ahn   // exception is when the header's terminator is a rethrow instruction, in
5536a37c5d6SHeejin Ahn   // which case that instruction, not a call instruction before it, is gonna
5546a37c5d6SHeejin Ahn   // throw.
5556a37c5d6SHeejin Ahn   MachineInstr *ThrowingCall = nullptr;
5566a37c5d6SHeejin Ahn   if (MBB.isPredecessor(Header)) {
5576a37c5d6SHeejin Ahn     auto TermPos = Header->getFirstTerminator();
5586a37c5d6SHeejin Ahn     if (TermPos == Header->end() ||
5596a37c5d6SHeejin Ahn         TermPos->getOpcode() != WebAssembly::RETHROW) {
5606a37c5d6SHeejin Ahn       for (auto &MI : reverse(*Header)) {
5616a37c5d6SHeejin Ahn         if (MI.isCall()) {
5626a37c5d6SHeejin Ahn           AfterSet.insert(&MI);
5636a37c5d6SHeejin Ahn           ThrowingCall = &MI;
5646a37c5d6SHeejin Ahn           // Possibly throwing calls are usually wrapped by EH_LABEL
5656a37c5d6SHeejin Ahn           // instructions. We don't want to split them and the call.
5666a37c5d6SHeejin Ahn           if (MI.getIterator() != Header->begin() &&
5676a37c5d6SHeejin Ahn               std::prev(MI.getIterator())->isEHLabel()) {
5686a37c5d6SHeejin Ahn             AfterSet.insert(&*std::prev(MI.getIterator()));
5696a37c5d6SHeejin Ahn             ThrowingCall = &*std::prev(MI.getIterator());
5706a37c5d6SHeejin Ahn           }
5716a37c5d6SHeejin Ahn           break;
5726a37c5d6SHeejin Ahn         }
5736a37c5d6SHeejin Ahn       }
5746a37c5d6SHeejin Ahn     }
5756a37c5d6SHeejin Ahn   }
5766a37c5d6SHeejin Ahn 
577e76fa9ecSHeejin Ahn   // Local expression tree should go after the TRY.
5786a37c5d6SHeejin Ahn   // For BLOCK placement, we start the search from the previous instruction of a
5796a37c5d6SHeejin Ahn   // BB's terminator, but in TRY's case, we should start from the previous
5806a37c5d6SHeejin Ahn   // instruction of a call that can throw, or a EH_LABEL that precedes the call,
5816a37c5d6SHeejin Ahn   // because the return values of the call's previous instructions can be
5826a37c5d6SHeejin Ahn   // stackified and consumed by the throwing call.
5836a37c5d6SHeejin Ahn   auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
5846a37c5d6SHeejin Ahn                                     : Header->getFirstTerminator();
5856a37c5d6SHeejin Ahn   for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
586409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
587409b4391SYury Delendik       continue;
588e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
589e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
590e76fa9ecSHeejin Ahn     else
591e76fa9ecSHeejin Ahn       break;
592e76fa9ecSHeejin Ahn   }
593e76fa9ecSHeejin Ahn 
594e76fa9ecSHeejin Ahn   // Add the TRY.
59518c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
596e76fa9ecSHeejin Ahn   MachineInstr *Begin =
597e76fa9ecSHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
598e76fa9ecSHeejin Ahn               TII.get(WebAssembly::TRY))
5992cb27072SThomas Lively           .addImm(int64_t(WebAssembly::BlockType::Void));
600e76fa9ecSHeejin Ahn 
601e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_TRY.
602e76fa9ecSHeejin Ahn   BeforeSet.clear();
603e76fa9ecSHeejin Ahn   AfterSet.clear();
60420cf0749SHeejin Ahn   for (const auto &MI : *Cont) {
605e76fa9ecSHeejin Ahn #ifndef NDEBUG
60644a5a4b1SHeejin Ahn     // END_TRY should precede existing LOOP and BLOCK markers.
60744a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
60844a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::BLOCK)
609e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
610e76fa9ecSHeejin Ahn 
611e76fa9ecSHeejin Ahn     // All END_TRY markers placed earlier belong to exceptions that contains
612e76fa9ecSHeejin Ahn     // this one.
613e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_TRY)
614e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
615e76fa9ecSHeejin Ahn #endif
616e76fa9ecSHeejin Ahn 
617e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and its header is after
618e76fa9ecSHeejin Ahn     // where TRY marker is, this loop is contained within the 'catch' part, so
619e76fa9ecSHeejin Ahn     // the END_TRY marker should go after that. Otherwise, the whole try-catch
620e76fa9ecSHeejin Ahn     // is contained within this loop, so the END_TRY should go before that.
621e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP) {
622222718fdSHeejin Ahn       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
623222718fdSHeejin Ahn       // are in the same BB, LOOP is always before TRY.
624222718fdSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
625e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
626e76fa9ecSHeejin Ahn #ifndef NDEBUG
627e76fa9ecSHeejin Ahn       else
628e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
629e76fa9ecSHeejin Ahn #endif
630e76fa9ecSHeejin Ahn     }
63144a5a4b1SHeejin Ahn 
63244a5a4b1SHeejin Ahn     // It is not possible for an END_BLOCK to be already in this block.
633e76fa9ecSHeejin Ahn   }
634e76fa9ecSHeejin Ahn 
635e76fa9ecSHeejin Ahn   // Mark the end of the TRY.
63620cf0749SHeejin Ahn   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
637e76fa9ecSHeejin Ahn   MachineInstr *End =
63820cf0749SHeejin Ahn       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
639e76fa9ecSHeejin Ahn               TII.get(WebAssembly::END_TRY));
640e76fa9ecSHeejin Ahn   registerTryScope(Begin, End, &MBB);
641e76fa9ecSHeejin Ahn 
64282da1ffcSHeejin Ahn   // Track the farthest-spanning scope that ends at this point. We create two
64382da1ffcSHeejin Ahn   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
64482da1ffcSHeejin Ahn   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
64582da1ffcSHeejin Ahn   // markers should not span across 'catch'. For example, this should not
64682da1ffcSHeejin Ahn   // happen:
64782da1ffcSHeejin Ahn   //
64882da1ffcSHeejin Ahn   // try
64982da1ffcSHeejin Ahn   //   block     --|  (X)
65082da1ffcSHeejin Ahn   // catch         |
65182da1ffcSHeejin Ahn   //   end_block --|
65282da1ffcSHeejin Ahn   // end_try
6531cc52357SHeejin Ahn   for (auto *End : {&MBB, Cont})
6541cc52357SHeejin Ahn     updateScopeTops(Header, End);
65582da1ffcSHeejin Ahn }
656e76fa9ecSHeejin Ahn 
657cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
658cf699b45SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
659cf699b45SHeejin Ahn 
660cf699b45SHeejin Ahn   // When there is an unconditional branch right before a catch instruction and
661cf699b45SHeejin Ahn   // it branches to the end of end_try marker, we don't need the branch, because
662cf699b45SHeejin Ahn   // it there is no exception, the control flow transfers to that point anyway.
663cf699b45SHeejin Ahn   // bb0:
664cf699b45SHeejin Ahn   //   try
665cf699b45SHeejin Ahn   //     ...
666cf699b45SHeejin Ahn   //     br bb2      <- Not necessary
667c93b9559SHeejin Ahn   // bb1 (ehpad):
668cf699b45SHeejin Ahn   //   catch
669cf699b45SHeejin Ahn   //     ...
670c93b9559SHeejin Ahn   // bb2:            <- Continuation BB
671cf699b45SHeejin Ahn   //   end
672c93b9559SHeejin Ahn   //
673c93b9559SHeejin Ahn   // A more involved case: When the BB where 'end' is located is an another EH
674c93b9559SHeejin Ahn   // pad, the Cont (= continuation) BB is that EH pad's 'end' BB. For example,
675c93b9559SHeejin Ahn   // bb0:
676c93b9559SHeejin Ahn   //   try
677c93b9559SHeejin Ahn   //     try
678c93b9559SHeejin Ahn   //       ...
679c93b9559SHeejin Ahn   //       br bb3      <- Not necessary
680c93b9559SHeejin Ahn   // bb1 (ehpad):
681c93b9559SHeejin Ahn   //     catch
682c93b9559SHeejin Ahn   // bb2 (ehpad):
683c93b9559SHeejin Ahn   //     end
684c93b9559SHeejin Ahn   //   catch
685c93b9559SHeejin Ahn   //     ...
686c93b9559SHeejin Ahn   // bb3:            <- Continuation BB
687c93b9559SHeejin Ahn   //   end
688c93b9559SHeejin Ahn   //
689c93b9559SHeejin Ahn   // When the EH pad at hand is bb1, its matching end_try is in bb2. But it is
690c93b9559SHeejin Ahn   // another EH pad, so bb0's continuation BB becomes bb3. So 'br bb3' in the
691c93b9559SHeejin Ahn   // code can be deleted. This is why we run 'while' until 'Cont' is not an EH
692c93b9559SHeejin Ahn   // pad.
693cf699b45SHeejin Ahn   for (auto &MBB : MF) {
694cf699b45SHeejin Ahn     if (!MBB.isEHPad())
695cf699b45SHeejin Ahn       continue;
696cf699b45SHeejin Ahn 
697cf699b45SHeejin Ahn     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
698cf699b45SHeejin Ahn     SmallVector<MachineOperand, 4> Cond;
6995c644c9bSHeejin Ahn     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
700c93b9559SHeejin Ahn 
701c93b9559SHeejin Ahn     MachineBasicBlock *Cont = &MBB;
702c93b9559SHeejin Ahn     while (Cont->isEHPad()) {
703c93b9559SHeejin Ahn       MachineInstr *Try = EHPadToTry[Cont];
704c93b9559SHeejin Ahn       MachineInstr *EndTry = BeginToEnd[Try];
705ed41945fSHeejin Ahn       // We started from an EH pad, so the end marker cannot be a delegate
706ed41945fSHeejin Ahn       assert(EndTry->getOpcode() != WebAssembly::DELEGATE);
707c93b9559SHeejin Ahn       Cont = EndTry->getParent();
708c93b9559SHeejin Ahn     }
709c93b9559SHeejin Ahn 
710cf699b45SHeejin Ahn     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
7113fe6ea46SHeejin Ahn     // This condition means either
7123fe6ea46SHeejin Ahn     // 1. This BB ends with a single unconditional branch whose destinaion is
7133fe6ea46SHeejin Ahn     //    Cont.
7143fe6ea46SHeejin Ahn     // 2. This BB ends with a conditional branch followed by an unconditional
7153fe6ea46SHeejin Ahn     //    branch, and the unconditional branch's destination is Cont.
7163fe6ea46SHeejin Ahn     // In both cases, we want to remove the last (= unconditional) branch.
717cf699b45SHeejin Ahn     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
7183fe6ea46SHeejin Ahn                        (!Cond.empty() && FBB && FBB == Cont))) {
7193fe6ea46SHeejin Ahn       bool ErasedUncondBr = false;
720a5099ad9SHeejin Ahn       (void)ErasedUncondBr;
7213fe6ea46SHeejin Ahn       for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
7223fe6ea46SHeejin Ahn            I != E; --I) {
7233fe6ea46SHeejin Ahn         auto PrevI = std::prev(I);
7243fe6ea46SHeejin Ahn         if (PrevI->isTerminator()) {
7253fe6ea46SHeejin Ahn           assert(PrevI->getOpcode() == WebAssembly::BR);
7263fe6ea46SHeejin Ahn           PrevI->eraseFromParent();
7273fe6ea46SHeejin Ahn           ErasedUncondBr = true;
7283fe6ea46SHeejin Ahn           break;
7293fe6ea46SHeejin Ahn         }
7303fe6ea46SHeejin Ahn       }
7313fe6ea46SHeejin Ahn       assert(ErasedUncondBr && "Unconditional branch not erased!");
7323fe6ea46SHeejin Ahn     }
733cf699b45SHeejin Ahn   }
734cf699b45SHeejin Ahn 
735cf699b45SHeejin Ahn   // When there are block / end_block markers that overlap with try / end_try
736cf699b45SHeejin Ahn   // markers, and the block and try markers' return types are the same, the
737cf699b45SHeejin Ahn   // block /end_block markers are not necessary, because try / end_try markers
738cf699b45SHeejin Ahn   // also can serve as boundaries for branches.
739cf699b45SHeejin Ahn   // block         <- Not necessary
740cf699b45SHeejin Ahn   //   try
741cf699b45SHeejin Ahn   //     ...
742cf699b45SHeejin Ahn   //   catch
743cf699b45SHeejin Ahn   //     ...
744cf699b45SHeejin Ahn   //   end
745cf699b45SHeejin Ahn   // end           <- Not necessary
746cf699b45SHeejin Ahn   SmallVector<MachineInstr *, 32> ToDelete;
747cf699b45SHeejin Ahn   for (auto &MBB : MF) {
748cf699b45SHeejin Ahn     for (auto &MI : MBB) {
749cf699b45SHeejin Ahn       if (MI.getOpcode() != WebAssembly::TRY)
750cf699b45SHeejin Ahn         continue;
751cf699b45SHeejin Ahn       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
752ed41945fSHeejin Ahn       if (EndTry->getOpcode() == WebAssembly::DELEGATE)
753ed41945fSHeejin Ahn         continue;
754ed41945fSHeejin Ahn 
755cf699b45SHeejin Ahn       MachineBasicBlock *TryBB = Try->getParent();
756cf699b45SHeejin Ahn       MachineBasicBlock *Cont = EndTry->getParent();
757cf699b45SHeejin Ahn       int64_t RetType = Try->getOperand(0).getImm();
7585c644c9bSHeejin Ahn       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
759cf699b45SHeejin Ahn            B != TryBB->begin() && E != Cont->end() &&
760cf699b45SHeejin Ahn            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
761cf699b45SHeejin Ahn            E->getOpcode() == WebAssembly::END_BLOCK &&
762cf699b45SHeejin Ahn            std::prev(B)->getOperand(0).getImm() == RetType;
763cf699b45SHeejin Ahn            --B, ++E) {
764cf699b45SHeejin Ahn         ToDelete.push_back(&*std::prev(B));
765cf699b45SHeejin Ahn         ToDelete.push_back(&*E);
766cf699b45SHeejin Ahn       }
767cf699b45SHeejin Ahn     }
768cf699b45SHeejin Ahn   }
769cf699b45SHeejin Ahn   for (auto *MI : ToDelete) {
770cf699b45SHeejin Ahn     if (MI->getOpcode() == WebAssembly::BLOCK)
771cf699b45SHeejin Ahn       unregisterScope(MI);
772cf699b45SHeejin Ahn     MI->eraseFromParent();
773cf699b45SHeejin Ahn   }
774cf699b45SHeejin Ahn }
775cf699b45SHeejin Ahn 
77683c26eaeSHeejin Ahn // Get the appropriate copy opcode for the given register class.
77783c26eaeSHeejin Ahn static unsigned getCopyOpcode(const TargetRegisterClass *RC) {
77883c26eaeSHeejin Ahn   if (RC == &WebAssembly::I32RegClass)
77983c26eaeSHeejin Ahn     return WebAssembly::COPY_I32;
78083c26eaeSHeejin Ahn   if (RC == &WebAssembly::I64RegClass)
78183c26eaeSHeejin Ahn     return WebAssembly::COPY_I64;
78283c26eaeSHeejin Ahn   if (RC == &WebAssembly::F32RegClass)
78383c26eaeSHeejin Ahn     return WebAssembly::COPY_F32;
78483c26eaeSHeejin Ahn   if (RC == &WebAssembly::F64RegClass)
78583c26eaeSHeejin Ahn     return WebAssembly::COPY_F64;
78683c26eaeSHeejin Ahn   if (RC == &WebAssembly::V128RegClass)
78783c26eaeSHeejin Ahn     return WebAssembly::COPY_V128;
78860653e24SHeejin Ahn   if (RC == &WebAssembly::FUNCREFRegClass)
78960653e24SHeejin Ahn     return WebAssembly::COPY_FUNCREF;
79060653e24SHeejin Ahn   if (RC == &WebAssembly::EXTERNREFRegClass)
79160653e24SHeejin Ahn     return WebAssembly::COPY_EXTERNREF;
79283c26eaeSHeejin Ahn   llvm_unreachable("Unexpected register class");
79383c26eaeSHeejin Ahn }
79483c26eaeSHeejin Ahn 
79561d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that
79661d5c76aSHeejin Ahn // have their uses in Split.
797ed41945fSHeejin Ahn static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB,
798ed41945fSHeejin Ahn                                          MachineBasicBlock &Split) {
7991cc52357SHeejin Ahn   MachineFunction &MF = *MBB.getParent();
8001cc52357SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
8011cc52357SHeejin Ahn   auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
8021cc52357SHeejin Ahn   auto &MRI = MF.getRegInfo();
8031cc52357SHeejin Ahn 
80461d5c76aSHeejin Ahn   for (auto &MI : Split) {
80561d5c76aSHeejin Ahn     for (auto &MO : MI.explicit_uses()) {
80661d5c76aSHeejin Ahn       if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg()))
80761d5c76aSHeejin Ahn         continue;
80861d5c76aSHeejin Ahn       if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
80961d5c76aSHeejin Ahn         if (Def->getParent() == &MBB)
81061d5c76aSHeejin Ahn           MFI.unstackifyVReg(MO.getReg());
81161d5c76aSHeejin Ahn     }
81261d5c76aSHeejin Ahn   }
81383c26eaeSHeejin Ahn 
81483c26eaeSHeejin Ahn   // In RegStackify, when a register definition is used multiple times,
81583c26eaeSHeejin Ahn   //    Reg = INST ...
81683c26eaeSHeejin Ahn   //    INST ..., Reg, ...
81783c26eaeSHeejin Ahn   //    INST ..., Reg, ...
81883c26eaeSHeejin Ahn   //    INST ..., Reg, ...
81983c26eaeSHeejin Ahn   //
82083c26eaeSHeejin Ahn   // we introduce a TEE, which has the following form:
82183c26eaeSHeejin Ahn   //    DefReg = INST ...
82283c26eaeSHeejin Ahn   //    TeeReg, Reg = TEE_... DefReg
82383c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
82483c26eaeSHeejin Ahn   //    INST ..., Reg, ...
82583c26eaeSHeejin Ahn   //    INST ..., Reg, ...
82683c26eaeSHeejin Ahn   // with DefReg and TeeReg stackified but Reg not stackified.
82783c26eaeSHeejin Ahn   //
82883c26eaeSHeejin Ahn   // But the invariant that TeeReg should be stackified can be violated while we
82983c26eaeSHeejin Ahn   // unstackify registers in the split BB above. In this case, we convert TEEs
83083c26eaeSHeejin Ahn   // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
83183c26eaeSHeejin Ahn   //    DefReg = INST ...
83283c26eaeSHeejin Ahn   //    TeeReg = COPY DefReg
83383c26eaeSHeejin Ahn   //    Reg = COPY DefReg
83483c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
83583c26eaeSHeejin Ahn   //    INST ..., Reg, ...
83683c26eaeSHeejin Ahn   //    INST ..., Reg, ...
83783c26eaeSHeejin Ahn   for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
83883c26eaeSHeejin Ahn     MachineInstr &MI = *I++;
83983c26eaeSHeejin Ahn     if (!WebAssembly::isTee(MI.getOpcode()))
84083c26eaeSHeejin Ahn       continue;
84183c26eaeSHeejin Ahn     Register TeeReg = MI.getOperand(0).getReg();
84283c26eaeSHeejin Ahn     Register Reg = MI.getOperand(1).getReg();
84383c26eaeSHeejin Ahn     Register DefReg = MI.getOperand(2).getReg();
84483c26eaeSHeejin Ahn     if (!MFI.isVRegStackified(TeeReg)) {
84583c26eaeSHeejin Ahn       // Now we are not using TEE anymore, so unstackify DefReg too
84683c26eaeSHeejin Ahn       MFI.unstackifyVReg(DefReg);
84783c26eaeSHeejin Ahn       unsigned CopyOpc = getCopyOpcode(MRI.getRegClass(DefReg));
84883c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
84983c26eaeSHeejin Ahn           .addReg(DefReg);
85083c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
85183c26eaeSHeejin Ahn       MI.eraseFromParent();
85283c26eaeSHeejin Ahn     }
85383c26eaeSHeejin Ahn   }
85461d5c76aSHeejin Ahn }
85561d5c76aSHeejin Ahn 
856ed41945fSHeejin Ahn // Wrap the given range of instruction with try-delegate. RangeBegin and
857ed41945fSHeejin Ahn // RangeEnd are inclusive.
858ed41945fSHeejin Ahn void WebAssemblyCFGStackify::addTryDelegate(MachineInstr *RangeBegin,
859ed41945fSHeejin Ahn                                             MachineInstr *RangeEnd,
860ed41945fSHeejin Ahn                                             MachineBasicBlock *DelegateDest) {
861ed41945fSHeejin Ahn   auto *BeginBB = RangeBegin->getParent();
862ed41945fSHeejin Ahn   auto *EndBB = RangeEnd->getParent();
863ed41945fSHeejin Ahn   MachineFunction &MF = *BeginBB->getParent();
864ed41945fSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
865ed41945fSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
866ed41945fSHeejin Ahn 
867ed41945fSHeejin Ahn   // Local expression tree before the first call of this range should go
868ed41945fSHeejin Ahn   // after the nested TRY.
869ed41945fSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
870ed41945fSHeejin Ahn   AfterSet.insert(RangeBegin);
871ed41945fSHeejin Ahn   for (auto I = MachineBasicBlock::iterator(RangeBegin), E = BeginBB->begin();
872ed41945fSHeejin Ahn        I != E; --I) {
873ed41945fSHeejin Ahn     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
874ed41945fSHeejin Ahn       continue;
875ed41945fSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
876ed41945fSHeejin Ahn       AfterSet.insert(&*std::prev(I));
877ed41945fSHeejin Ahn     else
878ed41945fSHeejin Ahn       break;
879ed41945fSHeejin Ahn   }
880ed41945fSHeejin Ahn 
881ed41945fSHeejin Ahn   // Create the nested try instruction.
882ed41945fSHeejin Ahn   auto TryPos = getLatestInsertPos(
883ed41945fSHeejin Ahn       BeginBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet);
884ed41945fSHeejin Ahn   MachineInstr *Try = BuildMI(*BeginBB, TryPos, RangeBegin->getDebugLoc(),
885ed41945fSHeejin Ahn                               TII.get(WebAssembly::TRY))
886ed41945fSHeejin Ahn                           .addImm(int64_t(WebAssembly::BlockType::Void));
887ed41945fSHeejin Ahn 
888ed41945fSHeejin Ahn   // Create a BB to insert the 'delegate' instruction.
889ed41945fSHeejin Ahn   MachineBasicBlock *DelegateBB = MF.CreateMachineBasicBlock();
890ed41945fSHeejin Ahn   // If the destination of 'delegate' is not the caller, adds the destination to
891ed41945fSHeejin Ahn   // the BB's successors.
892ed41945fSHeejin Ahn   if (DelegateDest != FakeCallerBB)
893ed41945fSHeejin Ahn     DelegateBB->addSuccessor(DelegateDest);
894ed41945fSHeejin Ahn 
895ed41945fSHeejin Ahn   auto SplitPos = std::next(RangeEnd->getIterator());
896ed41945fSHeejin Ahn   if (SplitPos == EndBB->end()) {
897ed41945fSHeejin Ahn     // If the range's end instruction is at the end of the BB, insert the new
898ed41945fSHeejin Ahn     // delegate BB after the current BB.
899ed41945fSHeejin Ahn     MF.insert(std::next(EndBB->getIterator()), DelegateBB);
900ed41945fSHeejin Ahn     EndBB->addSuccessor(DelegateBB);
901ed41945fSHeejin Ahn 
902ed41945fSHeejin Ahn   } else {
903*9f770b36SHeejin Ahn     // When the split pos is in the middle of a BB, we split the BB into two and
904*9f770b36SHeejin Ahn     // put the 'delegate' BB in between. We normally create a split BB and make
905*9f770b36SHeejin Ahn     // it a successor of the original BB (PostSplit == true), but in case the BB
906*9f770b36SHeejin Ahn     // is an EH pad and the split pos is before 'catch', we should preserve the
907*9f770b36SHeejin Ahn     // BB's property, including that it is an EH pad, in the later part of the
908*9f770b36SHeejin Ahn     // BB, where 'catch' is. In this case we set PostSplit to false.
909*9f770b36SHeejin Ahn     bool PostSplit = true;
910*9f770b36SHeejin Ahn     if (EndBB->isEHPad()) {
911*9f770b36SHeejin Ahn       for (auto I = MachineBasicBlock::iterator(SplitPos), E = EndBB->end();
912*9f770b36SHeejin Ahn            I != E; ++I) {
913*9f770b36SHeejin Ahn         if (WebAssembly::isCatch(I->getOpcode())) {
914*9f770b36SHeejin Ahn           PostSplit = false;
915*9f770b36SHeejin Ahn           break;
916*9f770b36SHeejin Ahn         }
917*9f770b36SHeejin Ahn       }
918*9f770b36SHeejin Ahn     }
919*9f770b36SHeejin Ahn 
920*9f770b36SHeejin Ahn     MachineBasicBlock *PreBB = nullptr, *PostBB = nullptr;
921*9f770b36SHeejin Ahn     if (PostSplit) {
922ed41945fSHeejin Ahn       // If the range's end instruction is in the middle of the BB, we split the
923ed41945fSHeejin Ahn       // BB into two and insert the delegate BB in between.
924ed41945fSHeejin Ahn       // - Before:
925ed41945fSHeejin Ahn       // bb:
926ed41945fSHeejin Ahn       //   range_end
927ed41945fSHeejin Ahn       //   other_insts
928ed41945fSHeejin Ahn       //
929ed41945fSHeejin Ahn       // - After:
930ed41945fSHeejin Ahn       // pre_bb: (previous 'bb')
931ed41945fSHeejin Ahn       //   range_end
932ed41945fSHeejin Ahn       // delegate_bb: (new)
933ed41945fSHeejin Ahn       //   delegate
934ed41945fSHeejin Ahn       // post_bb: (new)
935ed41945fSHeejin Ahn       //   other_insts
936*9f770b36SHeejin Ahn       PreBB = EndBB;
937*9f770b36SHeejin Ahn       PostBB = MF.CreateMachineBasicBlock();
938ed41945fSHeejin Ahn       MF.insert(std::next(PreBB->getIterator()), PostBB);
939ed41945fSHeejin Ahn       MF.insert(std::next(PreBB->getIterator()), DelegateBB);
940ed41945fSHeejin Ahn       PostBB->splice(PostBB->end(), PreBB, SplitPos, PreBB->end());
941ed41945fSHeejin Ahn       PostBB->transferSuccessors(PreBB);
942*9f770b36SHeejin Ahn     } else {
943*9f770b36SHeejin Ahn       // - Before:
944*9f770b36SHeejin Ahn       // ehpad:
945*9f770b36SHeejin Ahn       //   range_end
946*9f770b36SHeejin Ahn       //   catch
947*9f770b36SHeejin Ahn       //   ...
948*9f770b36SHeejin Ahn       //
949*9f770b36SHeejin Ahn       // - After:
950*9f770b36SHeejin Ahn       // pre_bb: (new)
951*9f770b36SHeejin Ahn       //   range_end
952*9f770b36SHeejin Ahn       // delegate_bb: (new)
953*9f770b36SHeejin Ahn       //   delegate
954*9f770b36SHeejin Ahn       // post_bb: (previous 'ehpad')
955*9f770b36SHeejin Ahn       //   catch
956*9f770b36SHeejin Ahn       //   ...
957*9f770b36SHeejin Ahn       assert(EndBB->isEHPad());
958*9f770b36SHeejin Ahn       PreBB = MF.CreateMachineBasicBlock();
959*9f770b36SHeejin Ahn       PostBB = EndBB;
960*9f770b36SHeejin Ahn       MF.insert(PostBB->getIterator(), PreBB);
961*9f770b36SHeejin Ahn       MF.insert(PostBB->getIterator(), DelegateBB);
962*9f770b36SHeejin Ahn       PreBB->splice(PreBB->end(), PostBB, PostBB->begin(), SplitPos);
963*9f770b36SHeejin Ahn       // We don't need to transfer predecessors of the EH pad to 'PreBB',
964*9f770b36SHeejin Ahn       // because an EH pad's predecessors are all through unwind edges and they
965*9f770b36SHeejin Ahn       // should still unwind to the EH pad, not PreBB.
966*9f770b36SHeejin Ahn     }
967ed41945fSHeejin Ahn     unstackifyVRegsUsedInSplitBB(*PreBB, *PostBB);
968ed41945fSHeejin Ahn     PreBB->addSuccessor(DelegateBB);
969ed41945fSHeejin Ahn     PreBB->addSuccessor(PostBB);
970ed41945fSHeejin Ahn   }
971ed41945fSHeejin Ahn 
972ed41945fSHeejin Ahn   // Add 'delegate' instruction in the delegate BB created above.
973ed41945fSHeejin Ahn   MachineInstr *Delegate = BuildMI(DelegateBB, RangeEnd->getDebugLoc(),
974ed41945fSHeejin Ahn                                    TII.get(WebAssembly::DELEGATE))
975ed41945fSHeejin Ahn                                .addMBB(DelegateDest);
976ed41945fSHeejin Ahn   registerTryScope(Try, Delegate, nullptr);
977ed41945fSHeejin Ahn }
978ed41945fSHeejin Ahn 
979ed41945fSHeejin Ahn bool WebAssemblyCFGStackify::fixCallUnwindMismatches(MachineFunction &MF) {
980ed41945fSHeejin Ahn   // Linearizing the control flow by placing TRY / END_TRY markers can create
981ed41945fSHeejin Ahn   // mismatches in unwind destinations for throwing instructions, such as calls.
982ed41945fSHeejin Ahn   //
983ed41945fSHeejin Ahn   // We use the 'delegate' instruction to fix the unwind mismatches. 'delegate'
984ed41945fSHeejin Ahn   // instruction delegates an exception to an outer 'catch'. It can target not
985ed41945fSHeejin Ahn   // only 'catch' but all block-like structures including another 'delegate',
986ed41945fSHeejin Ahn   // but with slightly different semantics than branches. When it targets a
987ed41945fSHeejin Ahn   // 'catch', it will delegate the exception to that catch. It is being
988ed41945fSHeejin Ahn   // discussed how to define the semantics when 'delegate''s target is a non-try
989ed41945fSHeejin Ahn   // block: it will either be a validation failure or it will target the next
990ed41945fSHeejin Ahn   // outer try-catch. But anyway our LLVM backend currently does not generate
991ed41945fSHeejin Ahn   // such code. The example below illustrates where the 'delegate' instruction
992ed41945fSHeejin Ahn   // in the middle will delegate the exception to, depending on the value of N.
993ed41945fSHeejin Ahn   // try
994ed41945fSHeejin Ahn   //   try
995ed41945fSHeejin Ahn   //     block
996ed41945fSHeejin Ahn   //       try
997ed41945fSHeejin Ahn   //         try
998ed41945fSHeejin Ahn   //           call @foo
999ed41945fSHeejin Ahn   //         delegate N    ;; Where will this delegate to?
1000ed41945fSHeejin Ahn   //       catch           ;; N == 0
1001ed41945fSHeejin Ahn   //       end
1002ed41945fSHeejin Ahn   //     end               ;; N == 1 (invalid; will not be generated)
1003ed41945fSHeejin Ahn   //   delegate            ;; N == 2
1004ed41945fSHeejin Ahn   // catch                 ;; N == 3
1005ed41945fSHeejin Ahn   // end
1006ed41945fSHeejin Ahn   //                       ;; N == 4 (to caller)
1007ed41945fSHeejin Ahn 
1008ed41945fSHeejin Ahn   // 1. When an instruction may throw, but the EH pad it will unwind to can be
1009ed41945fSHeejin Ahn   //    different from the original CFG.
1010ed41945fSHeejin Ahn   //
1011ed41945fSHeejin Ahn   // Example: we have the following CFG:
1012ed41945fSHeejin Ahn   // bb0:
1013ed41945fSHeejin Ahn   //   call @foo    ; if it throws, unwind to bb2
1014ed41945fSHeejin Ahn   // bb1:
1015ed41945fSHeejin Ahn   //   call @bar    ; if it throws, unwind to bb3
1016ed41945fSHeejin Ahn   // bb2 (ehpad):
1017ed41945fSHeejin Ahn   //   catch
1018ed41945fSHeejin Ahn   //   ...
1019ed41945fSHeejin Ahn   // bb3 (ehpad)
1020ed41945fSHeejin Ahn   //   catch
1021ed41945fSHeejin Ahn   //   ...
1022ed41945fSHeejin Ahn   //
1023ed41945fSHeejin Ahn   // And the CFG is sorted in this order. Then after placing TRY markers, it
1024ed41945fSHeejin Ahn   // will look like: (BB markers are omitted)
1025ed41945fSHeejin Ahn   // try
1026ed41945fSHeejin Ahn   //   try
1027ed41945fSHeejin Ahn   //     call @foo
1028ed41945fSHeejin Ahn   //     call @bar   ;; if it throws, unwind to bb3
1029ed41945fSHeejin Ahn   //   catch         ;; ehpad (bb2)
1030ed41945fSHeejin Ahn   //     ...
1031ed41945fSHeejin Ahn   //   end_try
1032ed41945fSHeejin Ahn   // catch           ;; ehpad (bb3)
1033ed41945fSHeejin Ahn   //   ...
1034ed41945fSHeejin Ahn   // end_try
1035ed41945fSHeejin Ahn   //
1036ed41945fSHeejin Ahn   // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it
1037ed41945fSHeejin Ahn   // is supposed to end up. We solve this problem by wrapping the mismatching
1038ed41945fSHeejin Ahn   // call with an inner try-delegate that rethrows the exception to the right
1039ed41945fSHeejin Ahn   // 'catch'.
1040ed41945fSHeejin Ahn   //
1041ed41945fSHeejin Ahn   // try
1042ed41945fSHeejin Ahn   //   try
1043ed41945fSHeejin Ahn   //     call @foo
1044ed41945fSHeejin Ahn   //     try               ;; (new)
1045ed41945fSHeejin Ahn   //       call @bar
1046ed41945fSHeejin Ahn   //     delegate 1 (bb3)  ;; (new)
1047ed41945fSHeejin Ahn   //   catch               ;; ehpad (bb2)
1048ed41945fSHeejin Ahn   //     ...
1049ed41945fSHeejin Ahn   //   end_try
1050ed41945fSHeejin Ahn   // catch                 ;; ehpad (bb3)
1051ed41945fSHeejin Ahn   //   ...
1052ed41945fSHeejin Ahn   // end_try
1053ed41945fSHeejin Ahn   //
1054ed41945fSHeejin Ahn   // ---
1055ed41945fSHeejin Ahn   // 2. The same as 1, but in this case an instruction unwinds to a caller
1056ed41945fSHeejin Ahn   //    function and not another EH pad.
1057ed41945fSHeejin Ahn   //
1058ed41945fSHeejin Ahn   // Example: we have the following CFG:
1059ed41945fSHeejin Ahn   // bb0:
1060ed41945fSHeejin Ahn   //   call @foo       ; if it throws, unwind to bb2
1061ed41945fSHeejin Ahn   // bb1:
1062ed41945fSHeejin Ahn   //   call @bar       ; if it throws, unwind to caller
1063ed41945fSHeejin Ahn   // bb2 (ehpad):
1064ed41945fSHeejin Ahn   //   catch
1065ed41945fSHeejin Ahn   //   ...
1066ed41945fSHeejin Ahn   //
1067ed41945fSHeejin Ahn   // And the CFG is sorted in this order. Then after placing TRY markers, it
1068ed41945fSHeejin Ahn   // will look like:
1069ed41945fSHeejin Ahn   // try
1070ed41945fSHeejin Ahn   //   call @foo
1071ed41945fSHeejin Ahn   //   call @bar     ;; if it throws, unwind to caller
1072ed41945fSHeejin Ahn   // catch           ;; ehpad (bb2)
1073ed41945fSHeejin Ahn   //   ...
1074ed41945fSHeejin Ahn   // end_try
1075ed41945fSHeejin Ahn   //
1076ed41945fSHeejin Ahn   // Now if bar() throws, it is going to end up ip in bb2, when it is supposed
1077ed41945fSHeejin Ahn   // throw up to the caller. We solve this problem in the same way, but in this
1078ed41945fSHeejin Ahn   // case 'delegate's immediate argument is the number of block depths + 1,
1079ed41945fSHeejin Ahn   // which means it rethrows to the caller.
1080ed41945fSHeejin Ahn   // try
1081ed41945fSHeejin Ahn   //   call @foo
1082ed41945fSHeejin Ahn   //   try                  ;; (new)
1083ed41945fSHeejin Ahn   //     call @bar
1084ed41945fSHeejin Ahn   //   delegate 1 (caller)  ;; (new)
1085ed41945fSHeejin Ahn   // catch                  ;; ehpad (bb2)
1086ed41945fSHeejin Ahn   //   ...
1087ed41945fSHeejin Ahn   // end_try
1088ed41945fSHeejin Ahn   //
1089ed41945fSHeejin Ahn   // Before rewriteDepthImmediates, delegate's argument is a BB. In case of the
1090ed41945fSHeejin Ahn   // caller, it will take a fake BB generated by getFakeCallerBlock(), which
1091ed41945fSHeejin Ahn   // will be converted to a correct immediate argument later.
1092ed41945fSHeejin Ahn   //
1093ed41945fSHeejin Ahn   // In case there are multiple calls in a BB that may throw to the caller, they
1094ed41945fSHeejin Ahn   // can be wrapped together in one nested try-delegate scope. (In 1, this
1095ed41945fSHeejin Ahn   // couldn't happen, because may-throwing instruction there had an unwind
1096ed41945fSHeejin Ahn   // destination, i.e., it was an invoke before, and there could be only one
1097ed41945fSHeejin Ahn   // invoke within a BB.)
1098ed41945fSHeejin Ahn 
1099ed41945fSHeejin Ahn   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
1100ed41945fSHeejin Ahn   // Range of intructions to be wrapped in a new nested try/catch. A range
1101ed41945fSHeejin Ahn   // exists in a single BB and does not span multiple BBs.
1102ed41945fSHeejin Ahn   using TryRange = std::pair<MachineInstr *, MachineInstr *>;
1103ed41945fSHeejin Ahn   // In original CFG, <unwind destination BB, a vector of try ranges>
1104ed41945fSHeejin Ahn   DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges;
1105ed41945fSHeejin Ahn 
1106ed41945fSHeejin Ahn   // Gather possibly throwing calls (i.e., previously invokes) whose current
1107ed41945fSHeejin Ahn   // unwind destination is not the same as the original CFG. (Case 1)
1108ed41945fSHeejin Ahn 
1109ed41945fSHeejin Ahn   for (auto &MBB : reverse(MF)) {
1110ed41945fSHeejin Ahn     bool SeenThrowableInstInBB = false;
1111ed41945fSHeejin Ahn     for (auto &MI : reverse(MBB)) {
1112ed41945fSHeejin Ahn       if (MI.getOpcode() == WebAssembly::TRY)
1113ed41945fSHeejin Ahn         EHPadStack.pop_back();
1114ed41945fSHeejin Ahn       else if (WebAssembly::isCatch(MI.getOpcode()))
1115ed41945fSHeejin Ahn         EHPadStack.push_back(MI.getParent());
1116ed41945fSHeejin Ahn 
1117ed41945fSHeejin Ahn       // In this loop we only gather calls that have an EH pad to unwind. So
1118ed41945fSHeejin Ahn       // there will be at most 1 such call (= invoke) in a BB, so after we've
1119ed41945fSHeejin Ahn       // seen one, we can skip the rest of BB. Also if MBB has no EH pad
1120ed41945fSHeejin Ahn       // successor or MI does not throw, this is not an invoke.
1121ed41945fSHeejin Ahn       if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() ||
1122ed41945fSHeejin Ahn           !WebAssembly::mayThrow(MI))
1123ed41945fSHeejin Ahn         continue;
1124ed41945fSHeejin Ahn       SeenThrowableInstInBB = true;
1125ed41945fSHeejin Ahn 
1126ed41945fSHeejin Ahn       // If the EH pad on the stack top is where this instruction should unwind
1127ed41945fSHeejin Ahn       // next, we're good.
1128ed41945fSHeejin Ahn       MachineBasicBlock *UnwindDest = getFakeCallerBlock(MF);
1129ed41945fSHeejin Ahn       for (auto *Succ : MBB.successors()) {
1130ed41945fSHeejin Ahn         // Even though semantically a BB can have multiple successors in case an
1131ed41945fSHeejin Ahn         // exception is not caught by a catchpad, in our backend implementation
1132ed41945fSHeejin Ahn         // it is guaranteed that a BB can have at most one EH pad successor. For
1133ed41945fSHeejin Ahn         // details, refer to comments in findWasmUnwindDestinations function in
1134ed41945fSHeejin Ahn         // SelectionDAGBuilder.cpp.
1135ed41945fSHeejin Ahn         if (Succ->isEHPad()) {
1136ed41945fSHeejin Ahn           UnwindDest = Succ;
1137ed41945fSHeejin Ahn           break;
1138ed41945fSHeejin Ahn         }
1139ed41945fSHeejin Ahn       }
1140ed41945fSHeejin Ahn       if (EHPadStack.back() == UnwindDest)
1141ed41945fSHeejin Ahn         continue;
1142ed41945fSHeejin Ahn 
1143ed41945fSHeejin Ahn       // Include EH_LABELs in the range before and afer the invoke
1144ed41945fSHeejin Ahn       MachineInstr *RangeBegin = &MI, *RangeEnd = &MI;
1145ed41945fSHeejin Ahn       if (RangeBegin->getIterator() != MBB.begin() &&
1146ed41945fSHeejin Ahn           std::prev(RangeBegin->getIterator())->isEHLabel())
1147ed41945fSHeejin Ahn         RangeBegin = &*std::prev(RangeBegin->getIterator());
1148ed41945fSHeejin Ahn       if (std::next(RangeEnd->getIterator()) != MBB.end() &&
1149ed41945fSHeejin Ahn           std::next(RangeEnd->getIterator())->isEHLabel())
1150ed41945fSHeejin Ahn         RangeEnd = &*std::next(RangeEnd->getIterator());
1151ed41945fSHeejin Ahn 
1152ed41945fSHeejin Ahn       // If not, record the range.
1153ed41945fSHeejin Ahn       UnwindDestToTryRanges[UnwindDest].push_back(
1154ed41945fSHeejin Ahn           TryRange(RangeBegin, RangeEnd));
1155ed41945fSHeejin Ahn       LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = " << MBB.getName()
1156ed41945fSHeejin Ahn                         << "\nCall = " << MI
1157ed41945fSHeejin Ahn                         << "\nOriginal dest = " << UnwindDest->getName()
1158ed41945fSHeejin Ahn                         << "  Current dest = " << EHPadStack.back()->getName()
1159ed41945fSHeejin Ahn                         << "\n\n");
1160ed41945fSHeejin Ahn     }
1161ed41945fSHeejin Ahn   }
1162ed41945fSHeejin Ahn 
1163ed41945fSHeejin Ahn   assert(EHPadStack.empty());
1164ed41945fSHeejin Ahn 
1165ed41945fSHeejin Ahn   // Gather possibly throwing calls that are supposed to unwind up to the caller
1166ed41945fSHeejin Ahn   // if they throw, but currently unwind to an incorrect destination. Unlike the
1167ed41945fSHeejin Ahn   // loop above, there can be multiple calls within a BB that unwind to the
1168ed41945fSHeejin Ahn   // caller, which we should group together in a range. (Case 2)
1169ed41945fSHeejin Ahn 
1170ed41945fSHeejin Ahn   MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive
1171ed41945fSHeejin Ahn 
1172ed41945fSHeejin Ahn   // Record the range.
1173ed41945fSHeejin Ahn   auto RecordCallerMismatchRange = [&](const MachineBasicBlock *CurrentDest) {
1174ed41945fSHeejin Ahn     UnwindDestToTryRanges[getFakeCallerBlock(MF)].push_back(
1175ed41945fSHeejin Ahn         TryRange(RangeBegin, RangeEnd));
1176ed41945fSHeejin Ahn     LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = "
1177ed41945fSHeejin Ahn                       << RangeBegin->getParent()->getName()
1178ed41945fSHeejin Ahn                       << "\nRange begin = " << *RangeBegin
1179ed41945fSHeejin Ahn                       << "Range end = " << *RangeEnd
1180ed41945fSHeejin Ahn                       << "\nOriginal dest = caller  Current dest = "
1181ed41945fSHeejin Ahn                       << CurrentDest->getName() << "\n\n");
1182ed41945fSHeejin Ahn     RangeBegin = RangeEnd = nullptr; // Reset range pointers
1183ed41945fSHeejin Ahn   };
1184ed41945fSHeejin Ahn 
1185ed41945fSHeejin Ahn   for (auto &MBB : reverse(MF)) {
1186ed41945fSHeejin Ahn     bool SeenThrowableInstInBB = false;
1187ed41945fSHeejin Ahn     for (auto &MI : reverse(MBB)) {
1188ed41945fSHeejin Ahn       if (MI.getOpcode() == WebAssembly::TRY)
1189ed41945fSHeejin Ahn         EHPadStack.pop_back();
1190ed41945fSHeejin Ahn       else if (WebAssembly::isCatch(MI.getOpcode()))
1191ed41945fSHeejin Ahn         EHPadStack.push_back(MI.getParent());
1192ed41945fSHeejin Ahn       bool MayThrow = WebAssembly::mayThrow(MI);
1193ed41945fSHeejin Ahn 
1194ed41945fSHeejin Ahn       // If MBB has an EH pad successor and this is the last instruction that
1195ed41945fSHeejin Ahn       // may throw, this instruction unwinds to the EH pad and not to the
1196ed41945fSHeejin Ahn       // caller.
1197ed41945fSHeejin Ahn       if (MBB.hasEHPadSuccessor() && MayThrow && !SeenThrowableInstInBB) {
1198ed41945fSHeejin Ahn         SeenThrowableInstInBB = true;
1199ed41945fSHeejin Ahn         continue;
1200ed41945fSHeejin Ahn       }
1201ed41945fSHeejin Ahn 
1202ed41945fSHeejin Ahn       // We wrap up the current range when we see a marker even if we haven't
1203ed41945fSHeejin Ahn       // finished a BB.
1204ed41945fSHeejin Ahn       if (RangeEnd && WebAssembly::isMarker(MI.getOpcode())) {
1205ed41945fSHeejin Ahn         RecordCallerMismatchRange(EHPadStack.back());
1206ed41945fSHeejin Ahn         continue;
1207ed41945fSHeejin Ahn       }
1208ed41945fSHeejin Ahn 
1209ed41945fSHeejin Ahn       // If EHPadStack is empty, that means it correctly unwinds to the caller
1210ed41945fSHeejin Ahn       // if it throws, so we're good. If MI does not throw, we're good too.
1211ed41945fSHeejin Ahn       if (EHPadStack.empty() || !MayThrow)
1212ed41945fSHeejin Ahn         continue;
1213ed41945fSHeejin Ahn 
1214ed41945fSHeejin Ahn       // We found an instruction that unwinds to the caller but currently has an
1215ed41945fSHeejin Ahn       // incorrect unwind destination. Create a new range or increment the
1216ed41945fSHeejin Ahn       // currently existing range.
1217ed41945fSHeejin Ahn       if (!RangeEnd)
1218ed41945fSHeejin Ahn         RangeBegin = RangeEnd = &MI;
1219ed41945fSHeejin Ahn       else
1220ed41945fSHeejin Ahn         RangeBegin = &MI;
1221ed41945fSHeejin Ahn     }
1222ed41945fSHeejin Ahn 
1223ed41945fSHeejin Ahn     if (RangeEnd)
1224ed41945fSHeejin Ahn       RecordCallerMismatchRange(EHPadStack.back());
1225ed41945fSHeejin Ahn   }
1226ed41945fSHeejin Ahn 
1227ed41945fSHeejin Ahn   assert(EHPadStack.empty());
1228ed41945fSHeejin Ahn 
1229ed41945fSHeejin Ahn   // We don't have any unwind destination mismatches to resolve.
1230ed41945fSHeejin Ahn   if (UnwindDestToTryRanges.empty())
1231ed41945fSHeejin Ahn     return false;
1232ed41945fSHeejin Ahn 
1233ed41945fSHeejin Ahn   // Now we fix the mismatches by wrapping calls with inner try-delegates.
1234ed41945fSHeejin Ahn   for (auto &P : UnwindDestToTryRanges) {
1235ed41945fSHeejin Ahn     NumCallUnwindMismatches += P.second.size();
1236ed41945fSHeejin Ahn     MachineBasicBlock *UnwindDest = P.first;
1237ed41945fSHeejin Ahn     auto &TryRanges = P.second;
1238ed41945fSHeejin Ahn 
1239ed41945fSHeejin Ahn     for (auto Range : TryRanges) {
1240ed41945fSHeejin Ahn       MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr;
1241ed41945fSHeejin Ahn       std::tie(RangeBegin, RangeEnd) = Range;
1242ed41945fSHeejin Ahn       auto *MBB = RangeBegin->getParent();
1243ed41945fSHeejin Ahn 
1244ed41945fSHeejin Ahn       // If this BB has an EH pad successor, i.e., ends with an 'invoke', now we
1245ed41945fSHeejin Ahn       // are going to wrap the invoke with try-delegate, making the 'delegate'
1246ed41945fSHeejin Ahn       // BB the new successor instead, so remove the EH pad succesor here. The
1247ed41945fSHeejin Ahn       // BB may not have an EH pad successor if calls in this BB throw to the
1248ed41945fSHeejin Ahn       // caller.
1249ed41945fSHeejin Ahn       MachineBasicBlock *EHPad = nullptr;
1250ed41945fSHeejin Ahn       for (auto *Succ : MBB->successors()) {
1251ed41945fSHeejin Ahn         if (Succ->isEHPad()) {
1252ed41945fSHeejin Ahn           EHPad = Succ;
1253ed41945fSHeejin Ahn           break;
1254ed41945fSHeejin Ahn         }
1255ed41945fSHeejin Ahn       }
1256ed41945fSHeejin Ahn       if (EHPad)
1257ed41945fSHeejin Ahn         MBB->removeSuccessor(EHPad);
1258ed41945fSHeejin Ahn 
1259ed41945fSHeejin Ahn       addTryDelegate(RangeBegin, RangeEnd, UnwindDest);
1260ed41945fSHeejin Ahn     }
1261ed41945fSHeejin Ahn   }
1262ed41945fSHeejin Ahn 
1263ed41945fSHeejin Ahn   return true;
1264ed41945fSHeejin Ahn }
1265ed41945fSHeejin Ahn 
1266ed41945fSHeejin Ahn bool WebAssemblyCFGStackify::fixCatchUnwindMismatches(MachineFunction &MF) {
1267*9f770b36SHeejin Ahn   // There is another kind of unwind destination mismatches besides call unwind
1268*9f770b36SHeejin Ahn   // mismatches, which we will call "catch unwind mismatches". See this example
1269*9f770b36SHeejin Ahn   // after the marker placement:
1270*9f770b36SHeejin Ahn   // try
1271*9f770b36SHeejin Ahn   //   try
1272*9f770b36SHeejin Ahn   //     call @foo
1273*9f770b36SHeejin Ahn   //   catch __cpp_exception  ;; ehpad A (next unwind dest: caller)
1274*9f770b36SHeejin Ahn   //     ...
1275*9f770b36SHeejin Ahn   //   end_try
1276*9f770b36SHeejin Ahn   // catch_all                ;; ehpad B
1277*9f770b36SHeejin Ahn   //   ...
1278*9f770b36SHeejin Ahn   // end_try
1279*9f770b36SHeejin Ahn   //
1280*9f770b36SHeejin Ahn   // 'call @foo's unwind destination is the ehpad A. But suppose 'call @foo'
1281*9f770b36SHeejin Ahn   // throws a foreign exception that is not caught by ehpad A, and its next
1282*9f770b36SHeejin Ahn   // destination should be the caller. But after control flow linearization,
1283*9f770b36SHeejin Ahn   // another EH pad can be placed in between (e.g. ehpad B here), making the
1284*9f770b36SHeejin Ahn   // next unwind destination incorrect. In this case, the  foreign exception
1285*9f770b36SHeejin Ahn   // will instead go to ehpad B and will be caught there instead. In this
1286*9f770b36SHeejin Ahn   // example the correct next unwind destination is the caller, but it can be
1287*9f770b36SHeejin Ahn   // another outer catch in other cases.
1288*9f770b36SHeejin Ahn   //
1289*9f770b36SHeejin Ahn   // There is no specific 'call' or 'throw' instruction to wrap with a
1290*9f770b36SHeejin Ahn   // try-delegate, so we wrap the whole try-catch-end with a try-delegate and
1291*9f770b36SHeejin Ahn   // make it rethrow to the right destination, as in the example below:
1292*9f770b36SHeejin Ahn   // try
1293*9f770b36SHeejin Ahn   //   try                     ;; (new)
1294*9f770b36SHeejin Ahn   //     try
1295*9f770b36SHeejin Ahn   //       call @foo
1296*9f770b36SHeejin Ahn   //     catch __cpp_exception ;; ehpad A (next unwind dest: caller)
1297*9f770b36SHeejin Ahn   //       ...
1298*9f770b36SHeejin Ahn   //     end_try
1299*9f770b36SHeejin Ahn   //   delegate 1 (caller)     ;; (new)
1300*9f770b36SHeejin Ahn   // catch_all                 ;; ehpad B
1301*9f770b36SHeejin Ahn   //   ...
1302*9f770b36SHeejin Ahn   // end_try
1303*9f770b36SHeejin Ahn 
1304*9f770b36SHeejin Ahn   const auto *EHInfo = MF.getWasmEHFuncInfo();
1305*9f770b36SHeejin Ahn   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
1306*9f770b36SHeejin Ahn   // For EH pads that have catch unwind mismatches, a map of <EH pad, its
1307*9f770b36SHeejin Ahn   // correct unwind destination>.
1308*9f770b36SHeejin Ahn   DenseMap<MachineBasicBlock *, MachineBasicBlock *> EHPadToUnwindDest;
1309*9f770b36SHeejin Ahn 
1310*9f770b36SHeejin Ahn   for (auto &MBB : reverse(MF)) {
1311*9f770b36SHeejin Ahn     for (auto &MI : reverse(MBB)) {
1312*9f770b36SHeejin Ahn       if (MI.getOpcode() == WebAssembly::TRY)
1313*9f770b36SHeejin Ahn         EHPadStack.pop_back();
1314*9f770b36SHeejin Ahn       else if (MI.getOpcode() == WebAssembly::DELEGATE)
1315*9f770b36SHeejin Ahn         EHPadStack.push_back(&MBB);
1316*9f770b36SHeejin Ahn       else if (WebAssembly::isCatch(MI.getOpcode())) {
1317*9f770b36SHeejin Ahn         auto *EHPad = &MBB;
1318*9f770b36SHeejin Ahn 
1319*9f770b36SHeejin Ahn         // catch_all always catches an exception, so we don't need to do
1320*9f770b36SHeejin Ahn         // anything
1321*9f770b36SHeejin Ahn         if (MI.getOpcode() == WebAssembly::CATCH_ALL) {
1322*9f770b36SHeejin Ahn         }
1323*9f770b36SHeejin Ahn 
1324*9f770b36SHeejin Ahn         // This can happen when the unwind dest was removed during the
1325*9f770b36SHeejin Ahn         // optimization, e.g. because it was unreachable.
1326*9f770b36SHeejin Ahn         else if (EHPadStack.empty() && EHInfo->hasEHPadUnwindDest(EHPad)) {
1327*9f770b36SHeejin Ahn           LLVM_DEBUG(dbgs() << "EHPad (" << EHPad->getName()
1328*9f770b36SHeejin Ahn                             << "'s unwind destination does not exist anymore"
1329*9f770b36SHeejin Ahn                             << "\n\n");
1330*9f770b36SHeejin Ahn         }
1331*9f770b36SHeejin Ahn 
1332*9f770b36SHeejin Ahn         // The EHPad's next unwind destination is the caller, but we incorrectly
1333*9f770b36SHeejin Ahn         // unwind to another EH pad.
1334*9f770b36SHeejin Ahn         else if (!EHPadStack.empty() && !EHInfo->hasEHPadUnwindDest(EHPad)) {
1335*9f770b36SHeejin Ahn           EHPadToUnwindDest[EHPad] = getFakeCallerBlock(MF);
1336*9f770b36SHeejin Ahn           LLVM_DEBUG(dbgs()
1337*9f770b36SHeejin Ahn                      << "- Catch unwind mismatch:\nEHPad = " << EHPad->getName()
1338*9f770b36SHeejin Ahn                      << "  Original dest = caller  Current dest = "
1339*9f770b36SHeejin Ahn                      << EHPadStack.back()->getName() << "\n\n");
1340*9f770b36SHeejin Ahn         }
1341*9f770b36SHeejin Ahn 
1342*9f770b36SHeejin Ahn         // The EHPad's next unwind destination is an EH pad, whereas we
1343*9f770b36SHeejin Ahn         // incorrectly unwind to another EH pad.
1344*9f770b36SHeejin Ahn         else if (!EHPadStack.empty() && EHInfo->hasEHPadUnwindDest(EHPad)) {
1345*9f770b36SHeejin Ahn           auto *UnwindDest = EHInfo->getEHPadUnwindDest(EHPad);
1346*9f770b36SHeejin Ahn           if (EHPadStack.back() != UnwindDest) {
1347*9f770b36SHeejin Ahn             EHPadToUnwindDest[EHPad] = UnwindDest;
1348*9f770b36SHeejin Ahn             LLVM_DEBUG(dbgs() << "- Catch unwind mismatch:\nEHPad = "
1349*9f770b36SHeejin Ahn                               << EHPad->getName() << "  Original dest = "
1350*9f770b36SHeejin Ahn                               << UnwindDest->getName() << "  Current dest = "
1351*9f770b36SHeejin Ahn                               << EHPadStack.back()->getName() << "\n\n");
1352*9f770b36SHeejin Ahn           }
1353*9f770b36SHeejin Ahn         }
1354*9f770b36SHeejin Ahn 
1355*9f770b36SHeejin Ahn         EHPadStack.push_back(EHPad);
1356*9f770b36SHeejin Ahn       }
1357*9f770b36SHeejin Ahn     }
1358*9f770b36SHeejin Ahn   }
1359*9f770b36SHeejin Ahn 
1360*9f770b36SHeejin Ahn   assert(EHPadStack.empty());
1361*9f770b36SHeejin Ahn   if (EHPadToUnwindDest.empty())
1362c4ac74fbSHeejin Ahn     return false;
1363*9f770b36SHeejin Ahn   NumCatchUnwindMismatches += EHPadToUnwindDest.size();
1364*9f770b36SHeejin Ahn 
1365*9f770b36SHeejin Ahn   for (auto &P : EHPadToUnwindDest) {
1366*9f770b36SHeejin Ahn     MachineBasicBlock *EHPad = P.first;
1367*9f770b36SHeejin Ahn     MachineBasicBlock *UnwindDest = P.second;
1368*9f770b36SHeejin Ahn     MachineInstr *Try = EHPadToTry[EHPad];
1369*9f770b36SHeejin Ahn     MachineInstr *EndTry = BeginToEnd[Try];
1370*9f770b36SHeejin Ahn     addTryDelegate(Try, EndTry, UnwindDest);
1371*9f770b36SHeejin Ahn   }
1372*9f770b36SHeejin Ahn 
1373*9f770b36SHeejin Ahn   return true;
1374c4ac74fbSHeejin Ahn }
1375c4ac74fbSHeejin Ahn 
1376ed41945fSHeejin Ahn void WebAssemblyCFGStackify::recalculateScopeTops(MachineFunction &MF) {
1377ed41945fSHeejin Ahn   // Renumber BBs and recalculate ScopeTop info because new BBs might have been
1378ed41945fSHeejin Ahn   // created and inserted during fixing unwind mismatches.
1379ed41945fSHeejin Ahn   MF.RenumberBlocks();
1380ed41945fSHeejin Ahn   ScopeTops.clear();
1381ed41945fSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs());
1382ed41945fSHeejin Ahn   for (auto &MBB : reverse(MF)) {
1383ed41945fSHeejin Ahn     for (auto &MI : reverse(MBB)) {
1384ed41945fSHeejin Ahn       if (ScopeTops[MBB.getNumber()])
1385ed41945fSHeejin Ahn         break;
1386ed41945fSHeejin Ahn       switch (MI.getOpcode()) {
1387ed41945fSHeejin Ahn       case WebAssembly::END_BLOCK:
1388ed41945fSHeejin Ahn       case WebAssembly::END_LOOP:
1389ed41945fSHeejin Ahn       case WebAssembly::END_TRY:
1390ed41945fSHeejin Ahn       case WebAssembly::DELEGATE:
1391ed41945fSHeejin Ahn         updateScopeTops(EndToBegin[&MI]->getParent(), &MBB);
1392ed41945fSHeejin Ahn         break;
1393ed41945fSHeejin Ahn       case WebAssembly::CATCH:
1394ed41945fSHeejin Ahn       case WebAssembly::CATCH_ALL:
1395ed41945fSHeejin Ahn         updateScopeTops(EHPadToTry[&MBB]->getParent(), &MBB);
1396ed41945fSHeejin Ahn         break;
1397ed41945fSHeejin Ahn       }
1398ed41945fSHeejin Ahn     }
1399ed41945fSHeejin Ahn   }
1400ed41945fSHeejin Ahn }
1401ed41945fSHeejin Ahn 
1402ed41945fSHeejin Ahn unsigned WebAssemblyCFGStackify::getDepth(
1403ed41945fSHeejin Ahn     const SmallVectorImpl<const MachineBasicBlock *> &Stack,
14041d68e80fSDan Gohman     const MachineBasicBlock *MBB) {
1405ed41945fSHeejin Ahn   if (MBB == FakeCallerBB)
1406ed41945fSHeejin Ahn     return Stack.size();
14071d68e80fSDan Gohman   unsigned Depth = 0;
14081d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
14091d68e80fSDan Gohman     if (X == MBB)
14101d68e80fSDan Gohman       break;
14111d68e80fSDan Gohman     ++Depth;
14121d68e80fSDan Gohman   }
14131d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
14141d68e80fSDan Gohman   return Depth;
14151d68e80fSDan Gohman }
14161d68e80fSDan Gohman 
14172726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
14182726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
14192726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
14202726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
14212726b88cSDan Gohman /// that end at the function end need to have a return type signature that
14222726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
14232726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
1424e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
1425e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
14262726b88cSDan Gohman 
14272726b88cSDan Gohman   if (MFI.getResults().empty())
14282726b88cSDan Gohman     return;
14292726b88cSDan Gohman 
14302cb27072SThomas Lively   // MCInstLower will add the proper types to multivalue signatures based on the
14312cb27072SThomas Lively   // function return type
14322cb27072SThomas Lively   WebAssembly::BlockType RetType =
14332cb27072SThomas Lively       MFI.getResults().size() > 1
14342cb27072SThomas Lively           ? WebAssembly::BlockType::Multivalue
14352cb27072SThomas Lively           : WebAssembly::BlockType(
14362cb27072SThomas Lively                 WebAssembly::toValType(MFI.getResults().front()));
14372726b88cSDan Gohman 
1438d25c17f3SHeejin Ahn   SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist;
1439d25c17f3SHeejin Ahn   Worklist.push_back(MF.rbegin()->rbegin());
1440d25c17f3SHeejin Ahn 
1441d25c17f3SHeejin Ahn   auto Process = [&](MachineBasicBlock::reverse_iterator It) {
1442d25c17f3SHeejin Ahn     auto *MBB = It->getParent();
1443d25c17f3SHeejin Ahn     while (It != MBB->rend()) {
1444d25c17f3SHeejin Ahn       MachineInstr &MI = *It++;
1445801bf7ebSShiva Chen       if (MI.isPosition() || MI.isDebugInstr())
14462726b88cSDan Gohman         continue;
14472cb27072SThomas Lively       switch (MI.getOpcode()) {
1448d25c17f3SHeejin Ahn       case WebAssembly::END_TRY: {
1449d25c17f3SHeejin Ahn         // If a 'try''s return type is fixed, both its try body and catch body
1450d25c17f3SHeejin Ahn         // should satisfy the return type, so we need to search 'end'
1451d25c17f3SHeejin Ahn         // instructions before its corresponding 'catch' too.
1452d25c17f3SHeejin Ahn         auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
1453d25c17f3SHeejin Ahn         assert(EHPad);
14549f8b2576SHeejin Ahn         auto NextIt =
14559f8b2576SHeejin Ahn             std::next(WebAssembly::findCatch(EHPad)->getReverseIterator());
14569f8b2576SHeejin Ahn         if (NextIt != EHPad->rend())
14579f8b2576SHeejin Ahn           Worklist.push_back(NextIt);
1458d25c17f3SHeejin Ahn         LLVM_FALLTHROUGH;
1459d25c17f3SHeejin Ahn       }
14602cb27072SThomas Lively       case WebAssembly::END_BLOCK:
14612cb27072SThomas Lively       case WebAssembly::END_LOOP:
146218c56a07SHeejin Ahn         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
14632726b88cSDan Gohman         continue;
14642cb27072SThomas Lively       default:
1465d25c17f3SHeejin Ahn         // Something other than an `end`. We're done for this BB.
14662726b88cSDan Gohman         return;
14672726b88cSDan Gohman       }
14682726b88cSDan Gohman     }
1469d25c17f3SHeejin Ahn     // We've reached the beginning of a BB. Continue the search in the previous
1470d25c17f3SHeejin Ahn     // BB.
1471d25c17f3SHeejin Ahn     Worklist.push_back(MBB->getPrevNode()->rbegin());
1472d25c17f3SHeejin Ahn   };
1473d25c17f3SHeejin Ahn 
1474d25c17f3SHeejin Ahn   while (!Worklist.empty())
1475d25c17f3SHeejin Ahn     Process(Worklist.pop_back_val());
14762cb27072SThomas Lively }
14772726b88cSDan Gohman 
1478d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
1479d934cb88SDan Gohman // were a block.
148018c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF,
1481d934cb88SDan Gohman                                 const WebAssemblyInstrInfo &TII) {
148210b31358SDerek Schuff   BuildMI(MF.back(), MF.back().end(),
148310b31358SDerek Schuff           MF.back().findPrevDebugLoc(MF.back().end()),
1484d934cb88SDan Gohman           TII.get(WebAssembly::END_FUNCTION));
1485d934cb88SDan Gohman }
1486d934cb88SDan Gohman 
1487e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places.
1488e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
1489e76fa9ecSHeejin Ahn   // We allocate one more than the number of blocks in the function to
1490e76fa9ecSHeejin Ahn   // accommodate for the possible fake block we may insert at the end.
1491e76fa9ecSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs() + 1);
14928fe7e86bSDan Gohman   // Place the LOOP for MBB if MBB is the header of a loop.
1493e76fa9ecSHeejin Ahn   for (auto &MBB : MF)
1494e76fa9ecSHeejin Ahn     placeLoopMarker(MBB);
149544a5a4b1SHeejin Ahn 
1496d6f48786SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
149744a5a4b1SHeejin Ahn   for (auto &MBB : MF) {
149844a5a4b1SHeejin Ahn     if (MBB.isEHPad()) {
149944a5a4b1SHeejin Ahn       // Place the TRY for MBB if MBB is the EH pad of an exception.
1500e76fa9ecSHeejin Ahn       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1501e76fa9ecSHeejin Ahn           MF.getFunction().hasPersonalityFn())
1502e76fa9ecSHeejin Ahn         placeTryMarker(MBB);
150344a5a4b1SHeejin Ahn     } else {
150432807932SDan Gohman       // Place the BLOCK for MBB if MBB is branched to from above.
1505e76fa9ecSHeejin Ahn       placeBlockMarker(MBB);
1506950a13cfSDan Gohman     }
150744a5a4b1SHeejin Ahn   }
1508c4ac74fbSHeejin Ahn   // Fix mismatches in unwind destinations induced by linearizing the code.
1509daeead4bSHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1510ed41945fSHeejin Ahn       MF.getFunction().hasPersonalityFn()) {
1511ed41945fSHeejin Ahn     bool Changed = fixCallUnwindMismatches(MF);
1512ed41945fSHeejin Ahn     Changed |= fixCatchUnwindMismatches(MF);
1513ed41945fSHeejin Ahn     if (Changed)
1514ed41945fSHeejin Ahn       recalculateScopeTops(MF);
1515ed41945fSHeejin Ahn   }
151644a5a4b1SHeejin Ahn }
1517950a13cfSDan Gohman 
1518e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
15191d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
15201d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
1521ed41945fSHeejin Ahn   SmallVector<const MachineBasicBlock *, 8> DelegateStack;
15221d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
1523e76fa9ecSHeejin Ahn     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) {
1524e76fa9ecSHeejin Ahn       MachineInstr &MI = *I;
15251d68e80fSDan Gohman       switch (MI.getOpcode()) {
15261d68e80fSDan Gohman       case WebAssembly::BLOCK:
1527e76fa9ecSHeejin Ahn       case WebAssembly::TRY:
1528e76fa9ecSHeejin Ahn         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <=
1529e76fa9ecSHeejin Ahn                    MBB.getNumber() &&
1530e76fa9ecSHeejin Ahn                "Block/try marker should be balanced");
1531e76fa9ecSHeejin Ahn         Stack.pop_back();
1532ed41945fSHeejin Ahn         DelegateStack.pop_back();
1533e76fa9ecSHeejin Ahn         break;
1534e76fa9ecSHeejin Ahn 
15351d68e80fSDan Gohman       case WebAssembly::LOOP:
15361d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
15371d68e80fSDan Gohman         Stack.pop_back();
1538ed41945fSHeejin Ahn         DelegateStack.pop_back();
15391d68e80fSDan Gohman         break;
1540e76fa9ecSHeejin Ahn 
15411d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
1542ed41945fSHeejin Ahn         Stack.push_back(&MBB);
1543ed41945fSHeejin Ahn         DelegateStack.push_back(&MBB);
1544ed41945fSHeejin Ahn         break;
1545ed41945fSHeejin Ahn 
1546e76fa9ecSHeejin Ahn       case WebAssembly::END_TRY:
1547ed41945fSHeejin Ahn         // We handle DELEGATE in the default level, because DELEGATE has
1548ed41945fSHeejin Ahn         // immediate operands to rewirte.
15491d68e80fSDan Gohman         Stack.push_back(&MBB);
15501d68e80fSDan Gohman         break;
1551e76fa9ecSHeejin Ahn 
15521d68e80fSDan Gohman       case WebAssembly::END_LOOP:
1553e76fa9ecSHeejin Ahn         Stack.push_back(EndToBegin[&MI]->getParent());
1554ed41945fSHeejin Ahn         DelegateStack.push_back(EndToBegin[&MI]->getParent());
1555ed41945fSHeejin Ahn         break;
1556ed41945fSHeejin Ahn 
1557ed41945fSHeejin Ahn       case WebAssembly::CATCH:
1558ed41945fSHeejin Ahn       case WebAssembly::CATCH_ALL:
1559ed41945fSHeejin Ahn         DelegateStack.push_back(&MBB);
15601d68e80fSDan Gohman         break;
1561e76fa9ecSHeejin Ahn 
15621d68e80fSDan Gohman       default:
15631d68e80fSDan Gohman         if (MI.isTerminator()) {
15641d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
15651d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
15661d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
15671d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
15681d68e80fSDan Gohman           for (auto MO : Ops) {
1569ed41945fSHeejin Ahn             if (MO.isMBB()) {
1570ed41945fSHeejin Ahn               if (MI.getOpcode() == WebAssembly::DELEGATE)
1571ed41945fSHeejin Ahn                 MO = MachineOperand::CreateImm(
1572ed41945fSHeejin Ahn                     getDepth(DelegateStack, MO.getMBB()));
1573ed41945fSHeejin Ahn               else
157418c56a07SHeejin Ahn                 MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB()));
1575ed41945fSHeejin Ahn             }
15761d68e80fSDan Gohman             MI.addOperand(MF, MO);
157732807932SDan Gohman           }
15781d68e80fSDan Gohman         }
1579ed41945fSHeejin Ahn 
1580ed41945fSHeejin Ahn         if (MI.getOpcode() == WebAssembly::DELEGATE) {
1581ed41945fSHeejin Ahn           Stack.push_back(&MBB);
1582ed41945fSHeejin Ahn           DelegateStack.push_back(&MBB);
1583ed41945fSHeejin Ahn         }
15841d68e80fSDan Gohman         break;
15851d68e80fSDan Gohman       }
15861d68e80fSDan Gohman     }
15871d68e80fSDan Gohman   }
15881d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
1589e76fa9ecSHeejin Ahn }
15902726b88cSDan Gohman 
1591ed41945fSHeejin Ahn void WebAssemblyCFGStackify::cleanupFunctionData(MachineFunction &MF) {
1592ed41945fSHeejin Ahn   if (FakeCallerBB)
1593ed41945fSHeejin Ahn     MF.DeleteMachineBasicBlock(FakeCallerBB);
1594ed41945fSHeejin Ahn   AppendixBB = FakeCallerBB = nullptr;
1595ed41945fSHeejin Ahn }
1596ed41945fSHeejin Ahn 
1597e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() {
1598e76fa9ecSHeejin Ahn   ScopeTops.clear();
1599e76fa9ecSHeejin Ahn   BeginToEnd.clear();
1600e76fa9ecSHeejin Ahn   EndToBegin.clear();
1601e76fa9ecSHeejin Ahn   TryToEHPad.clear();
1602e76fa9ecSHeejin Ahn   EHPadToTry.clear();
16031d68e80fSDan Gohman }
160432807932SDan Gohman 
1605950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
1606d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
1607950a13cfSDan Gohman                        "********** Function: "
1608950a13cfSDan Gohman                     << MF.getName() << '\n');
1609cf699b45SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1610950a13cfSDan Gohman 
1611e76fa9ecSHeejin Ahn   releaseMemory();
1612e76fa9ecSHeejin Ahn 
1613e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
16149c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
1615950a13cfSDan Gohman 
1616e76fa9ecSHeejin Ahn   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
1617e76fa9ecSHeejin Ahn   placeMarkers(MF);
1618e76fa9ecSHeejin Ahn 
1619c4ac74fbSHeejin Ahn   // Remove unnecessary instructions possibly introduced by try/end_trys.
1620cf699b45SHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1621cf699b45SHeejin Ahn       MF.getFunction().hasPersonalityFn())
1622cf699b45SHeejin Ahn     removeUnnecessaryInstrs(MF);
1623cf699b45SHeejin Ahn 
1624e76fa9ecSHeejin Ahn   // Convert MBB operands in terminators to relative depth immediates.
1625e76fa9ecSHeejin Ahn   rewriteDepthImmediates(MF);
1626e76fa9ecSHeejin Ahn 
1627e76fa9ecSHeejin Ahn   // Fix up block/loop/try signatures at the end of the function to conform to
1628e76fa9ecSHeejin Ahn   // WebAssembly's rules.
1629e76fa9ecSHeejin Ahn   fixEndsAtEndOfFunction(MF);
1630e76fa9ecSHeejin Ahn 
1631e76fa9ecSHeejin Ahn   // Add an end instruction at the end of the function body.
1632e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1633e76fa9ecSHeejin Ahn   if (!MF.getSubtarget<WebAssemblySubtarget>()
1634e76fa9ecSHeejin Ahn            .getTargetTriple()
1635e76fa9ecSHeejin Ahn            .isOSBinFormatELF())
163618c56a07SHeejin Ahn     appendEndToFunction(MF, TII);
163732807932SDan Gohman 
1638ed41945fSHeejin Ahn   cleanupFunctionData(MF);
1639ed41945fSHeejin Ahn 
16401aaa481fSHeejin Ahn   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1641950a13cfSDan Gohman   return true;
1642950a13cfSDan Gohman }
1643