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"
349f770b36SHeejin 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");
439f770b36SHeejin 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
832968611fSHeejin Ahn   using EndMarkerInfo =
842968611fSHeejin Ahn       std::pair<const MachineBasicBlock *, const MachineInstr *>;
852968611fSHeejin Ahn   unsigned getBranchDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
862968611fSHeejin Ahn                           const MachineBasicBlock *MBB);
872968611fSHeejin Ahn   unsigned getDelegateDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
88ed41945fSHeejin Ahn                             const MachineBasicBlock *MBB);
8935f5f797SHeejin Ahn   unsigned
9035f5f797SHeejin Ahn   getRethrowDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
9135f5f797SHeejin Ahn                   const SmallVectorImpl<const MachineBasicBlock *> &EHPadStack);
92e76fa9ecSHeejin Ahn   void rewriteDepthImmediates(MachineFunction &MF);
93e76fa9ecSHeejin Ahn   void fixEndsAtEndOfFunction(MachineFunction &MF);
94ed41945fSHeejin Ahn   void cleanupFunctionData(MachineFunction &MF);
95e76fa9ecSHeejin Ahn 
96ed41945fSHeejin Ahn   // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY) or DELEGATE
97ed41945fSHeejin Ahn   // (in case of TRY).
98e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
99ed41945fSHeejin Ahn   // For each END_(BLOCK|LOOP|TRY) or DELEGATE, the corresponding
100ed41945fSHeejin Ahn   // BLOCK|LOOP|TRY.
101e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
102e76fa9ecSHeejin Ahn   // <TRY marker, EH pad> map
103e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
104e76fa9ecSHeejin Ahn   // <EH pad, TRY marker> map
105e76fa9ecSHeejin Ahn   DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
106e76fa9ecSHeejin Ahn 
107ed41945fSHeejin Ahn   // We need an appendix block to place 'end_loop' or 'end_try' marker when the
108ed41945fSHeejin Ahn   // loop / exception bottom block is the last block in a function
109c4ac74fbSHeejin Ahn   MachineBasicBlock *AppendixBB = nullptr;
110c4ac74fbSHeejin Ahn   MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
111c4ac74fbSHeejin Ahn     if (!AppendixBB) {
112c4ac74fbSHeejin Ahn       AppendixBB = MF.CreateMachineBasicBlock();
113c4ac74fbSHeejin Ahn       // Give it a fake predecessor so that AsmPrinter prints its label.
114c4ac74fbSHeejin Ahn       AppendixBB->addSuccessor(AppendixBB);
115c4ac74fbSHeejin Ahn       MF.push_back(AppendixBB);
116c4ac74fbSHeejin Ahn     }
117c4ac74fbSHeejin Ahn     return AppendixBB;
118c4ac74fbSHeejin Ahn   }
119c4ac74fbSHeejin Ahn 
120ed41945fSHeejin Ahn   // Before running rewriteDepthImmediates function, 'delegate' has a BB as its
121ed41945fSHeejin Ahn   // destination operand. getFakeCallerBlock() returns a fake BB that will be
122ed41945fSHeejin Ahn   // used for the operand when 'delegate' needs to rethrow to the caller. This
123ed41945fSHeejin Ahn   // will be rewritten as an immediate value that is the number of block depths
124ed41945fSHeejin Ahn   // + 1 in rewriteDepthImmediates, and this fake BB will be removed at the end
125ed41945fSHeejin Ahn   // of the pass.
126ed41945fSHeejin Ahn   MachineBasicBlock *FakeCallerBB = nullptr;
127ed41945fSHeejin Ahn   MachineBasicBlock *getFakeCallerBlock(MachineFunction &MF) {
128ed41945fSHeejin Ahn     if (!FakeCallerBB)
129ed41945fSHeejin Ahn       FakeCallerBB = MF.CreateMachineBasicBlock();
130ed41945fSHeejin Ahn     return FakeCallerBB;
131ed41945fSHeejin Ahn   }
132ed41945fSHeejin Ahn 
133cf699b45SHeejin Ahn   // Helper functions to register / unregister scope information created by
134cf699b45SHeejin Ahn   // marker instructions.
135e76fa9ecSHeejin Ahn   void registerScope(MachineInstr *Begin, MachineInstr *End);
136e76fa9ecSHeejin Ahn   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
137e76fa9ecSHeejin Ahn                         MachineBasicBlock *EHPad);
138cf699b45SHeejin Ahn   void unregisterScope(MachineInstr *Begin);
139e76fa9ecSHeejin Ahn 
140950a13cfSDan Gohman public:
141950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
142950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
143e76fa9ecSHeejin Ahn   ~WebAssemblyCFGStackify() override { releaseMemory(); }
144e76fa9ecSHeejin Ahn   void releaseMemory() override;
145950a13cfSDan Gohman };
146950a13cfSDan Gohman } // end anonymous namespace
147950a13cfSDan Gohman 
148950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
14940926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
150c4ac74fbSHeejin Ahn                 "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false,
151f208f631SHeejin Ahn                 false)
15240926451SJacob Gravelle 
153950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
154950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
155950a13cfSDan Gohman }
156950a13cfSDan Gohman 
157b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
158b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
159b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
160b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
161b3aa1ecaSDan Gohman /// explicit mentions.
16218c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
16335e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
164b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
165b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
166b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
167b3aa1ecaSDan Gohman         return true;
168b3aa1ecaSDan Gohman   return false;
169b3aa1ecaSDan Gohman }
170b3aa1ecaSDan Gohman 
171e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB,
172e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
173e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
174e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only
175e76fa9ecSHeejin Ahn // used for sanity checking.
1761cc52357SHeejin Ahn template <typename Container>
177e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
1781cc52357SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
1791cc52357SHeejin Ahn                      const Container &AfterSet) {
180e76fa9ecSHeejin Ahn   auto InsertPos = MBB->end();
181e76fa9ecSHeejin Ahn   while (InsertPos != MBB->begin()) {
182e76fa9ecSHeejin Ahn     if (BeforeSet.count(&*std::prev(InsertPos))) {
183e76fa9ecSHeejin Ahn #ifndef NDEBUG
184e76fa9ecSHeejin Ahn       // Sanity check
185e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
186e76fa9ecSHeejin Ahn         assert(!AfterSet.count(&*std::prev(Pos)));
187e76fa9ecSHeejin Ahn #endif
188e76fa9ecSHeejin Ahn       break;
189e76fa9ecSHeejin Ahn     }
190e76fa9ecSHeejin Ahn     --InsertPos;
191e76fa9ecSHeejin Ahn   }
192e76fa9ecSHeejin Ahn   return InsertPos;
193e76fa9ecSHeejin Ahn }
194e76fa9ecSHeejin Ahn 
195e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB,
196e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
197e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
198e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only
199e76fa9ecSHeejin Ahn // used for sanity checking.
2001cc52357SHeejin Ahn template <typename Container>
201e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
2021cc52357SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
2031cc52357SHeejin Ahn                    const Container &AfterSet) {
204e76fa9ecSHeejin Ahn   auto InsertPos = MBB->begin();
205e76fa9ecSHeejin Ahn   while (InsertPos != MBB->end()) {
206e76fa9ecSHeejin Ahn     if (AfterSet.count(&*InsertPos)) {
207e76fa9ecSHeejin Ahn #ifndef NDEBUG
208e76fa9ecSHeejin Ahn       // Sanity check
209e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
210e76fa9ecSHeejin Ahn         assert(!BeforeSet.count(&*Pos));
211e76fa9ecSHeejin Ahn #endif
212e76fa9ecSHeejin Ahn       break;
213e76fa9ecSHeejin Ahn     }
214e76fa9ecSHeejin Ahn     ++InsertPos;
215e76fa9ecSHeejin Ahn   }
216e76fa9ecSHeejin Ahn   return InsertPos;
217e76fa9ecSHeejin Ahn }
218e76fa9ecSHeejin Ahn 
219e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
220e76fa9ecSHeejin Ahn                                            MachineInstr *End) {
221e76fa9ecSHeejin Ahn   BeginToEnd[Begin] = End;
222e76fa9ecSHeejin Ahn   EndToBegin[End] = Begin;
223e76fa9ecSHeejin Ahn }
224e76fa9ecSHeejin Ahn 
225ed41945fSHeejin Ahn // When 'End' is not an 'end_try' but 'delegate, EHPad is nullptr.
226e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
227e76fa9ecSHeejin Ahn                                               MachineInstr *End,
228e76fa9ecSHeejin Ahn                                               MachineBasicBlock *EHPad) {
229e76fa9ecSHeejin Ahn   registerScope(Begin, End);
230e76fa9ecSHeejin Ahn   TryToEHPad[Begin] = EHPad;
231e76fa9ecSHeejin Ahn   EHPadToTry[EHPad] = Begin;
232e76fa9ecSHeejin Ahn }
233e76fa9ecSHeejin Ahn 
234cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
235cf699b45SHeejin Ahn   assert(BeginToEnd.count(Begin));
236cf699b45SHeejin Ahn   MachineInstr *End = BeginToEnd[Begin];
237cf699b45SHeejin Ahn   assert(EndToBegin.count(End));
238cf699b45SHeejin Ahn   BeginToEnd.erase(Begin);
239cf699b45SHeejin Ahn   EndToBegin.erase(End);
240cf699b45SHeejin Ahn   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
241cf699b45SHeejin Ahn   if (EHPad) {
242cf699b45SHeejin Ahn     assert(EHPadToTry.count(EHPad));
243cf699b45SHeejin Ahn     TryToEHPad.erase(Begin);
244cf699b45SHeejin Ahn     EHPadToTry.erase(EHPad);
245cf699b45SHeejin Ahn   }
246cf699b45SHeejin Ahn }
247cf699b45SHeejin Ahn 
24832807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
249c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and
250c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later.
251e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
25244a5a4b1SHeejin Ahn   assert(!MBB.isEHPad());
253e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
254e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
255e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
256e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
257e76fa9ecSHeejin Ahn 
2588fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
2598fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
2608fe7e86bSDan Gohman   // which reduces overall stack height.
26132807932SDan Gohman   MachineBasicBlock *Header = nullptr;
26232807932SDan Gohman   bool IsBranchedTo = false;
26332807932SDan Gohman   int MBBNumber = MBB.getNumber();
264e76fa9ecSHeejin Ahn   for (MachineBasicBlock *Pred : MBB.predecessors()) {
26532807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
26632807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
26752e240a0SHeejin Ahn       if (explicitlyBranchesTo(Pred, &MBB))
26832807932SDan Gohman         IsBranchedTo = true;
26932807932SDan Gohman     }
270e76fa9ecSHeejin Ahn   }
27132807932SDan Gohman   if (!Header)
27232807932SDan Gohman     return;
27332807932SDan Gohman   if (!IsBranchedTo)
27432807932SDan Gohman     return;
27532807932SDan Gohman 
2768fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
2775c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
2788fe7e86bSDan Gohman 
2798fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
2808fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
2818fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
2828fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
2838fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
2848fe7e86bSDan Gohman         // Skip over an intervening scope.
2855c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
2868fe7e86bSDan Gohman       } else {
2878fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
2888fe7e86bSDan Gohman         Header = ScopeTop;
2898fe7e86bSDan Gohman         break;
2908fe7e86bSDan Gohman       }
2918fe7e86bSDan Gohman     }
2928fe7e86bSDan Gohman   }
2938fe7e86bSDan Gohman 
2948fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
295e76fa9ecSHeejin Ahn 
296e76fa9ecSHeejin Ahn   // Instructions that should go before the BLOCK.
297e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
298e76fa9ecSHeejin Ahn   // Instructions that should go after the BLOCK.
299e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
300e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
30144a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
30244a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the BLOCK, because the loop is
30344a5a4b1SHeejin Ahn     // nested in this BLOCK. Otherwise it should be before the BLOCK.
30444a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
30544a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
30644a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
307e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
308e76fa9ecSHeejin Ahn #ifndef NDEBUG
309e76fa9ecSHeejin Ahn       else
310e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
311e76fa9ecSHeejin Ahn #endif
312e76fa9ecSHeejin Ahn     }
313e76fa9ecSHeejin Ahn 
314834debffSHeejin Ahn     // If there is a previously placed BLOCK/TRY marker and its corresponding
315834debffSHeejin Ahn     // END marker is before the current BLOCK's END marker, that should be
316834debffSHeejin Ahn     // placed after this BLOCK. Otherwise it should be placed before this BLOCK
317834debffSHeejin Ahn     // marker.
31844a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
319834debffSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY) {
320834debffSHeejin Ahn       if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
321e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
322834debffSHeejin Ahn #ifndef NDEBUG
323834debffSHeejin Ahn       else
324834debffSHeejin Ahn         BeforeSet.insert(&MI);
325834debffSHeejin Ahn #endif
326834debffSHeejin Ahn     }
327e76fa9ecSHeejin Ahn 
328e76fa9ecSHeejin Ahn #ifndef NDEBUG
329e76fa9ecSHeejin Ahn     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
330e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
331e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
332e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
333e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
334e76fa9ecSHeejin Ahn #endif
335e76fa9ecSHeejin Ahn 
336e76fa9ecSHeejin Ahn     // Terminators should go after the BLOCK.
337e76fa9ecSHeejin Ahn     if (MI.isTerminator())
338e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
339e76fa9ecSHeejin Ahn   }
340e76fa9ecSHeejin Ahn 
341e76fa9ecSHeejin Ahn   // Local expression tree should go after the BLOCK.
342e76fa9ecSHeejin Ahn   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
343e76fa9ecSHeejin Ahn        --I) {
344409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
345409b4391SYury Delendik       continue;
346e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
347e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
348e76fa9ecSHeejin Ahn     else
349e76fa9ecSHeejin Ahn       break;
35032807932SDan Gohman   }
35132807932SDan Gohman 
3528fe7e86bSDan Gohman   // Add the BLOCK.
3532cb27072SThomas Lively   WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
35418c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
35592401cc1SHeejin Ahn   MachineInstr *Begin =
35692401cc1SHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
3572726b88cSDan Gohman               TII.get(WebAssembly::BLOCK))
358d6f48786SHeejin Ahn           .addImm(int64_t(ReturnType));
3591d68e80fSDan Gohman 
360e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_BLOCK.
361e76fa9ecSHeejin Ahn   BeforeSet.clear();
362e76fa9ecSHeejin Ahn   AfterSet.clear();
363e76fa9ecSHeejin Ahn   for (auto &MI : MBB) {
364e76fa9ecSHeejin Ahn #ifndef NDEBUG
365e76fa9ecSHeejin Ahn     // END_BLOCK should precede existing LOOP and TRY markers.
366e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
367e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
368e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
369e76fa9ecSHeejin Ahn #endif
370e76fa9ecSHeejin Ahn 
371e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and the header of the
372e76fa9ecSHeejin Ahn     // loop is above this block's header, the END_LOOP should be placed after
373e76fa9ecSHeejin Ahn     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
374e76fa9ecSHeejin Ahn     // should be placed before the BLOCK. The same for END_TRY.
375e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP ||
376e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY) {
377e76fa9ecSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
378e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
379e76fa9ecSHeejin Ahn #ifndef NDEBUG
380e76fa9ecSHeejin Ahn       else
381e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
382e76fa9ecSHeejin Ahn #endif
383e76fa9ecSHeejin Ahn     }
384e76fa9ecSHeejin Ahn   }
385e76fa9ecSHeejin Ahn 
3861d68e80fSDan Gohman   // Mark the end of the block.
38718c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
38810b31358SDerek Schuff   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
3892726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
390e76fa9ecSHeejin Ahn   registerScope(Begin, End);
3918fe7e86bSDan Gohman 
3928fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
3931cc52357SHeejin Ahn   updateScopeTops(Header, &MBB);
394950a13cfSDan Gohman }
395950a13cfSDan Gohman 
3968fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
397e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
398e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
399e76fa9ecSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
400276f9e8cSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
401276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
402e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
403e76fa9ecSHeejin Ahn 
4048fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
4058fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
4068fe7e86bSDan Gohman     return;
4078fe7e86bSDan Gohman 
4088fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
4098fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
410276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(Loop);
4115c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
412e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
413c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
4145c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
415e3e4a5ffSDan Gohman   }
4168fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
417f6857223SDan Gohman 
418e76fa9ecSHeejin Ahn   // Decide where in Header to put the LOOP.
419e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
420e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
421e76fa9ecSHeejin Ahn   for (const auto &MI : MBB) {
422e76fa9ecSHeejin Ahn     // LOOP marker should be after any existing loop that ends here. Otherwise
423e76fa9ecSHeejin Ahn     // we assume the instruction belongs to the loop.
424e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
425e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
426e76fa9ecSHeejin Ahn #ifndef NDEBUG
427e76fa9ecSHeejin Ahn     else
428e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
429e76fa9ecSHeejin Ahn #endif
430e76fa9ecSHeejin Ahn   }
431e76fa9ecSHeejin Ahn 
432e76fa9ecSHeejin Ahn   // Mark the beginning of the loop.
43318c56a07SHeejin Ahn   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
43410b31358SDerek Schuff   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
4352726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
4362cb27072SThomas Lively                             .addImm(int64_t(WebAssembly::BlockType::Void));
4371d68e80fSDan Gohman 
438e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_LOOP.
439e76fa9ecSHeejin Ahn   BeforeSet.clear();
440e76fa9ecSHeejin Ahn   AfterSet.clear();
441e76fa9ecSHeejin Ahn #ifndef NDEBUG
442e76fa9ecSHeejin Ahn   for (const auto &MI : MBB)
443e76fa9ecSHeejin Ahn     // Existing END_LOOP markers belong to parent loops of this loop
444e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
445e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
446e76fa9ecSHeejin Ahn #endif
447e76fa9ecSHeejin Ahn 
448e76fa9ecSHeejin Ahn   // Mark the end of the loop (using arbitrary debug location that branched to
449e76fa9ecSHeejin Ahn   // the loop end as its location).
45018c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
45167f74aceSHeejin Ahn   DebugLoc EndDL = AfterLoop->pred_empty()
45267f74aceSHeejin Ahn                        ? DebugLoc()
45367f74aceSHeejin Ahn                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
454e76fa9ecSHeejin Ahn   MachineInstr *End =
455e76fa9ecSHeejin Ahn       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
456e76fa9ecSHeejin Ahn   registerScope(Begin, End);
4578fe7e86bSDan Gohman 
4588fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4598fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
460442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
4611cc52357SHeejin Ahn   updateScopeTops(&MBB, AfterLoop);
462e3e4a5ffSDan Gohman }
463950a13cfSDan Gohman 
464e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
46544a5a4b1SHeejin Ahn   assert(MBB.isEHPad());
466e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
467e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
468e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
469276f9e8cSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
470e76fa9ecSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
471276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
472e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
473e76fa9ecSHeejin Ahn 
474e76fa9ecSHeejin Ahn   // Compute the nearest common dominator of all unwind predecessors
475e76fa9ecSHeejin Ahn   MachineBasicBlock *Header = nullptr;
476e76fa9ecSHeejin Ahn   int MBBNumber = MBB.getNumber();
477e76fa9ecSHeejin Ahn   for (auto *Pred : MBB.predecessors()) {
478e76fa9ecSHeejin Ahn     if (Pred->getNumber() < MBBNumber) {
479e76fa9ecSHeejin Ahn       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
48018c56a07SHeejin Ahn       assert(!explicitlyBranchesTo(Pred, &MBB) &&
481e76fa9ecSHeejin Ahn              "Explicit branch to an EH pad!");
482e76fa9ecSHeejin Ahn     }
483e76fa9ecSHeejin Ahn   }
484e76fa9ecSHeejin Ahn   if (!Header)
485e76fa9ecSHeejin Ahn     return;
486e76fa9ecSHeejin Ahn 
487e76fa9ecSHeejin Ahn   // If this try is at the bottom of the function, insert a dummy block at the
488e76fa9ecSHeejin Ahn   // end.
489e76fa9ecSHeejin Ahn   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
490e76fa9ecSHeejin Ahn   assert(WE);
491276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(WE);
492e76fa9ecSHeejin Ahn 
4935c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
494e76fa9ecSHeejin Ahn   if (Iter == MF.end()) {
495c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
4965c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
497e76fa9ecSHeejin Ahn   }
49820cf0749SHeejin Ahn   MachineBasicBlock *Cont = &*Iter;
499e76fa9ecSHeejin Ahn 
50020cf0749SHeejin Ahn   assert(Cont != &MF.front());
5015c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
502e76fa9ecSHeejin Ahn 
503e76fa9ecSHeejin Ahn   // If the nearest common dominator is inside a more deeply nested context,
504e76fa9ecSHeejin Ahn   // walk out to the nearest scope which isn't more deeply nested.
505e76fa9ecSHeejin Ahn   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
506e76fa9ecSHeejin Ahn     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
507e76fa9ecSHeejin Ahn       if (ScopeTop->getNumber() > Header->getNumber()) {
508e76fa9ecSHeejin Ahn         // Skip over an intervening scope.
5095c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
510e76fa9ecSHeejin Ahn       } else {
511e76fa9ecSHeejin Ahn         // We found a scope level at an appropriate depth.
512e76fa9ecSHeejin Ahn         Header = ScopeTop;
513e76fa9ecSHeejin Ahn         break;
514e76fa9ecSHeejin Ahn       }
515e76fa9ecSHeejin Ahn     }
516e76fa9ecSHeejin Ahn   }
517e76fa9ecSHeejin Ahn 
518e76fa9ecSHeejin Ahn   // Decide where in Header to put the TRY.
519e76fa9ecSHeejin Ahn 
52044a5a4b1SHeejin Ahn   // Instructions that should go before the TRY.
521e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
52244a5a4b1SHeejin Ahn   // Instructions that should go after the TRY.
523e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
524e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
52544a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
52644a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the TRY, because the loop is nested
52744a5a4b1SHeejin Ahn     // in this TRY. Otherwise it should be before the TRY.
528e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
52944a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
53044a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
531e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
532e76fa9ecSHeejin Ahn #ifndef NDEBUG
533e76fa9ecSHeejin Ahn       else
534e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
535e76fa9ecSHeejin Ahn #endif
536e76fa9ecSHeejin Ahn     }
537e76fa9ecSHeejin Ahn 
53844a5a4b1SHeejin Ahn     // All previously inserted BLOCK/TRY markers should be after the TRY because
53944a5a4b1SHeejin Ahn     // they are all nested trys.
54044a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
54144a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
542e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
543e76fa9ecSHeejin Ahn 
544e76fa9ecSHeejin Ahn #ifndef NDEBUG
54544a5a4b1SHeejin Ahn     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
54644a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
54744a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
548e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
549e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
550e76fa9ecSHeejin Ahn #endif
551e76fa9ecSHeejin Ahn 
552e76fa9ecSHeejin Ahn     // Terminators should go after the TRY.
553e76fa9ecSHeejin Ahn     if (MI.isTerminator())
554e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
555e76fa9ecSHeejin Ahn   }
556e76fa9ecSHeejin Ahn 
5576a37c5d6SHeejin Ahn   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
5586a37c5d6SHeejin Ahn   // contain the call within it. So the call should go after the TRY. The
5596a37c5d6SHeejin Ahn   // exception is when the header's terminator is a rethrow instruction, in
5606a37c5d6SHeejin Ahn   // which case that instruction, not a call instruction before it, is gonna
5616a37c5d6SHeejin Ahn   // throw.
5626a37c5d6SHeejin Ahn   MachineInstr *ThrowingCall = nullptr;
5636a37c5d6SHeejin Ahn   if (MBB.isPredecessor(Header)) {
5646a37c5d6SHeejin Ahn     auto TermPos = Header->getFirstTerminator();
5656a37c5d6SHeejin Ahn     if (TermPos == Header->end() ||
5666a37c5d6SHeejin Ahn         TermPos->getOpcode() != WebAssembly::RETHROW) {
5676a37c5d6SHeejin Ahn       for (auto &MI : reverse(*Header)) {
5686a37c5d6SHeejin Ahn         if (MI.isCall()) {
5696a37c5d6SHeejin Ahn           AfterSet.insert(&MI);
5706a37c5d6SHeejin Ahn           ThrowingCall = &MI;
5716a37c5d6SHeejin Ahn           // Possibly throwing calls are usually wrapped by EH_LABEL
5726a37c5d6SHeejin Ahn           // instructions. We don't want to split them and the call.
5736a37c5d6SHeejin Ahn           if (MI.getIterator() != Header->begin() &&
5746a37c5d6SHeejin Ahn               std::prev(MI.getIterator())->isEHLabel()) {
5756a37c5d6SHeejin Ahn             AfterSet.insert(&*std::prev(MI.getIterator()));
5766a37c5d6SHeejin Ahn             ThrowingCall = &*std::prev(MI.getIterator());
5776a37c5d6SHeejin Ahn           }
5786a37c5d6SHeejin Ahn           break;
5796a37c5d6SHeejin Ahn         }
5806a37c5d6SHeejin Ahn       }
5816a37c5d6SHeejin Ahn     }
5826a37c5d6SHeejin Ahn   }
5836a37c5d6SHeejin Ahn 
584e76fa9ecSHeejin Ahn   // Local expression tree should go after the TRY.
5856a37c5d6SHeejin Ahn   // For BLOCK placement, we start the search from the previous instruction of a
5866a37c5d6SHeejin Ahn   // BB's terminator, but in TRY's case, we should start from the previous
5876a37c5d6SHeejin Ahn   // instruction of a call that can throw, or a EH_LABEL that precedes the call,
5886a37c5d6SHeejin Ahn   // because the return values of the call's previous instructions can be
5896a37c5d6SHeejin Ahn   // stackified and consumed by the throwing call.
5906a37c5d6SHeejin Ahn   auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
5916a37c5d6SHeejin Ahn                                     : Header->getFirstTerminator();
5926a37c5d6SHeejin Ahn   for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
593409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
594409b4391SYury Delendik       continue;
595e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
596e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
597e76fa9ecSHeejin Ahn     else
598e76fa9ecSHeejin Ahn       break;
599e76fa9ecSHeejin Ahn   }
600e76fa9ecSHeejin Ahn 
601e76fa9ecSHeejin Ahn   // Add the TRY.
60218c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
603e76fa9ecSHeejin Ahn   MachineInstr *Begin =
604e76fa9ecSHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
605e76fa9ecSHeejin Ahn               TII.get(WebAssembly::TRY))
6062cb27072SThomas Lively           .addImm(int64_t(WebAssembly::BlockType::Void));
607e76fa9ecSHeejin Ahn 
608e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_TRY.
609e76fa9ecSHeejin Ahn   BeforeSet.clear();
610e76fa9ecSHeejin Ahn   AfterSet.clear();
61120cf0749SHeejin Ahn   for (const auto &MI : *Cont) {
612e76fa9ecSHeejin Ahn #ifndef NDEBUG
61344a5a4b1SHeejin Ahn     // END_TRY should precede existing LOOP and BLOCK markers.
61444a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
61544a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::BLOCK)
616e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
617e76fa9ecSHeejin Ahn 
618e76fa9ecSHeejin Ahn     // All END_TRY markers placed earlier belong to exceptions that contains
619e76fa9ecSHeejin Ahn     // this one.
620e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_TRY)
621e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
622e76fa9ecSHeejin Ahn #endif
623e76fa9ecSHeejin Ahn 
624e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and its header is after
625e76fa9ecSHeejin Ahn     // where TRY marker is, this loop is contained within the 'catch' part, so
626e76fa9ecSHeejin Ahn     // the END_TRY marker should go after that. Otherwise, the whole try-catch
627e76fa9ecSHeejin Ahn     // is contained within this loop, so the END_TRY should go before that.
628e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP) {
629222718fdSHeejin Ahn       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
630222718fdSHeejin Ahn       // are in the same BB, LOOP is always before TRY.
631222718fdSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
632e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
633e76fa9ecSHeejin Ahn #ifndef NDEBUG
634e76fa9ecSHeejin Ahn       else
635e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
636e76fa9ecSHeejin Ahn #endif
637e76fa9ecSHeejin Ahn     }
63844a5a4b1SHeejin Ahn 
63944a5a4b1SHeejin Ahn     // It is not possible for an END_BLOCK to be already in this block.
640e76fa9ecSHeejin Ahn   }
641e76fa9ecSHeejin Ahn 
642e76fa9ecSHeejin Ahn   // Mark the end of the TRY.
64320cf0749SHeejin Ahn   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
644e76fa9ecSHeejin Ahn   MachineInstr *End =
64520cf0749SHeejin Ahn       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
646e76fa9ecSHeejin Ahn               TII.get(WebAssembly::END_TRY));
647e76fa9ecSHeejin Ahn   registerTryScope(Begin, End, &MBB);
648e76fa9ecSHeejin Ahn 
64982da1ffcSHeejin Ahn   // Track the farthest-spanning scope that ends at this point. We create two
65082da1ffcSHeejin Ahn   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
65182da1ffcSHeejin Ahn   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
65282da1ffcSHeejin Ahn   // markers should not span across 'catch'. For example, this should not
65382da1ffcSHeejin Ahn   // happen:
65482da1ffcSHeejin Ahn   //
65582da1ffcSHeejin Ahn   // try
65682da1ffcSHeejin Ahn   //   block     --|  (X)
65782da1ffcSHeejin Ahn   // catch         |
65882da1ffcSHeejin Ahn   //   end_block --|
65982da1ffcSHeejin Ahn   // end_try
6601cc52357SHeejin Ahn   for (auto *End : {&MBB, Cont})
6611cc52357SHeejin Ahn     updateScopeTops(Header, End);
66282da1ffcSHeejin Ahn }
663e76fa9ecSHeejin Ahn 
664cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
665cf699b45SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
666cf699b45SHeejin Ahn 
667cf699b45SHeejin Ahn   // When there is an unconditional branch right before a catch instruction and
668cf699b45SHeejin Ahn   // it branches to the end of end_try marker, we don't need the branch, because
669cf699b45SHeejin Ahn   // it there is no exception, the control flow transfers to that point anyway.
670cf699b45SHeejin Ahn   // bb0:
671cf699b45SHeejin Ahn   //   try
672cf699b45SHeejin Ahn   //     ...
673cf699b45SHeejin Ahn   //     br bb2      <- Not necessary
674c93b9559SHeejin Ahn   // bb1 (ehpad):
675cf699b45SHeejin Ahn   //   catch
676cf699b45SHeejin Ahn   //     ...
677c93b9559SHeejin Ahn   // bb2:            <- Continuation BB
678cf699b45SHeejin Ahn   //   end
679c93b9559SHeejin Ahn   //
680c93b9559SHeejin Ahn   // A more involved case: When the BB where 'end' is located is an another EH
681c93b9559SHeejin Ahn   // pad, the Cont (= continuation) BB is that EH pad's 'end' BB. For example,
682c93b9559SHeejin Ahn   // bb0:
683c93b9559SHeejin Ahn   //   try
684c93b9559SHeejin Ahn   //     try
685c93b9559SHeejin Ahn   //       ...
686c93b9559SHeejin Ahn   //       br bb3      <- Not necessary
687c93b9559SHeejin Ahn   // bb1 (ehpad):
688c93b9559SHeejin Ahn   //     catch
689c93b9559SHeejin Ahn   // bb2 (ehpad):
690c93b9559SHeejin Ahn   //     end
691c93b9559SHeejin Ahn   //   catch
692c93b9559SHeejin Ahn   //     ...
693c93b9559SHeejin Ahn   // bb3:            <- Continuation BB
694c93b9559SHeejin Ahn   //   end
695c93b9559SHeejin Ahn   //
696c93b9559SHeejin Ahn   // When the EH pad at hand is bb1, its matching end_try is in bb2. But it is
697c93b9559SHeejin Ahn   // another EH pad, so bb0's continuation BB becomes bb3. So 'br bb3' in the
698c93b9559SHeejin Ahn   // code can be deleted. This is why we run 'while' until 'Cont' is not an EH
699c93b9559SHeejin Ahn   // pad.
700cf699b45SHeejin Ahn   for (auto &MBB : MF) {
701cf699b45SHeejin Ahn     if (!MBB.isEHPad())
702cf699b45SHeejin Ahn       continue;
703cf699b45SHeejin Ahn 
704cf699b45SHeejin Ahn     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
705cf699b45SHeejin Ahn     SmallVector<MachineOperand, 4> Cond;
7065c644c9bSHeejin Ahn     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
707c93b9559SHeejin Ahn 
708c93b9559SHeejin Ahn     MachineBasicBlock *Cont = &MBB;
709c93b9559SHeejin Ahn     while (Cont->isEHPad()) {
710c93b9559SHeejin Ahn       MachineInstr *Try = EHPadToTry[Cont];
711c93b9559SHeejin Ahn       MachineInstr *EndTry = BeginToEnd[Try];
712ed41945fSHeejin Ahn       // We started from an EH pad, so the end marker cannot be a delegate
713ed41945fSHeejin Ahn       assert(EndTry->getOpcode() != WebAssembly::DELEGATE);
714c93b9559SHeejin Ahn       Cont = EndTry->getParent();
715c93b9559SHeejin Ahn     }
716c93b9559SHeejin Ahn 
717cf699b45SHeejin Ahn     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
7183fe6ea46SHeejin Ahn     // This condition means either
7193fe6ea46SHeejin Ahn     // 1. This BB ends with a single unconditional branch whose destinaion is
7203fe6ea46SHeejin Ahn     //    Cont.
7213fe6ea46SHeejin Ahn     // 2. This BB ends with a conditional branch followed by an unconditional
7223fe6ea46SHeejin Ahn     //    branch, and the unconditional branch's destination is Cont.
7233fe6ea46SHeejin Ahn     // In both cases, we want to remove the last (= unconditional) branch.
724cf699b45SHeejin Ahn     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
7253fe6ea46SHeejin Ahn                        (!Cond.empty() && FBB && FBB == Cont))) {
7263fe6ea46SHeejin Ahn       bool ErasedUncondBr = false;
727a5099ad9SHeejin Ahn       (void)ErasedUncondBr;
7283fe6ea46SHeejin Ahn       for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
7293fe6ea46SHeejin Ahn            I != E; --I) {
7303fe6ea46SHeejin Ahn         auto PrevI = std::prev(I);
7313fe6ea46SHeejin Ahn         if (PrevI->isTerminator()) {
7323fe6ea46SHeejin Ahn           assert(PrevI->getOpcode() == WebAssembly::BR);
7333fe6ea46SHeejin Ahn           PrevI->eraseFromParent();
7343fe6ea46SHeejin Ahn           ErasedUncondBr = true;
7353fe6ea46SHeejin Ahn           break;
7363fe6ea46SHeejin Ahn         }
7373fe6ea46SHeejin Ahn       }
7383fe6ea46SHeejin Ahn       assert(ErasedUncondBr && "Unconditional branch not erased!");
7393fe6ea46SHeejin Ahn     }
740cf699b45SHeejin Ahn   }
741cf699b45SHeejin Ahn 
742cf699b45SHeejin Ahn   // When there are block / end_block markers that overlap with try / end_try
743cf699b45SHeejin Ahn   // markers, and the block and try markers' return types are the same, the
744cf699b45SHeejin Ahn   // block /end_block markers are not necessary, because try / end_try markers
745cf699b45SHeejin Ahn   // also can serve as boundaries for branches.
746cf699b45SHeejin Ahn   // block         <- Not necessary
747cf699b45SHeejin Ahn   //   try
748cf699b45SHeejin Ahn   //     ...
749cf699b45SHeejin Ahn   //   catch
750cf699b45SHeejin Ahn   //     ...
751cf699b45SHeejin Ahn   //   end
752cf699b45SHeejin Ahn   // end           <- Not necessary
753cf699b45SHeejin Ahn   SmallVector<MachineInstr *, 32> ToDelete;
754cf699b45SHeejin Ahn   for (auto &MBB : MF) {
755cf699b45SHeejin Ahn     for (auto &MI : MBB) {
756cf699b45SHeejin Ahn       if (MI.getOpcode() != WebAssembly::TRY)
757cf699b45SHeejin Ahn         continue;
758cf699b45SHeejin Ahn       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
759ed41945fSHeejin Ahn       if (EndTry->getOpcode() == WebAssembly::DELEGATE)
760ed41945fSHeejin Ahn         continue;
761ed41945fSHeejin Ahn 
762cf699b45SHeejin Ahn       MachineBasicBlock *TryBB = Try->getParent();
763cf699b45SHeejin Ahn       MachineBasicBlock *Cont = EndTry->getParent();
764cf699b45SHeejin Ahn       int64_t RetType = Try->getOperand(0).getImm();
7655c644c9bSHeejin Ahn       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
766cf699b45SHeejin Ahn            B != TryBB->begin() && E != Cont->end() &&
767cf699b45SHeejin Ahn            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
768cf699b45SHeejin Ahn            E->getOpcode() == WebAssembly::END_BLOCK &&
769cf699b45SHeejin Ahn            std::prev(B)->getOperand(0).getImm() == RetType;
770cf699b45SHeejin Ahn            --B, ++E) {
771cf699b45SHeejin Ahn         ToDelete.push_back(&*std::prev(B));
772cf699b45SHeejin Ahn         ToDelete.push_back(&*E);
773cf699b45SHeejin Ahn       }
774cf699b45SHeejin Ahn     }
775cf699b45SHeejin Ahn   }
776cf699b45SHeejin Ahn   for (auto *MI : ToDelete) {
777cf699b45SHeejin Ahn     if (MI->getOpcode() == WebAssembly::BLOCK)
778cf699b45SHeejin Ahn       unregisterScope(MI);
779cf699b45SHeejin Ahn     MI->eraseFromParent();
780cf699b45SHeejin Ahn   }
781cf699b45SHeejin Ahn }
782cf699b45SHeejin Ahn 
78383c26eaeSHeejin Ahn // Get the appropriate copy opcode for the given register class.
78483c26eaeSHeejin Ahn static unsigned getCopyOpcode(const TargetRegisterClass *RC) {
78583c26eaeSHeejin Ahn   if (RC == &WebAssembly::I32RegClass)
78683c26eaeSHeejin Ahn     return WebAssembly::COPY_I32;
78783c26eaeSHeejin Ahn   if (RC == &WebAssembly::I64RegClass)
78883c26eaeSHeejin Ahn     return WebAssembly::COPY_I64;
78983c26eaeSHeejin Ahn   if (RC == &WebAssembly::F32RegClass)
79083c26eaeSHeejin Ahn     return WebAssembly::COPY_F32;
79183c26eaeSHeejin Ahn   if (RC == &WebAssembly::F64RegClass)
79283c26eaeSHeejin Ahn     return WebAssembly::COPY_F64;
79383c26eaeSHeejin Ahn   if (RC == &WebAssembly::V128RegClass)
79483c26eaeSHeejin Ahn     return WebAssembly::COPY_V128;
79560653e24SHeejin Ahn   if (RC == &WebAssembly::FUNCREFRegClass)
79660653e24SHeejin Ahn     return WebAssembly::COPY_FUNCREF;
79760653e24SHeejin Ahn   if (RC == &WebAssembly::EXTERNREFRegClass)
79860653e24SHeejin Ahn     return WebAssembly::COPY_EXTERNREF;
79983c26eaeSHeejin Ahn   llvm_unreachable("Unexpected register class");
80083c26eaeSHeejin Ahn }
80183c26eaeSHeejin Ahn 
80261d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that
80361d5c76aSHeejin Ahn // have their uses in Split.
804ed41945fSHeejin Ahn static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB,
805ed41945fSHeejin Ahn                                          MachineBasicBlock &Split) {
8061cc52357SHeejin Ahn   MachineFunction &MF = *MBB.getParent();
8071cc52357SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
8081cc52357SHeejin Ahn   auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
8091cc52357SHeejin Ahn   auto &MRI = MF.getRegInfo();
8101cc52357SHeejin Ahn 
81161d5c76aSHeejin Ahn   for (auto &MI : Split) {
81261d5c76aSHeejin Ahn     for (auto &MO : MI.explicit_uses()) {
81361d5c76aSHeejin Ahn       if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg()))
81461d5c76aSHeejin Ahn         continue;
81561d5c76aSHeejin Ahn       if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
81661d5c76aSHeejin Ahn         if (Def->getParent() == &MBB)
81761d5c76aSHeejin Ahn           MFI.unstackifyVReg(MO.getReg());
81861d5c76aSHeejin Ahn     }
81961d5c76aSHeejin Ahn   }
82083c26eaeSHeejin Ahn 
82183c26eaeSHeejin Ahn   // In RegStackify, when a register definition is used multiple times,
82283c26eaeSHeejin Ahn   //    Reg = INST ...
82383c26eaeSHeejin Ahn   //    INST ..., Reg, ...
82483c26eaeSHeejin Ahn   //    INST ..., Reg, ...
82583c26eaeSHeejin Ahn   //    INST ..., Reg, ...
82683c26eaeSHeejin Ahn   //
82783c26eaeSHeejin Ahn   // we introduce a TEE, which has the following form:
82883c26eaeSHeejin Ahn   //    DefReg = INST ...
82983c26eaeSHeejin Ahn   //    TeeReg, Reg = TEE_... DefReg
83083c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
83183c26eaeSHeejin Ahn   //    INST ..., Reg, ...
83283c26eaeSHeejin Ahn   //    INST ..., Reg, ...
83383c26eaeSHeejin Ahn   // with DefReg and TeeReg stackified but Reg not stackified.
83483c26eaeSHeejin Ahn   //
83583c26eaeSHeejin Ahn   // But the invariant that TeeReg should be stackified can be violated while we
83683c26eaeSHeejin Ahn   // unstackify registers in the split BB above. In this case, we convert TEEs
83783c26eaeSHeejin Ahn   // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
83883c26eaeSHeejin Ahn   //    DefReg = INST ...
83983c26eaeSHeejin Ahn   //    TeeReg = COPY DefReg
84083c26eaeSHeejin Ahn   //    Reg = COPY DefReg
84183c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
84283c26eaeSHeejin Ahn   //    INST ..., Reg, ...
84383c26eaeSHeejin Ahn   //    INST ..., Reg, ...
84483c26eaeSHeejin Ahn   for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
84583c26eaeSHeejin Ahn     MachineInstr &MI = *I++;
84683c26eaeSHeejin Ahn     if (!WebAssembly::isTee(MI.getOpcode()))
84783c26eaeSHeejin Ahn       continue;
84883c26eaeSHeejin Ahn     Register TeeReg = MI.getOperand(0).getReg();
84983c26eaeSHeejin Ahn     Register Reg = MI.getOperand(1).getReg();
85083c26eaeSHeejin Ahn     Register DefReg = MI.getOperand(2).getReg();
85183c26eaeSHeejin Ahn     if (!MFI.isVRegStackified(TeeReg)) {
85283c26eaeSHeejin Ahn       // Now we are not using TEE anymore, so unstackify DefReg too
85383c26eaeSHeejin Ahn       MFI.unstackifyVReg(DefReg);
85483c26eaeSHeejin Ahn       unsigned CopyOpc = getCopyOpcode(MRI.getRegClass(DefReg));
85583c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
85683c26eaeSHeejin Ahn           .addReg(DefReg);
85783c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
85883c26eaeSHeejin Ahn       MI.eraseFromParent();
85983c26eaeSHeejin Ahn     }
86083c26eaeSHeejin Ahn   }
86161d5c76aSHeejin Ahn }
86261d5c76aSHeejin Ahn 
863ed41945fSHeejin Ahn // Wrap the given range of instruction with try-delegate. RangeBegin and
864ed41945fSHeejin Ahn // RangeEnd are inclusive.
865ed41945fSHeejin Ahn void WebAssemblyCFGStackify::addTryDelegate(MachineInstr *RangeBegin,
866ed41945fSHeejin Ahn                                             MachineInstr *RangeEnd,
867ed41945fSHeejin Ahn                                             MachineBasicBlock *DelegateDest) {
868ed41945fSHeejin Ahn   auto *BeginBB = RangeBegin->getParent();
869ed41945fSHeejin Ahn   auto *EndBB = RangeEnd->getParent();
870ed41945fSHeejin Ahn   MachineFunction &MF = *BeginBB->getParent();
871ed41945fSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
872ed41945fSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
873ed41945fSHeejin Ahn 
874ed41945fSHeejin Ahn   // Local expression tree before the first call of this range should go
875ed41945fSHeejin Ahn   // after the nested TRY.
876ed41945fSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
877ed41945fSHeejin Ahn   AfterSet.insert(RangeBegin);
878ed41945fSHeejin Ahn   for (auto I = MachineBasicBlock::iterator(RangeBegin), E = BeginBB->begin();
879ed41945fSHeejin Ahn        I != E; --I) {
880ed41945fSHeejin Ahn     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
881ed41945fSHeejin Ahn       continue;
882ed41945fSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
883ed41945fSHeejin Ahn       AfterSet.insert(&*std::prev(I));
884ed41945fSHeejin Ahn     else
885ed41945fSHeejin Ahn       break;
886ed41945fSHeejin Ahn   }
887ed41945fSHeejin Ahn 
888ed41945fSHeejin Ahn   // Create the nested try instruction.
889ed41945fSHeejin Ahn   auto TryPos = getLatestInsertPos(
890ed41945fSHeejin Ahn       BeginBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet);
891ed41945fSHeejin Ahn   MachineInstr *Try = BuildMI(*BeginBB, TryPos, RangeBegin->getDebugLoc(),
892ed41945fSHeejin Ahn                               TII.get(WebAssembly::TRY))
893ed41945fSHeejin Ahn                           .addImm(int64_t(WebAssembly::BlockType::Void));
894ed41945fSHeejin Ahn 
895ed41945fSHeejin Ahn   // Create a BB to insert the 'delegate' instruction.
896ed41945fSHeejin Ahn   MachineBasicBlock *DelegateBB = MF.CreateMachineBasicBlock();
897ed41945fSHeejin Ahn   // If the destination of 'delegate' is not the caller, adds the destination to
898ed41945fSHeejin Ahn   // the BB's successors.
899ed41945fSHeejin Ahn   if (DelegateDest != FakeCallerBB)
900ed41945fSHeejin Ahn     DelegateBB->addSuccessor(DelegateDest);
901ed41945fSHeejin Ahn 
902ed41945fSHeejin Ahn   auto SplitPos = std::next(RangeEnd->getIterator());
903ed41945fSHeejin Ahn   if (SplitPos == EndBB->end()) {
904ed41945fSHeejin Ahn     // If the range's end instruction is at the end of the BB, insert the new
905ed41945fSHeejin Ahn     // delegate BB after the current BB.
906ed41945fSHeejin Ahn     MF.insert(std::next(EndBB->getIterator()), DelegateBB);
907ed41945fSHeejin Ahn     EndBB->addSuccessor(DelegateBB);
908ed41945fSHeejin Ahn 
909ed41945fSHeejin Ahn   } else {
9109f770b36SHeejin Ahn     // When the split pos is in the middle of a BB, we split the BB into two and
9119f770b36SHeejin Ahn     // put the 'delegate' BB in between. We normally create a split BB and make
9129f770b36SHeejin Ahn     // it a successor of the original BB (PostSplit == true), but in case the BB
9139f770b36SHeejin Ahn     // is an EH pad and the split pos is before 'catch', we should preserve the
9149f770b36SHeejin Ahn     // BB's property, including that it is an EH pad, in the later part of the
9159f770b36SHeejin Ahn     // BB, where 'catch' is. In this case we set PostSplit to false.
9169f770b36SHeejin Ahn     bool PostSplit = true;
9179f770b36SHeejin Ahn     if (EndBB->isEHPad()) {
9189f770b36SHeejin Ahn       for (auto I = MachineBasicBlock::iterator(SplitPos), E = EndBB->end();
9199f770b36SHeejin Ahn            I != E; ++I) {
9209f770b36SHeejin Ahn         if (WebAssembly::isCatch(I->getOpcode())) {
9219f770b36SHeejin Ahn           PostSplit = false;
9229f770b36SHeejin Ahn           break;
9239f770b36SHeejin Ahn         }
9249f770b36SHeejin Ahn       }
9259f770b36SHeejin Ahn     }
9269f770b36SHeejin Ahn 
9279f770b36SHeejin Ahn     MachineBasicBlock *PreBB = nullptr, *PostBB = nullptr;
9289f770b36SHeejin Ahn     if (PostSplit) {
929ed41945fSHeejin Ahn       // If the range's end instruction is in the middle of the BB, we split the
930ed41945fSHeejin Ahn       // BB into two and insert the delegate BB in between.
931ed41945fSHeejin Ahn       // - Before:
932ed41945fSHeejin Ahn       // bb:
933ed41945fSHeejin Ahn       //   range_end
934ed41945fSHeejin Ahn       //   other_insts
935ed41945fSHeejin Ahn       //
936ed41945fSHeejin Ahn       // - After:
937ed41945fSHeejin Ahn       // pre_bb: (previous 'bb')
938ed41945fSHeejin Ahn       //   range_end
939ed41945fSHeejin Ahn       // delegate_bb: (new)
940ed41945fSHeejin Ahn       //   delegate
941ed41945fSHeejin Ahn       // post_bb: (new)
942ed41945fSHeejin Ahn       //   other_insts
9439f770b36SHeejin Ahn       PreBB = EndBB;
9449f770b36SHeejin Ahn       PostBB = MF.CreateMachineBasicBlock();
945ed41945fSHeejin Ahn       MF.insert(std::next(PreBB->getIterator()), PostBB);
946ed41945fSHeejin Ahn       MF.insert(std::next(PreBB->getIterator()), DelegateBB);
947ed41945fSHeejin Ahn       PostBB->splice(PostBB->end(), PreBB, SplitPos, PreBB->end());
948ed41945fSHeejin Ahn       PostBB->transferSuccessors(PreBB);
9499f770b36SHeejin Ahn     } else {
9509f770b36SHeejin Ahn       // - Before:
9519f770b36SHeejin Ahn       // ehpad:
9529f770b36SHeejin Ahn       //   range_end
9539f770b36SHeejin Ahn       //   catch
9549f770b36SHeejin Ahn       //   ...
9559f770b36SHeejin Ahn       //
9569f770b36SHeejin Ahn       // - After:
9579f770b36SHeejin Ahn       // pre_bb: (new)
9589f770b36SHeejin Ahn       //   range_end
9599f770b36SHeejin Ahn       // delegate_bb: (new)
9609f770b36SHeejin Ahn       //   delegate
9619f770b36SHeejin Ahn       // post_bb: (previous 'ehpad')
9629f770b36SHeejin Ahn       //   catch
9639f770b36SHeejin Ahn       //   ...
9649f770b36SHeejin Ahn       assert(EndBB->isEHPad());
9659f770b36SHeejin Ahn       PreBB = MF.CreateMachineBasicBlock();
9669f770b36SHeejin Ahn       PostBB = EndBB;
9679f770b36SHeejin Ahn       MF.insert(PostBB->getIterator(), PreBB);
9689f770b36SHeejin Ahn       MF.insert(PostBB->getIterator(), DelegateBB);
9699f770b36SHeejin Ahn       PreBB->splice(PreBB->end(), PostBB, PostBB->begin(), SplitPos);
9709f770b36SHeejin Ahn       // We don't need to transfer predecessors of the EH pad to 'PreBB',
9719f770b36SHeejin Ahn       // because an EH pad's predecessors are all through unwind edges and they
9729f770b36SHeejin Ahn       // should still unwind to the EH pad, not PreBB.
9739f770b36SHeejin Ahn     }
974ed41945fSHeejin Ahn     unstackifyVRegsUsedInSplitBB(*PreBB, *PostBB);
975ed41945fSHeejin Ahn     PreBB->addSuccessor(DelegateBB);
976ed41945fSHeejin Ahn     PreBB->addSuccessor(PostBB);
977ed41945fSHeejin Ahn   }
978ed41945fSHeejin Ahn 
979ed41945fSHeejin Ahn   // Add 'delegate' instruction in the delegate BB created above.
980ed41945fSHeejin Ahn   MachineInstr *Delegate = BuildMI(DelegateBB, RangeEnd->getDebugLoc(),
981ed41945fSHeejin Ahn                                    TII.get(WebAssembly::DELEGATE))
982ed41945fSHeejin Ahn                                .addMBB(DelegateDest);
983ed41945fSHeejin Ahn   registerTryScope(Try, Delegate, nullptr);
984ed41945fSHeejin Ahn }
985ed41945fSHeejin Ahn 
986ed41945fSHeejin Ahn bool WebAssemblyCFGStackify::fixCallUnwindMismatches(MachineFunction &MF) {
987ed41945fSHeejin Ahn   // Linearizing the control flow by placing TRY / END_TRY markers can create
988ed41945fSHeejin Ahn   // mismatches in unwind destinations for throwing instructions, such as calls.
989ed41945fSHeejin Ahn   //
990ed41945fSHeejin Ahn   // We use the 'delegate' instruction to fix the unwind mismatches. 'delegate'
991ed41945fSHeejin Ahn   // instruction delegates an exception to an outer 'catch'. It can target not
992ed41945fSHeejin Ahn   // only 'catch' but all block-like structures including another 'delegate',
993ed41945fSHeejin Ahn   // but with slightly different semantics than branches. When it targets a
994ed41945fSHeejin Ahn   // 'catch', it will delegate the exception to that catch. It is being
995ed41945fSHeejin Ahn   // discussed how to define the semantics when 'delegate''s target is a non-try
996ed41945fSHeejin Ahn   // block: it will either be a validation failure or it will target the next
997ed41945fSHeejin Ahn   // outer try-catch. But anyway our LLVM backend currently does not generate
998ed41945fSHeejin Ahn   // such code. The example below illustrates where the 'delegate' instruction
999ed41945fSHeejin Ahn   // in the middle will delegate the exception to, depending on the value of N.
1000ed41945fSHeejin Ahn   // try
1001ed41945fSHeejin Ahn   //   try
1002ed41945fSHeejin Ahn   //     block
1003ed41945fSHeejin Ahn   //       try
1004ed41945fSHeejin Ahn   //         try
1005ed41945fSHeejin Ahn   //           call @foo
1006ed41945fSHeejin Ahn   //         delegate N    ;; Where will this delegate to?
1007ed41945fSHeejin Ahn   //       catch           ;; N == 0
1008ed41945fSHeejin Ahn   //       end
1009ed41945fSHeejin Ahn   //     end               ;; N == 1 (invalid; will not be generated)
1010ed41945fSHeejin Ahn   //   delegate            ;; N == 2
1011ed41945fSHeejin Ahn   // catch                 ;; N == 3
1012ed41945fSHeejin Ahn   // end
1013ed41945fSHeejin Ahn   //                       ;; N == 4 (to caller)
1014ed41945fSHeejin Ahn 
1015ed41945fSHeejin Ahn   // 1. When an instruction may throw, but the EH pad it will unwind to can be
1016ed41945fSHeejin Ahn   //    different from the original CFG.
1017ed41945fSHeejin Ahn   //
1018ed41945fSHeejin Ahn   // Example: we have the following CFG:
1019ed41945fSHeejin Ahn   // bb0:
1020ed41945fSHeejin Ahn   //   call @foo    ; if it throws, unwind to bb2
1021ed41945fSHeejin Ahn   // bb1:
1022ed41945fSHeejin Ahn   //   call @bar    ; if it throws, unwind to bb3
1023ed41945fSHeejin Ahn   // bb2 (ehpad):
1024ed41945fSHeejin Ahn   //   catch
1025ed41945fSHeejin Ahn   //   ...
1026ed41945fSHeejin Ahn   // bb3 (ehpad)
1027ed41945fSHeejin Ahn   //   catch
1028ed41945fSHeejin Ahn   //   ...
1029ed41945fSHeejin Ahn   //
1030ed41945fSHeejin Ahn   // And the CFG is sorted in this order. Then after placing TRY markers, it
1031ed41945fSHeejin Ahn   // will look like: (BB markers are omitted)
1032ed41945fSHeejin Ahn   // try
1033ed41945fSHeejin Ahn   //   try
1034ed41945fSHeejin Ahn   //     call @foo
1035ed41945fSHeejin Ahn   //     call @bar   ;; if it throws, unwind to bb3
1036ed41945fSHeejin Ahn   //   catch         ;; ehpad (bb2)
1037ed41945fSHeejin Ahn   //     ...
1038ed41945fSHeejin Ahn   //   end_try
1039ed41945fSHeejin Ahn   // catch           ;; ehpad (bb3)
1040ed41945fSHeejin Ahn   //   ...
1041ed41945fSHeejin Ahn   // end_try
1042ed41945fSHeejin Ahn   //
1043ed41945fSHeejin Ahn   // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it
1044ed41945fSHeejin Ahn   // is supposed to end up. We solve this problem by wrapping the mismatching
1045ed41945fSHeejin Ahn   // call with an inner try-delegate that rethrows the exception to the right
1046ed41945fSHeejin Ahn   // 'catch'.
1047ed41945fSHeejin Ahn   //
1048ed41945fSHeejin Ahn   // try
1049ed41945fSHeejin Ahn   //   try
1050ed41945fSHeejin Ahn   //     call @foo
1051ed41945fSHeejin Ahn   //     try               ;; (new)
1052ed41945fSHeejin Ahn   //       call @bar
1053ed41945fSHeejin Ahn   //     delegate 1 (bb3)  ;; (new)
1054ed41945fSHeejin Ahn   //   catch               ;; ehpad (bb2)
1055ed41945fSHeejin Ahn   //     ...
1056ed41945fSHeejin Ahn   //   end_try
1057ed41945fSHeejin Ahn   // catch                 ;; ehpad (bb3)
1058ed41945fSHeejin Ahn   //   ...
1059ed41945fSHeejin Ahn   // end_try
1060ed41945fSHeejin Ahn   //
1061ed41945fSHeejin Ahn   // ---
1062ed41945fSHeejin Ahn   // 2. The same as 1, but in this case an instruction unwinds to a caller
1063ed41945fSHeejin Ahn   //    function and not another EH pad.
1064ed41945fSHeejin Ahn   //
1065ed41945fSHeejin Ahn   // Example: we have the following CFG:
1066ed41945fSHeejin Ahn   // bb0:
1067ed41945fSHeejin Ahn   //   call @foo       ; if it throws, unwind to bb2
1068ed41945fSHeejin Ahn   // bb1:
1069ed41945fSHeejin Ahn   //   call @bar       ; if it throws, unwind to caller
1070ed41945fSHeejin Ahn   // bb2 (ehpad):
1071ed41945fSHeejin Ahn   //   catch
1072ed41945fSHeejin Ahn   //   ...
1073ed41945fSHeejin Ahn   //
1074ed41945fSHeejin Ahn   // And the CFG is sorted in this order. Then after placing TRY markers, it
1075ed41945fSHeejin Ahn   // will look like:
1076ed41945fSHeejin Ahn   // try
1077ed41945fSHeejin Ahn   //   call @foo
1078ed41945fSHeejin Ahn   //   call @bar     ;; if it throws, unwind to caller
1079ed41945fSHeejin Ahn   // catch           ;; ehpad (bb2)
1080ed41945fSHeejin Ahn   //   ...
1081ed41945fSHeejin Ahn   // end_try
1082ed41945fSHeejin Ahn   //
1083ed41945fSHeejin Ahn   // Now if bar() throws, it is going to end up ip in bb2, when it is supposed
1084ed41945fSHeejin Ahn   // throw up to the caller. We solve this problem in the same way, but in this
1085ed41945fSHeejin Ahn   // case 'delegate's immediate argument is the number of block depths + 1,
1086ed41945fSHeejin Ahn   // which means it rethrows to the caller.
1087ed41945fSHeejin Ahn   // try
1088ed41945fSHeejin Ahn   //   call @foo
1089ed41945fSHeejin Ahn   //   try                  ;; (new)
1090ed41945fSHeejin Ahn   //     call @bar
1091ed41945fSHeejin Ahn   //   delegate 1 (caller)  ;; (new)
1092ed41945fSHeejin Ahn   // catch                  ;; ehpad (bb2)
1093ed41945fSHeejin Ahn   //   ...
1094ed41945fSHeejin Ahn   // end_try
1095ed41945fSHeejin Ahn   //
1096ed41945fSHeejin Ahn   // Before rewriteDepthImmediates, delegate's argument is a BB. In case of the
1097ed41945fSHeejin Ahn   // caller, it will take a fake BB generated by getFakeCallerBlock(), which
1098ed41945fSHeejin Ahn   // will be converted to a correct immediate argument later.
1099ed41945fSHeejin Ahn   //
1100ed41945fSHeejin Ahn   // In case there are multiple calls in a BB that may throw to the caller, they
1101ed41945fSHeejin Ahn   // can be wrapped together in one nested try-delegate scope. (In 1, this
1102ed41945fSHeejin Ahn   // couldn't happen, because may-throwing instruction there had an unwind
1103ed41945fSHeejin Ahn   // destination, i.e., it was an invoke before, and there could be only one
1104ed41945fSHeejin Ahn   // invoke within a BB.)
1105ed41945fSHeejin Ahn 
1106ed41945fSHeejin Ahn   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
1107ed41945fSHeejin Ahn   // Range of intructions to be wrapped in a new nested try/catch. A range
1108ed41945fSHeejin Ahn   // exists in a single BB and does not span multiple BBs.
1109ed41945fSHeejin Ahn   using TryRange = std::pair<MachineInstr *, MachineInstr *>;
1110ed41945fSHeejin Ahn   // In original CFG, <unwind destination BB, a vector of try ranges>
1111ed41945fSHeejin Ahn   DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges;
1112ed41945fSHeejin Ahn 
1113ed41945fSHeejin Ahn   // Gather possibly throwing calls (i.e., previously invokes) whose current
1114ed41945fSHeejin Ahn   // unwind destination is not the same as the original CFG. (Case 1)
1115ed41945fSHeejin Ahn 
1116ed41945fSHeejin Ahn   for (auto &MBB : reverse(MF)) {
1117ed41945fSHeejin Ahn     bool SeenThrowableInstInBB = false;
1118ed41945fSHeejin Ahn     for (auto &MI : reverse(MBB)) {
1119ed41945fSHeejin Ahn       if (MI.getOpcode() == WebAssembly::TRY)
1120ed41945fSHeejin Ahn         EHPadStack.pop_back();
1121ed41945fSHeejin Ahn       else if (WebAssembly::isCatch(MI.getOpcode()))
1122ed41945fSHeejin Ahn         EHPadStack.push_back(MI.getParent());
1123ed41945fSHeejin Ahn 
1124ed41945fSHeejin Ahn       // In this loop we only gather calls that have an EH pad to unwind. So
1125ed41945fSHeejin Ahn       // there will be at most 1 such call (= invoke) in a BB, so after we've
1126ed41945fSHeejin Ahn       // seen one, we can skip the rest of BB. Also if MBB has no EH pad
1127ed41945fSHeejin Ahn       // successor or MI does not throw, this is not an invoke.
1128ed41945fSHeejin Ahn       if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() ||
1129ed41945fSHeejin Ahn           !WebAssembly::mayThrow(MI))
1130ed41945fSHeejin Ahn         continue;
1131ed41945fSHeejin Ahn       SeenThrowableInstInBB = true;
1132ed41945fSHeejin Ahn 
1133ed41945fSHeejin Ahn       // If the EH pad on the stack top is where this instruction should unwind
1134ed41945fSHeejin Ahn       // next, we're good.
1135ed41945fSHeejin Ahn       MachineBasicBlock *UnwindDest = getFakeCallerBlock(MF);
1136ed41945fSHeejin Ahn       for (auto *Succ : MBB.successors()) {
1137ed41945fSHeejin Ahn         // Even though semantically a BB can have multiple successors in case an
1138ed41945fSHeejin Ahn         // exception is not caught by a catchpad, in our backend implementation
1139ed41945fSHeejin Ahn         // it is guaranteed that a BB can have at most one EH pad successor. For
1140ed41945fSHeejin Ahn         // details, refer to comments in findWasmUnwindDestinations function in
1141ed41945fSHeejin Ahn         // SelectionDAGBuilder.cpp.
1142ed41945fSHeejin Ahn         if (Succ->isEHPad()) {
1143ed41945fSHeejin Ahn           UnwindDest = Succ;
1144ed41945fSHeejin Ahn           break;
1145ed41945fSHeejin Ahn         }
1146ed41945fSHeejin Ahn       }
1147ed41945fSHeejin Ahn       if (EHPadStack.back() == UnwindDest)
1148ed41945fSHeejin Ahn         continue;
1149ed41945fSHeejin Ahn 
1150ed41945fSHeejin Ahn       // Include EH_LABELs in the range before and afer the invoke
1151ed41945fSHeejin Ahn       MachineInstr *RangeBegin = &MI, *RangeEnd = &MI;
1152ed41945fSHeejin Ahn       if (RangeBegin->getIterator() != MBB.begin() &&
1153ed41945fSHeejin Ahn           std::prev(RangeBegin->getIterator())->isEHLabel())
1154ed41945fSHeejin Ahn         RangeBegin = &*std::prev(RangeBegin->getIterator());
1155ed41945fSHeejin Ahn       if (std::next(RangeEnd->getIterator()) != MBB.end() &&
1156ed41945fSHeejin Ahn           std::next(RangeEnd->getIterator())->isEHLabel())
1157ed41945fSHeejin Ahn         RangeEnd = &*std::next(RangeEnd->getIterator());
1158ed41945fSHeejin Ahn 
1159ed41945fSHeejin Ahn       // If not, record the range.
1160ed41945fSHeejin Ahn       UnwindDestToTryRanges[UnwindDest].push_back(
1161ed41945fSHeejin Ahn           TryRange(RangeBegin, RangeEnd));
1162ed41945fSHeejin Ahn       LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = " << MBB.getName()
1163ed41945fSHeejin Ahn                         << "\nCall = " << MI
1164ed41945fSHeejin Ahn                         << "\nOriginal dest = " << UnwindDest->getName()
1165ed41945fSHeejin Ahn                         << "  Current dest = " << EHPadStack.back()->getName()
1166ed41945fSHeejin Ahn                         << "\n\n");
1167ed41945fSHeejin Ahn     }
1168ed41945fSHeejin Ahn   }
1169ed41945fSHeejin Ahn 
1170ed41945fSHeejin Ahn   assert(EHPadStack.empty());
1171ed41945fSHeejin Ahn 
1172ed41945fSHeejin Ahn   // Gather possibly throwing calls that are supposed to unwind up to the caller
1173ed41945fSHeejin Ahn   // if they throw, but currently unwind to an incorrect destination. Unlike the
1174ed41945fSHeejin Ahn   // loop above, there can be multiple calls within a BB that unwind to the
1175ed41945fSHeejin Ahn   // caller, which we should group together in a range. (Case 2)
1176ed41945fSHeejin Ahn 
1177ed41945fSHeejin Ahn   MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive
1178ed41945fSHeejin Ahn 
1179ed41945fSHeejin Ahn   // Record the range.
1180ed41945fSHeejin Ahn   auto RecordCallerMismatchRange = [&](const MachineBasicBlock *CurrentDest) {
1181ed41945fSHeejin Ahn     UnwindDestToTryRanges[getFakeCallerBlock(MF)].push_back(
1182ed41945fSHeejin Ahn         TryRange(RangeBegin, RangeEnd));
1183ed41945fSHeejin Ahn     LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = "
1184ed41945fSHeejin Ahn                       << RangeBegin->getParent()->getName()
1185ed41945fSHeejin Ahn                       << "\nRange begin = " << *RangeBegin
1186ed41945fSHeejin Ahn                       << "Range end = " << *RangeEnd
1187ed41945fSHeejin Ahn                       << "\nOriginal dest = caller  Current dest = "
1188ed41945fSHeejin Ahn                       << CurrentDest->getName() << "\n\n");
1189ed41945fSHeejin Ahn     RangeBegin = RangeEnd = nullptr; // Reset range pointers
1190ed41945fSHeejin Ahn   };
1191ed41945fSHeejin Ahn 
1192ed41945fSHeejin Ahn   for (auto &MBB : reverse(MF)) {
1193ed41945fSHeejin Ahn     bool SeenThrowableInstInBB = false;
1194ed41945fSHeejin Ahn     for (auto &MI : reverse(MBB)) {
1195ed41945fSHeejin Ahn       bool MayThrow = WebAssembly::mayThrow(MI);
1196ed41945fSHeejin Ahn 
1197ed41945fSHeejin Ahn       // If MBB has an EH pad successor and this is the last instruction that
1198ed41945fSHeejin Ahn       // may throw, this instruction unwinds to the EH pad and not to the
1199ed41945fSHeejin Ahn       // caller.
1200*da01a9dbSHeejin Ahn       if (MBB.hasEHPadSuccessor() && MayThrow && !SeenThrowableInstInBB)
1201ed41945fSHeejin Ahn         SeenThrowableInstInBB = true;
1202ed41945fSHeejin Ahn 
1203ed41945fSHeejin Ahn       // We wrap up the current range when we see a marker even if we haven't
1204ed41945fSHeejin Ahn       // finished a BB.
1205*da01a9dbSHeejin Ahn       else if (RangeEnd && WebAssembly::isMarker(MI.getOpcode()))
1206ed41945fSHeejin Ahn         RecordCallerMismatchRange(EHPadStack.back());
1207ed41945fSHeejin Ahn 
1208ed41945fSHeejin Ahn       // If EHPadStack is empty, that means it correctly unwinds to the caller
1209ed41945fSHeejin Ahn       // if it throws, so we're good. If MI does not throw, we're good too.
1210*da01a9dbSHeejin Ahn       else if (EHPadStack.empty() || !MayThrow) {
1211*da01a9dbSHeejin Ahn       }
1212ed41945fSHeejin Ahn 
1213ed41945fSHeejin Ahn       // We found an instruction that unwinds to the caller but currently has an
1214ed41945fSHeejin Ahn       // incorrect unwind destination. Create a new range or increment the
1215ed41945fSHeejin Ahn       // currently existing range.
1216*da01a9dbSHeejin Ahn       else {
1217ed41945fSHeejin Ahn         if (!RangeEnd)
1218ed41945fSHeejin Ahn           RangeBegin = RangeEnd = &MI;
1219ed41945fSHeejin Ahn         else
1220ed41945fSHeejin Ahn           RangeBegin = &MI;
1221ed41945fSHeejin Ahn       }
1222ed41945fSHeejin Ahn 
1223*da01a9dbSHeejin Ahn       // Update EHPadStack.
1224*da01a9dbSHeejin Ahn       if (MI.getOpcode() == WebAssembly::TRY)
1225*da01a9dbSHeejin Ahn         EHPadStack.pop_back();
1226*da01a9dbSHeejin Ahn       else if (WebAssembly::isCatch(MI.getOpcode()))
1227*da01a9dbSHeejin Ahn         EHPadStack.push_back(MI.getParent());
1228*da01a9dbSHeejin Ahn     }
1229*da01a9dbSHeejin Ahn 
1230ed41945fSHeejin Ahn     if (RangeEnd)
1231ed41945fSHeejin Ahn       RecordCallerMismatchRange(EHPadStack.back());
1232ed41945fSHeejin Ahn   }
1233ed41945fSHeejin Ahn 
1234ed41945fSHeejin Ahn   assert(EHPadStack.empty());
1235ed41945fSHeejin Ahn 
1236ed41945fSHeejin Ahn   // We don't have any unwind destination mismatches to resolve.
1237ed41945fSHeejin Ahn   if (UnwindDestToTryRanges.empty())
1238ed41945fSHeejin Ahn     return false;
1239ed41945fSHeejin Ahn 
1240ed41945fSHeejin Ahn   // Now we fix the mismatches by wrapping calls with inner try-delegates.
1241ed41945fSHeejin Ahn   for (auto &P : UnwindDestToTryRanges) {
1242ed41945fSHeejin Ahn     NumCallUnwindMismatches += P.second.size();
1243ed41945fSHeejin Ahn     MachineBasicBlock *UnwindDest = P.first;
1244ed41945fSHeejin Ahn     auto &TryRanges = P.second;
1245ed41945fSHeejin Ahn 
1246ed41945fSHeejin Ahn     for (auto Range : TryRanges) {
1247ed41945fSHeejin Ahn       MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr;
1248ed41945fSHeejin Ahn       std::tie(RangeBegin, RangeEnd) = Range;
1249ed41945fSHeejin Ahn       auto *MBB = RangeBegin->getParent();
1250ed41945fSHeejin Ahn 
1251ed41945fSHeejin Ahn       // If this BB has an EH pad successor, i.e., ends with an 'invoke', now we
1252ed41945fSHeejin Ahn       // are going to wrap the invoke with try-delegate, making the 'delegate'
1253ed41945fSHeejin Ahn       // BB the new successor instead, so remove the EH pad succesor here. The
1254ed41945fSHeejin Ahn       // BB may not have an EH pad successor if calls in this BB throw to the
1255ed41945fSHeejin Ahn       // caller.
1256ed41945fSHeejin Ahn       MachineBasicBlock *EHPad = nullptr;
1257ed41945fSHeejin Ahn       for (auto *Succ : MBB->successors()) {
1258ed41945fSHeejin Ahn         if (Succ->isEHPad()) {
1259ed41945fSHeejin Ahn           EHPad = Succ;
1260ed41945fSHeejin Ahn           break;
1261ed41945fSHeejin Ahn         }
1262ed41945fSHeejin Ahn       }
1263ed41945fSHeejin Ahn       if (EHPad)
1264ed41945fSHeejin Ahn         MBB->removeSuccessor(EHPad);
1265ed41945fSHeejin Ahn 
1266ed41945fSHeejin Ahn       addTryDelegate(RangeBegin, RangeEnd, UnwindDest);
1267ed41945fSHeejin Ahn     }
1268ed41945fSHeejin Ahn   }
1269ed41945fSHeejin Ahn 
1270ed41945fSHeejin Ahn   return true;
1271ed41945fSHeejin Ahn }
1272ed41945fSHeejin Ahn 
1273ed41945fSHeejin Ahn bool WebAssemblyCFGStackify::fixCatchUnwindMismatches(MachineFunction &MF) {
12749f770b36SHeejin Ahn   // There is another kind of unwind destination mismatches besides call unwind
12759f770b36SHeejin Ahn   // mismatches, which we will call "catch unwind mismatches". See this example
12769f770b36SHeejin Ahn   // after the marker placement:
12779f770b36SHeejin Ahn   // try
12789f770b36SHeejin Ahn   //   try
12799f770b36SHeejin Ahn   //     call @foo
12809f770b36SHeejin Ahn   //   catch __cpp_exception  ;; ehpad A (next unwind dest: caller)
12819f770b36SHeejin Ahn   //     ...
12829f770b36SHeejin Ahn   //   end_try
12839f770b36SHeejin Ahn   // catch_all                ;; ehpad B
12849f770b36SHeejin Ahn   //   ...
12859f770b36SHeejin Ahn   // end_try
12869f770b36SHeejin Ahn   //
12879f770b36SHeejin Ahn   // 'call @foo's unwind destination is the ehpad A. But suppose 'call @foo'
12889f770b36SHeejin Ahn   // throws a foreign exception that is not caught by ehpad A, and its next
12899f770b36SHeejin Ahn   // destination should be the caller. But after control flow linearization,
12909f770b36SHeejin Ahn   // another EH pad can be placed in between (e.g. ehpad B here), making the
12919f770b36SHeejin Ahn   // next unwind destination incorrect. In this case, the  foreign exception
12929f770b36SHeejin Ahn   // will instead go to ehpad B and will be caught there instead. In this
12939f770b36SHeejin Ahn   // example the correct next unwind destination is the caller, but it can be
12949f770b36SHeejin Ahn   // another outer catch in other cases.
12959f770b36SHeejin Ahn   //
12969f770b36SHeejin Ahn   // There is no specific 'call' or 'throw' instruction to wrap with a
12979f770b36SHeejin Ahn   // try-delegate, so we wrap the whole try-catch-end with a try-delegate and
12989f770b36SHeejin Ahn   // make it rethrow to the right destination, as in the example below:
12999f770b36SHeejin Ahn   // try
13009f770b36SHeejin Ahn   //   try                     ;; (new)
13019f770b36SHeejin Ahn   //     try
13029f770b36SHeejin Ahn   //       call @foo
13039f770b36SHeejin Ahn   //     catch __cpp_exception ;; ehpad A (next unwind dest: caller)
13049f770b36SHeejin Ahn   //       ...
13059f770b36SHeejin Ahn   //     end_try
13069f770b36SHeejin Ahn   //   delegate 1 (caller)     ;; (new)
13079f770b36SHeejin Ahn   // catch_all                 ;; ehpad B
13089f770b36SHeejin Ahn   //   ...
13099f770b36SHeejin Ahn   // end_try
13109f770b36SHeejin Ahn 
13119f770b36SHeejin Ahn   const auto *EHInfo = MF.getWasmEHFuncInfo();
13129f770b36SHeejin Ahn   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
13139f770b36SHeejin Ahn   // For EH pads that have catch unwind mismatches, a map of <EH pad, its
13149f770b36SHeejin Ahn   // correct unwind destination>.
13159f770b36SHeejin Ahn   DenseMap<MachineBasicBlock *, MachineBasicBlock *> EHPadToUnwindDest;
13169f770b36SHeejin Ahn 
13179f770b36SHeejin Ahn   for (auto &MBB : reverse(MF)) {
13189f770b36SHeejin Ahn     for (auto &MI : reverse(MBB)) {
13199f770b36SHeejin Ahn       if (MI.getOpcode() == WebAssembly::TRY)
13209f770b36SHeejin Ahn         EHPadStack.pop_back();
13219f770b36SHeejin Ahn       else if (MI.getOpcode() == WebAssembly::DELEGATE)
13229f770b36SHeejin Ahn         EHPadStack.push_back(&MBB);
13239f770b36SHeejin Ahn       else if (WebAssembly::isCatch(MI.getOpcode())) {
13249f770b36SHeejin Ahn         auto *EHPad = &MBB;
13259f770b36SHeejin Ahn 
13269f770b36SHeejin Ahn         // catch_all always catches an exception, so we don't need to do
13279f770b36SHeejin Ahn         // anything
13289f770b36SHeejin Ahn         if (MI.getOpcode() == WebAssembly::CATCH_ALL) {
13299f770b36SHeejin Ahn         }
13309f770b36SHeejin Ahn 
13319f770b36SHeejin Ahn         // This can happen when the unwind dest was removed during the
13329f770b36SHeejin Ahn         // optimization, e.g. because it was unreachable.
13339f770b36SHeejin Ahn         else if (EHPadStack.empty() && EHInfo->hasEHPadUnwindDest(EHPad)) {
13349f770b36SHeejin Ahn           LLVM_DEBUG(dbgs() << "EHPad (" << EHPad->getName()
13359f770b36SHeejin Ahn                             << "'s unwind destination does not exist anymore"
13369f770b36SHeejin Ahn                             << "\n\n");
13379f770b36SHeejin Ahn         }
13389f770b36SHeejin Ahn 
13399f770b36SHeejin Ahn         // The EHPad's next unwind destination is the caller, but we incorrectly
13409f770b36SHeejin Ahn         // unwind to another EH pad.
13419f770b36SHeejin Ahn         else if (!EHPadStack.empty() && !EHInfo->hasEHPadUnwindDest(EHPad)) {
13429f770b36SHeejin Ahn           EHPadToUnwindDest[EHPad] = getFakeCallerBlock(MF);
13439f770b36SHeejin Ahn           LLVM_DEBUG(dbgs()
13449f770b36SHeejin Ahn                      << "- Catch unwind mismatch:\nEHPad = " << EHPad->getName()
13459f770b36SHeejin Ahn                      << "  Original dest = caller  Current dest = "
13469f770b36SHeejin Ahn                      << EHPadStack.back()->getName() << "\n\n");
13479f770b36SHeejin Ahn         }
13489f770b36SHeejin Ahn 
13499f770b36SHeejin Ahn         // The EHPad's next unwind destination is an EH pad, whereas we
13509f770b36SHeejin Ahn         // incorrectly unwind to another EH pad.
13519f770b36SHeejin Ahn         else if (!EHPadStack.empty() && EHInfo->hasEHPadUnwindDest(EHPad)) {
13529f770b36SHeejin Ahn           auto *UnwindDest = EHInfo->getEHPadUnwindDest(EHPad);
13539f770b36SHeejin Ahn           if (EHPadStack.back() != UnwindDest) {
13549f770b36SHeejin Ahn             EHPadToUnwindDest[EHPad] = UnwindDest;
13559f770b36SHeejin Ahn             LLVM_DEBUG(dbgs() << "- Catch unwind mismatch:\nEHPad = "
13569f770b36SHeejin Ahn                               << EHPad->getName() << "  Original dest = "
13579f770b36SHeejin Ahn                               << UnwindDest->getName() << "  Current dest = "
13589f770b36SHeejin Ahn                               << EHPadStack.back()->getName() << "\n\n");
13599f770b36SHeejin Ahn           }
13609f770b36SHeejin Ahn         }
13619f770b36SHeejin Ahn 
13629f770b36SHeejin Ahn         EHPadStack.push_back(EHPad);
13639f770b36SHeejin Ahn       }
13649f770b36SHeejin Ahn     }
13659f770b36SHeejin Ahn   }
13669f770b36SHeejin Ahn 
13679f770b36SHeejin Ahn   assert(EHPadStack.empty());
13689f770b36SHeejin Ahn   if (EHPadToUnwindDest.empty())
1369c4ac74fbSHeejin Ahn     return false;
13709f770b36SHeejin Ahn   NumCatchUnwindMismatches += EHPadToUnwindDest.size();
13719f770b36SHeejin Ahn 
13729f770b36SHeejin Ahn   for (auto &P : EHPadToUnwindDest) {
13739f770b36SHeejin Ahn     MachineBasicBlock *EHPad = P.first;
13749f770b36SHeejin Ahn     MachineBasicBlock *UnwindDest = P.second;
13759f770b36SHeejin Ahn     MachineInstr *Try = EHPadToTry[EHPad];
13769f770b36SHeejin Ahn     MachineInstr *EndTry = BeginToEnd[Try];
13779f770b36SHeejin Ahn     addTryDelegate(Try, EndTry, UnwindDest);
13789f770b36SHeejin Ahn   }
13799f770b36SHeejin Ahn 
13809f770b36SHeejin Ahn   return true;
1381c4ac74fbSHeejin Ahn }
1382c4ac74fbSHeejin Ahn 
1383ed41945fSHeejin Ahn void WebAssemblyCFGStackify::recalculateScopeTops(MachineFunction &MF) {
1384ed41945fSHeejin Ahn   // Renumber BBs and recalculate ScopeTop info because new BBs might have been
1385ed41945fSHeejin Ahn   // created and inserted during fixing unwind mismatches.
1386ed41945fSHeejin Ahn   MF.RenumberBlocks();
1387ed41945fSHeejin Ahn   ScopeTops.clear();
1388ed41945fSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs());
1389ed41945fSHeejin Ahn   for (auto &MBB : reverse(MF)) {
1390ed41945fSHeejin Ahn     for (auto &MI : reverse(MBB)) {
1391ed41945fSHeejin Ahn       if (ScopeTops[MBB.getNumber()])
1392ed41945fSHeejin Ahn         break;
1393ed41945fSHeejin Ahn       switch (MI.getOpcode()) {
1394ed41945fSHeejin Ahn       case WebAssembly::END_BLOCK:
1395ed41945fSHeejin Ahn       case WebAssembly::END_LOOP:
1396ed41945fSHeejin Ahn       case WebAssembly::END_TRY:
1397ed41945fSHeejin Ahn       case WebAssembly::DELEGATE:
1398ed41945fSHeejin Ahn         updateScopeTops(EndToBegin[&MI]->getParent(), &MBB);
1399ed41945fSHeejin Ahn         break;
1400ed41945fSHeejin Ahn       case WebAssembly::CATCH:
1401ed41945fSHeejin Ahn       case WebAssembly::CATCH_ALL:
1402ed41945fSHeejin Ahn         updateScopeTops(EHPadToTry[&MBB]->getParent(), &MBB);
1403ed41945fSHeejin Ahn         break;
1404ed41945fSHeejin Ahn       }
1405ed41945fSHeejin Ahn     }
1406ed41945fSHeejin Ahn   }
1407ed41945fSHeejin Ahn }
1408ed41945fSHeejin Ahn 
14092726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
14102726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
14112726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
14122726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
14132726b88cSDan Gohman /// that end at the function end need to have a return type signature that
14142726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
14152726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
1416e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
1417e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
14182726b88cSDan Gohman 
14192726b88cSDan Gohman   if (MFI.getResults().empty())
14202726b88cSDan Gohman     return;
14212726b88cSDan Gohman 
14222cb27072SThomas Lively   // MCInstLower will add the proper types to multivalue signatures based on the
14232cb27072SThomas Lively   // function return type
14242cb27072SThomas Lively   WebAssembly::BlockType RetType =
14252cb27072SThomas Lively       MFI.getResults().size() > 1
14262cb27072SThomas Lively           ? WebAssembly::BlockType::Multivalue
14272cb27072SThomas Lively           : WebAssembly::BlockType(
14282cb27072SThomas Lively                 WebAssembly::toValType(MFI.getResults().front()));
14292726b88cSDan Gohman 
1430d25c17f3SHeejin Ahn   SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist;
1431d25c17f3SHeejin Ahn   Worklist.push_back(MF.rbegin()->rbegin());
1432d25c17f3SHeejin Ahn 
1433d25c17f3SHeejin Ahn   auto Process = [&](MachineBasicBlock::reverse_iterator It) {
1434d25c17f3SHeejin Ahn     auto *MBB = It->getParent();
1435d25c17f3SHeejin Ahn     while (It != MBB->rend()) {
1436d25c17f3SHeejin Ahn       MachineInstr &MI = *It++;
1437801bf7ebSShiva Chen       if (MI.isPosition() || MI.isDebugInstr())
14382726b88cSDan Gohman         continue;
14392cb27072SThomas Lively       switch (MI.getOpcode()) {
1440d25c17f3SHeejin Ahn       case WebAssembly::END_TRY: {
1441d25c17f3SHeejin Ahn         // If a 'try''s return type is fixed, both its try body and catch body
1442d25c17f3SHeejin Ahn         // should satisfy the return type, so we need to search 'end'
1443d25c17f3SHeejin Ahn         // instructions before its corresponding 'catch' too.
1444d25c17f3SHeejin Ahn         auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
1445d25c17f3SHeejin Ahn         assert(EHPad);
14469f8b2576SHeejin Ahn         auto NextIt =
14479f8b2576SHeejin Ahn             std::next(WebAssembly::findCatch(EHPad)->getReverseIterator());
14489f8b2576SHeejin Ahn         if (NextIt != EHPad->rend())
14499f8b2576SHeejin Ahn           Worklist.push_back(NextIt);
1450d25c17f3SHeejin Ahn         LLVM_FALLTHROUGH;
1451d25c17f3SHeejin Ahn       }
14522cb27072SThomas Lively       case WebAssembly::END_BLOCK:
14532cb27072SThomas Lively       case WebAssembly::END_LOOP:
145418c56a07SHeejin Ahn         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
14552726b88cSDan Gohman         continue;
14562cb27072SThomas Lively       default:
1457d25c17f3SHeejin Ahn         // Something other than an `end`. We're done for this BB.
14582726b88cSDan Gohman         return;
14592726b88cSDan Gohman       }
14602726b88cSDan Gohman     }
1461d25c17f3SHeejin Ahn     // We've reached the beginning of a BB. Continue the search in the previous
1462d25c17f3SHeejin Ahn     // BB.
1463d25c17f3SHeejin Ahn     Worklist.push_back(MBB->getPrevNode()->rbegin());
1464d25c17f3SHeejin Ahn   };
1465d25c17f3SHeejin Ahn 
1466d25c17f3SHeejin Ahn   while (!Worklist.empty())
1467d25c17f3SHeejin Ahn     Process(Worklist.pop_back_val());
14682cb27072SThomas Lively }
14692726b88cSDan Gohman 
1470d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
1471d934cb88SDan Gohman // were a block.
147218c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF,
1473d934cb88SDan Gohman                                 const WebAssemblyInstrInfo &TII) {
147410b31358SDerek Schuff   BuildMI(MF.back(), MF.back().end(),
147510b31358SDerek Schuff           MF.back().findPrevDebugLoc(MF.back().end()),
1476d934cb88SDan Gohman           TII.get(WebAssembly::END_FUNCTION));
1477d934cb88SDan Gohman }
1478d934cb88SDan Gohman 
1479e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places.
1480e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
1481e76fa9ecSHeejin Ahn   // We allocate one more than the number of blocks in the function to
1482e76fa9ecSHeejin Ahn   // accommodate for the possible fake block we may insert at the end.
1483e76fa9ecSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs() + 1);
14848fe7e86bSDan Gohman   // Place the LOOP for MBB if MBB is the header of a loop.
1485e76fa9ecSHeejin Ahn   for (auto &MBB : MF)
1486e76fa9ecSHeejin Ahn     placeLoopMarker(MBB);
148744a5a4b1SHeejin Ahn 
1488d6f48786SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
148944a5a4b1SHeejin Ahn   for (auto &MBB : MF) {
149044a5a4b1SHeejin Ahn     if (MBB.isEHPad()) {
149144a5a4b1SHeejin Ahn       // Place the TRY for MBB if MBB is the EH pad of an exception.
1492e76fa9ecSHeejin Ahn       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1493e76fa9ecSHeejin Ahn           MF.getFunction().hasPersonalityFn())
1494e76fa9ecSHeejin Ahn         placeTryMarker(MBB);
149544a5a4b1SHeejin Ahn     } else {
149632807932SDan Gohman       // Place the BLOCK for MBB if MBB is branched to from above.
1497e76fa9ecSHeejin Ahn       placeBlockMarker(MBB);
1498950a13cfSDan Gohman     }
149944a5a4b1SHeejin Ahn   }
1500c4ac74fbSHeejin Ahn   // Fix mismatches in unwind destinations induced by linearizing the code.
1501daeead4bSHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1502ed41945fSHeejin Ahn       MF.getFunction().hasPersonalityFn()) {
1503ed41945fSHeejin Ahn     bool Changed = fixCallUnwindMismatches(MF);
1504ed41945fSHeejin Ahn     Changed |= fixCatchUnwindMismatches(MF);
1505ed41945fSHeejin Ahn     if (Changed)
1506ed41945fSHeejin Ahn       recalculateScopeTops(MF);
1507ed41945fSHeejin Ahn   }
150844a5a4b1SHeejin Ahn }
1509950a13cfSDan Gohman 
15102968611fSHeejin Ahn unsigned WebAssemblyCFGStackify::getBranchDepth(
15112968611fSHeejin Ahn     const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
15122968611fSHeejin Ahn   unsigned Depth = 0;
15132968611fSHeejin Ahn   for (auto X : reverse(Stack)) {
15142968611fSHeejin Ahn     if (X.first == MBB)
15152968611fSHeejin Ahn       break;
15162968611fSHeejin Ahn     ++Depth;
15172968611fSHeejin Ahn   }
15182968611fSHeejin Ahn   assert(Depth < Stack.size() && "Branch destination should be in scope");
15192968611fSHeejin Ahn   return Depth;
15202968611fSHeejin Ahn }
15212968611fSHeejin Ahn 
15222968611fSHeejin Ahn unsigned WebAssemblyCFGStackify::getDelegateDepth(
15232968611fSHeejin Ahn     const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
15242968611fSHeejin Ahn   if (MBB == FakeCallerBB)
15252968611fSHeejin Ahn     return Stack.size();
15262968611fSHeejin Ahn   // Delegate's destination is either a catch or a another delegate BB. When the
15272968611fSHeejin Ahn   // destination is another delegate, we can compute the argument in the same
15282968611fSHeejin Ahn   // way as branches, because the target delegate BB only contains the single
15292968611fSHeejin Ahn   // delegate instruction.
15302968611fSHeejin Ahn   if (!MBB->isEHPad()) // Target is a delegate BB
15312968611fSHeejin Ahn     return getBranchDepth(Stack, MBB);
15322968611fSHeejin Ahn 
15332968611fSHeejin Ahn   // When the delegate's destination is a catch BB, we need to use its
15342968611fSHeejin Ahn   // corresponding try's end_try BB because Stack contains each marker's end BB.
15352968611fSHeejin Ahn   // Also we need to check if the end marker instruction matches, because a
15362968611fSHeejin Ahn   // single BB can contain multiple end markers, like this:
15372968611fSHeejin Ahn   // bb:
15382968611fSHeejin Ahn   //   END_BLOCK
15392968611fSHeejin Ahn   //   END_TRY
15402968611fSHeejin Ahn   //   END_BLOCK
15412968611fSHeejin Ahn   //   END_TRY
15422968611fSHeejin Ahn   //   ...
15432968611fSHeejin Ahn   //
15442968611fSHeejin Ahn   // In case of branches getting the immediate that targets any of these is
15452968611fSHeejin Ahn   // fine, but delegate has to exactly target the correct try.
15462968611fSHeejin Ahn   unsigned Depth = 0;
15472968611fSHeejin Ahn   const MachineInstr *EndTry = BeginToEnd[EHPadToTry[MBB]];
15482968611fSHeejin Ahn   for (auto X : reverse(Stack)) {
15492968611fSHeejin Ahn     if (X.first == EndTry->getParent() && X.second == EndTry)
15502968611fSHeejin Ahn       break;
15512968611fSHeejin Ahn     ++Depth;
15522968611fSHeejin Ahn   }
15532968611fSHeejin Ahn   assert(Depth < Stack.size() && "Delegate destination should be in scope");
15542968611fSHeejin Ahn   return Depth;
15552968611fSHeejin Ahn }
15562968611fSHeejin Ahn 
155735f5f797SHeejin Ahn unsigned WebAssemblyCFGStackify::getRethrowDepth(
155835f5f797SHeejin Ahn     const SmallVectorImpl<EndMarkerInfo> &Stack,
155935f5f797SHeejin Ahn     const SmallVectorImpl<const MachineBasicBlock *> &EHPadStack) {
156035f5f797SHeejin Ahn   unsigned Depth = 0;
156135f5f797SHeejin Ahn   // In our current implementation, rethrows always rethrow the exception caught
156235f5f797SHeejin Ahn   // by the innermost enclosing catch. This means while traversing Stack in the
156335f5f797SHeejin Ahn   // reverse direction, when we encounter END_TRY, we should check if the
156435f5f797SHeejin Ahn   // END_TRY corresponds to the current innermost EH pad. For example:
156535f5f797SHeejin Ahn   // try
156635f5f797SHeejin Ahn   //   ...
156735f5f797SHeejin Ahn   // catch         ;; (a)
156835f5f797SHeejin Ahn   //   try
156935f5f797SHeejin Ahn   //     rethrow 1 ;; (b)
157035f5f797SHeejin Ahn   //   catch       ;; (c)
157135f5f797SHeejin Ahn   //     rethrow 0 ;; (d)
157235f5f797SHeejin Ahn   //   end         ;; (e)
157335f5f797SHeejin Ahn   // end           ;; (f)
157435f5f797SHeejin Ahn   //
157535f5f797SHeejin Ahn   // When we are at 'rethrow' (d), while reversely traversing Stack the first
157635f5f797SHeejin Ahn   // 'end' we encounter is the 'end' (e), which corresponds to the 'catch' (c).
157735f5f797SHeejin Ahn   // And 'rethrow' (d) rethrows the exception caught by 'catch' (c), so we stop
157835f5f797SHeejin Ahn   // there and the depth should be 0. But when we are at 'rethrow' (b), it
157935f5f797SHeejin Ahn   // rethrows the exception caught by 'catch' (a), so when traversing Stack
158035f5f797SHeejin Ahn   // reversely, we should skip the 'end' (e) and choose 'end' (f), which
158135f5f797SHeejin Ahn   // corresponds to 'catch' (a).
158235f5f797SHeejin Ahn   for (auto X : reverse(Stack)) {
158335f5f797SHeejin Ahn     const MachineInstr *End = X.second;
158435f5f797SHeejin Ahn     if (End->getOpcode() == WebAssembly::END_TRY) {
158535f5f797SHeejin Ahn       auto *EHPad = TryToEHPad[EndToBegin[End]];
158635f5f797SHeejin Ahn       if (EHPadStack.back() == EHPad)
158735f5f797SHeejin Ahn         break;
158835f5f797SHeejin Ahn     }
158935f5f797SHeejin Ahn     ++Depth;
159035f5f797SHeejin Ahn   }
159135f5f797SHeejin Ahn   assert(Depth < Stack.size() && "Rethrow destination should be in scope");
159235f5f797SHeejin Ahn   return Depth;
159335f5f797SHeejin Ahn }
159435f5f797SHeejin Ahn 
1595e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
15961d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
15972968611fSHeejin Ahn   SmallVector<EndMarkerInfo, 8> Stack;
159835f5f797SHeejin Ahn   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
15991d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
1600e76fa9ecSHeejin Ahn     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) {
1601e76fa9ecSHeejin Ahn       MachineInstr &MI = *I;
16021d68e80fSDan Gohman       switch (MI.getOpcode()) {
16031d68e80fSDan Gohman       case WebAssembly::BLOCK:
1604e76fa9ecSHeejin Ahn       case WebAssembly::TRY:
16052968611fSHeejin Ahn         assert(ScopeTops[Stack.back().first->getNumber()]->getNumber() <=
1606e76fa9ecSHeejin Ahn                    MBB.getNumber() &&
1607e76fa9ecSHeejin Ahn                "Block/try marker should be balanced");
1608e76fa9ecSHeejin Ahn         Stack.pop_back();
1609e76fa9ecSHeejin Ahn         break;
1610e76fa9ecSHeejin Ahn 
16111d68e80fSDan Gohman       case WebAssembly::LOOP:
16122968611fSHeejin Ahn         assert(Stack.back().first == &MBB && "Loop top should be balanced");
16131d68e80fSDan Gohman         Stack.pop_back();
16141d68e80fSDan Gohman         break;
1615e76fa9ecSHeejin Ahn 
16161d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
16172968611fSHeejin Ahn         Stack.push_back(std::make_pair(&MBB, &MI));
1618ed41945fSHeejin Ahn         break;
1619ed41945fSHeejin Ahn 
162035f5f797SHeejin Ahn       case WebAssembly::END_TRY: {
1621ed41945fSHeejin Ahn         // We handle DELEGATE in the default level, because DELEGATE has
16222968611fSHeejin Ahn         // immediate operands to rewrite.
16232968611fSHeejin Ahn         Stack.push_back(std::make_pair(&MBB, &MI));
162435f5f797SHeejin Ahn         auto *EHPad = TryToEHPad[EndToBegin[&MI]];
162535f5f797SHeejin Ahn         EHPadStack.push_back(EHPad);
16261d68e80fSDan Gohman         break;
162735f5f797SHeejin Ahn       }
1628e76fa9ecSHeejin Ahn 
16291d68e80fSDan Gohman       case WebAssembly::END_LOOP:
16302968611fSHeejin Ahn         Stack.push_back(std::make_pair(EndToBegin[&MI]->getParent(), &MI));
16311d68e80fSDan Gohman         break;
1632e76fa9ecSHeejin Ahn 
163335f5f797SHeejin Ahn       case WebAssembly::CATCH:
163435f5f797SHeejin Ahn       case WebAssembly::CATCH_ALL:
163535f5f797SHeejin Ahn         EHPadStack.pop_back();
163635f5f797SHeejin Ahn         break;
163735f5f797SHeejin Ahn 
163835f5f797SHeejin Ahn       case WebAssembly::RETHROW:
163935f5f797SHeejin Ahn         MI.getOperand(0).setImm(getRethrowDepth(Stack, EHPadStack));
164035f5f797SHeejin Ahn         break;
164135f5f797SHeejin Ahn 
16421d68e80fSDan Gohman       default:
16431d68e80fSDan Gohman         if (MI.isTerminator()) {
16441d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
16451d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
16461d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
16471d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
16481d68e80fSDan Gohman           for (auto MO : Ops) {
1649ed41945fSHeejin Ahn             if (MO.isMBB()) {
1650ed41945fSHeejin Ahn               if (MI.getOpcode() == WebAssembly::DELEGATE)
1651ed41945fSHeejin Ahn                 MO = MachineOperand::CreateImm(
16522968611fSHeejin Ahn                     getDelegateDepth(Stack, MO.getMBB()));
1653ed41945fSHeejin Ahn               else
16542968611fSHeejin Ahn                 MO = MachineOperand::CreateImm(
16552968611fSHeejin Ahn                     getBranchDepth(Stack, MO.getMBB()));
1656ed41945fSHeejin Ahn             }
16571d68e80fSDan Gohman             MI.addOperand(MF, MO);
165832807932SDan Gohman           }
16591d68e80fSDan Gohman         }
1660ed41945fSHeejin Ahn 
16612968611fSHeejin Ahn         if (MI.getOpcode() == WebAssembly::DELEGATE)
16622968611fSHeejin Ahn           Stack.push_back(std::make_pair(&MBB, &MI));
16631d68e80fSDan Gohman         break;
16641d68e80fSDan Gohman       }
16651d68e80fSDan Gohman     }
16661d68e80fSDan Gohman   }
16671d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
1668e76fa9ecSHeejin Ahn }
16692726b88cSDan Gohman 
1670ed41945fSHeejin Ahn void WebAssemblyCFGStackify::cleanupFunctionData(MachineFunction &MF) {
1671ed41945fSHeejin Ahn   if (FakeCallerBB)
1672ed41945fSHeejin Ahn     MF.DeleteMachineBasicBlock(FakeCallerBB);
1673ed41945fSHeejin Ahn   AppendixBB = FakeCallerBB = nullptr;
1674ed41945fSHeejin Ahn }
1675ed41945fSHeejin Ahn 
1676e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() {
1677e76fa9ecSHeejin Ahn   ScopeTops.clear();
1678e76fa9ecSHeejin Ahn   BeginToEnd.clear();
1679e76fa9ecSHeejin Ahn   EndToBegin.clear();
1680e76fa9ecSHeejin Ahn   TryToEHPad.clear();
1681e76fa9ecSHeejin Ahn   EHPadToTry.clear();
16821d68e80fSDan Gohman }
168332807932SDan Gohman 
1684950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
1685d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
1686950a13cfSDan Gohman                        "********** Function: "
1687950a13cfSDan Gohman                     << MF.getName() << '\n');
1688cf699b45SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1689950a13cfSDan Gohman 
1690e76fa9ecSHeejin Ahn   releaseMemory();
1691e76fa9ecSHeejin Ahn 
1692e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
16939c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
1694950a13cfSDan Gohman 
1695e76fa9ecSHeejin Ahn   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
1696e76fa9ecSHeejin Ahn   placeMarkers(MF);
1697e76fa9ecSHeejin Ahn 
1698c4ac74fbSHeejin Ahn   // Remove unnecessary instructions possibly introduced by try/end_trys.
1699cf699b45SHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1700cf699b45SHeejin Ahn       MF.getFunction().hasPersonalityFn())
1701cf699b45SHeejin Ahn     removeUnnecessaryInstrs(MF);
1702cf699b45SHeejin Ahn 
1703e76fa9ecSHeejin Ahn   // Convert MBB operands in terminators to relative depth immediates.
1704e76fa9ecSHeejin Ahn   rewriteDepthImmediates(MF);
1705e76fa9ecSHeejin Ahn 
1706e76fa9ecSHeejin Ahn   // Fix up block/loop/try signatures at the end of the function to conform to
1707e76fa9ecSHeejin Ahn   // WebAssembly's rules.
1708e76fa9ecSHeejin Ahn   fixEndsAtEndOfFunction(MF);
1709e76fa9ecSHeejin Ahn 
1710e76fa9ecSHeejin Ahn   // Add an end instruction at the end of the function body.
1711e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1712e76fa9ecSHeejin Ahn   if (!MF.getSubtarget<WebAssemblySubtarget>()
1713e76fa9ecSHeejin Ahn            .getTargetTriple()
1714e76fa9ecSHeejin Ahn            .isOSBinFormatELF())
171518c56a07SHeejin Ahn     appendEndToFunction(MF, TII);
171632807932SDan Gohman 
1717ed41945fSHeejin Ahn   cleanupFunctionData(MF);
1718ed41945fSHeejin Ahn 
17191aaa481fSHeejin Ahn   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1720950a13cfSDan Gohman   return true;
1721950a13cfSDan Gohman }
1722