xref: /src/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyCFGStackify.cpp (revision 415efcecd8b80f68e76376ef2b854cb6f5c84b5a)
1dd58ef01SDimitry Andric //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2dd58ef01SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6dd58ef01SDimitry Andric //
7dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
8dd58ef01SDimitry Andric ///
9dd58ef01SDimitry Andric /// \file
10eb11fae6SDimitry Andric /// This file implements a CFG stacking pass.
11dd58ef01SDimitry Andric ///
12d8e91e46SDimitry Andric /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes,
13d8e91e46SDimitry Andric /// since scope boundaries serve as the labels for WebAssembly's control
14d8e91e46SDimitry Andric /// transfers.
15dd58ef01SDimitry Andric ///
16dd58ef01SDimitry Andric /// This is sufficient to convert arbitrary CFGs into a form that works on
17dd58ef01SDimitry Andric /// WebAssembly, provided that all loops are single-entry.
18dd58ef01SDimitry Andric ///
19d8e91e46SDimitry Andric /// In case we use exceptions, this pass also fixes mismatches in unwind
20d8e91e46SDimitry Andric /// destinations created during transforming CFG into wasm structured format.
21d8e91e46SDimitry Andric ///
22dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
23dd58ef01SDimitry Andric 
24344a3780SDimitry Andric #include "Utils/WebAssemblyTypeUtilities.h"
257ab83427SDimitry Andric #include "WebAssembly.h"
26d8e91e46SDimitry Andric #include "WebAssemblyExceptionInfo.h"
2701095a5dSDimitry Andric #include "WebAssemblyMachineFunctionInfo.h"
28b60736ecSDimitry Andric #include "WebAssemblySortRegion.h"
29dd58ef01SDimitry Andric #include "WebAssemblySubtarget.h"
30b1c73532SDimitry Andric #include "WebAssemblyUtilities.h"
31e6d15924SDimitry Andric #include "llvm/ADT/Statistic.h"
32dd58ef01SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
33dd58ef01SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
341d5ae102SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
35344a3780SDimitry Andric #include "llvm/CodeGen/WasmEHFuncInfo.h"
36d8e91e46SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
37cfca06d7SDimitry Andric #include "llvm/Target/TargetMachine.h"
38dd58ef01SDimitry Andric using namespace llvm;
39b60736ecSDimitry Andric using WebAssembly::SortRegionInfo;
40dd58ef01SDimitry Andric 
41dd58ef01SDimitry Andric #define DEBUG_TYPE "wasm-cfg-stackify"
42dd58ef01SDimitry Andric 
43344a3780SDimitry Andric STATISTIC(NumCallUnwindMismatches, "Number of call unwind mismatches found");
44344a3780SDimitry Andric STATISTIC(NumCatchUnwindMismatches, "Number of catch unwind mismatches found");
45e6d15924SDimitry Andric 
46dd58ef01SDimitry Andric namespace {
47dd58ef01SDimitry Andric class WebAssemblyCFGStackify final : public MachineFunctionPass {
getPassName() const48b915e9e0SDimitry Andric   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
49dd58ef01SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const50dd58ef01SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
51ac9a064cSDimitry Andric     AU.addRequired<MachineDominatorTreeWrapperPass>();
52ac9a064cSDimitry Andric     AU.addRequired<MachineLoopInfoWrapperPass>();
53d8e91e46SDimitry Andric     AU.addRequired<WebAssemblyExceptionInfo>();
54dd58ef01SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
55dd58ef01SDimitry Andric   }
56dd58ef01SDimitry Andric 
57dd58ef01SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
58dd58ef01SDimitry Andric 
59d8e91e46SDimitry Andric   // For each block whose label represents the end of a scope, record the block
60d8e91e46SDimitry Andric   // which holds the beginning of the scope. This will allow us to quickly skip
61d8e91e46SDimitry Andric   // over scoped regions when walking blocks.
62d8e91e46SDimitry Andric   SmallVector<MachineBasicBlock *, 8> ScopeTops;
updateScopeTops(MachineBasicBlock * Begin,MachineBasicBlock * End)63b60736ecSDimitry Andric   void updateScopeTops(MachineBasicBlock *Begin, MachineBasicBlock *End) {
64b60736ecSDimitry Andric     int EndNo = End->getNumber();
65b60736ecSDimitry Andric     if (!ScopeTops[EndNo] || ScopeTops[EndNo]->getNumber() > Begin->getNumber())
66b60736ecSDimitry Andric       ScopeTops[EndNo] = Begin;
67b60736ecSDimitry Andric   }
68d8e91e46SDimitry Andric 
69e6d15924SDimitry Andric   // Placing markers.
70d8e91e46SDimitry Andric   void placeMarkers(MachineFunction &MF);
71d8e91e46SDimitry Andric   void placeBlockMarker(MachineBasicBlock &MBB);
72d8e91e46SDimitry Andric   void placeLoopMarker(MachineBasicBlock &MBB);
73d8e91e46SDimitry Andric   void placeTryMarker(MachineBasicBlock &MBB);
74344a3780SDimitry Andric 
75344a3780SDimitry Andric   // Exception handling related functions
76344a3780SDimitry Andric   bool fixCallUnwindMismatches(MachineFunction &MF);
77344a3780SDimitry Andric   bool fixCatchUnwindMismatches(MachineFunction &MF);
78344a3780SDimitry Andric   void addTryDelegate(MachineInstr *RangeBegin, MachineInstr *RangeEnd,
79344a3780SDimitry Andric                       MachineBasicBlock *DelegateDest);
80344a3780SDimitry Andric   void recalculateScopeTops(MachineFunction &MF);
81e6d15924SDimitry Andric   void removeUnnecessaryInstrs(MachineFunction &MF);
82344a3780SDimitry Andric 
83344a3780SDimitry Andric   // Wrap-up
84344a3780SDimitry Andric   using EndMarkerInfo =
85344a3780SDimitry Andric       std::pair<const MachineBasicBlock *, const MachineInstr *>;
86344a3780SDimitry Andric   unsigned getBranchDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
87344a3780SDimitry Andric                           const MachineBasicBlock *MBB);
88344a3780SDimitry Andric   unsigned getDelegateDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
89344a3780SDimitry Andric                             const MachineBasicBlock *MBB);
90f65bf063SDimitry Andric   unsigned getRethrowDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
91f65bf063SDimitry Andric                            const MachineBasicBlock *EHPadToRethrow);
92d8e91e46SDimitry Andric   void rewriteDepthImmediates(MachineFunction &MF);
93d8e91e46SDimitry Andric   void fixEndsAtEndOfFunction(MachineFunction &MF);
94344a3780SDimitry Andric   void cleanupFunctionData(MachineFunction &MF);
95d8e91e46SDimitry Andric 
96344a3780SDimitry Andric   // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY) or DELEGATE
97344a3780SDimitry Andric   // (in case of TRY).
98d8e91e46SDimitry Andric   DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
99344a3780SDimitry Andric   // For each END_(BLOCK|LOOP|TRY) or DELEGATE, the corresponding
100344a3780SDimitry Andric   // BLOCK|LOOP|TRY.
101d8e91e46SDimitry Andric   DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
102d8e91e46SDimitry Andric   // <TRY marker, EH pad> map
103d8e91e46SDimitry Andric   DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
104d8e91e46SDimitry Andric   // <EH pad, TRY marker> map
105d8e91e46SDimitry Andric   DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
106d8e91e46SDimitry Andric 
107344a3780SDimitry Andric   // We need an appendix block to place 'end_loop' or 'end_try' marker when the
108344a3780SDimitry Andric   // loop / exception bottom block is the last block in a function
109e6d15924SDimitry Andric   MachineBasicBlock *AppendixBB = nullptr;
getAppendixBlock(MachineFunction & MF)110e6d15924SDimitry Andric   MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
111e6d15924SDimitry Andric     if (!AppendixBB) {
112e6d15924SDimitry Andric       AppendixBB = MF.CreateMachineBasicBlock();
113e6d15924SDimitry Andric       // Give it a fake predecessor so that AsmPrinter prints its label.
114e6d15924SDimitry Andric       AppendixBB->addSuccessor(AppendixBB);
115e6d15924SDimitry Andric       MF.push_back(AppendixBB);
116e6d15924SDimitry Andric     }
117e6d15924SDimitry Andric     return AppendixBB;
118e6d15924SDimitry Andric   }
119e6d15924SDimitry Andric 
120344a3780SDimitry Andric   // Before running rewriteDepthImmediates function, 'delegate' has a BB as its
121344a3780SDimitry Andric   // destination operand. getFakeCallerBlock() returns a fake BB that will be
122344a3780SDimitry Andric   // used for the operand when 'delegate' needs to rethrow to the caller. This
123344a3780SDimitry Andric   // will be rewritten as an immediate value that is the number of block depths
124344a3780SDimitry Andric   // + 1 in rewriteDepthImmediates, and this fake BB will be removed at the end
125344a3780SDimitry Andric   // of the pass.
126344a3780SDimitry Andric   MachineBasicBlock *FakeCallerBB = nullptr;
getFakeCallerBlock(MachineFunction & MF)127344a3780SDimitry Andric   MachineBasicBlock *getFakeCallerBlock(MachineFunction &MF) {
128344a3780SDimitry Andric     if (!FakeCallerBB)
129344a3780SDimitry Andric       FakeCallerBB = MF.CreateMachineBasicBlock();
130344a3780SDimitry Andric     return FakeCallerBB;
131344a3780SDimitry Andric   }
132344a3780SDimitry Andric 
133e6d15924SDimitry Andric   // Helper functions to register / unregister scope information created by
134e6d15924SDimitry Andric   // marker instructions.
135d8e91e46SDimitry Andric   void registerScope(MachineInstr *Begin, MachineInstr *End);
136d8e91e46SDimitry Andric   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
137d8e91e46SDimitry Andric                         MachineBasicBlock *EHPad);
138e6d15924SDimitry Andric   void unregisterScope(MachineInstr *Begin);
139d8e91e46SDimitry Andric 
140dd58ef01SDimitry Andric public:
141dd58ef01SDimitry Andric   static char ID; // Pass identification, replacement for typeid
WebAssemblyCFGStackify()142dd58ef01SDimitry Andric   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
~WebAssemblyCFGStackify()143d8e91e46SDimitry Andric   ~WebAssemblyCFGStackify() override { releaseMemory(); }
144d8e91e46SDimitry Andric   void releaseMemory() override;
145dd58ef01SDimitry Andric };
146dd58ef01SDimitry Andric } // end anonymous namespace
147dd58ef01SDimitry Andric 
148dd58ef01SDimitry Andric char WebAssemblyCFGStackify::ID = 0;
149eb11fae6SDimitry Andric INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
150e6d15924SDimitry Andric                 "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false,
151d8e91e46SDimitry Andric                 false)
152eb11fae6SDimitry Andric 
createWebAssemblyCFGStackify()153dd58ef01SDimitry Andric FunctionPass *llvm::createWebAssemblyCFGStackify() {
154dd58ef01SDimitry Andric   return new WebAssemblyCFGStackify();
155dd58ef01SDimitry Andric }
156dd58ef01SDimitry Andric 
157dd58ef01SDimitry Andric /// Test whether Pred has any terminators explicitly branching to MBB, as
158dd58ef01SDimitry Andric /// opposed to falling through. Note that it's possible (eg. in unoptimized
159dd58ef01SDimitry Andric /// code) for a branch instruction to both branch to a block and fallthrough
160dd58ef01SDimitry Andric /// to it, so we check the actual branch operands to see if there are any
161dd58ef01SDimitry Andric /// explicit mentions.
explicitlyBranchesTo(MachineBasicBlock * Pred,MachineBasicBlock * MBB)162e6d15924SDimitry Andric static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
163050e163aSDimitry Andric                                  MachineBasicBlock *MBB) {
164dd58ef01SDimitry Andric   for (MachineInstr &MI : Pred->terminators())
165dd58ef01SDimitry Andric     for (MachineOperand &MO : MI.explicit_operands())
166dd58ef01SDimitry Andric       if (MO.isMBB() && MO.getMBB() == MBB)
167dd58ef01SDimitry Andric         return true;
168dd58ef01SDimitry Andric   return false;
169dd58ef01SDimitry Andric }
170dd58ef01SDimitry Andric 
171d8e91e46SDimitry Andric // Returns an iterator to the earliest position possible within the MBB,
172d8e91e46SDimitry Andric // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
173d8e91e46SDimitry Andric // contains instructions that should go before the marker, and AfterSet contains
174d8e91e46SDimitry Andric // ones that should go after the marker. In this function, AfterSet is only
175c0981da4SDimitry Andric // used for validation checking.
176b60736ecSDimitry Andric template <typename Container>
177d8e91e46SDimitry Andric static MachineBasicBlock::iterator
getEarliestInsertPos(MachineBasicBlock * MBB,const Container & BeforeSet,const Container & AfterSet)178b60736ecSDimitry Andric getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
179b60736ecSDimitry Andric                      const Container &AfterSet) {
180d8e91e46SDimitry Andric   auto InsertPos = MBB->end();
181d8e91e46SDimitry Andric   while (InsertPos != MBB->begin()) {
182d8e91e46SDimitry Andric     if (BeforeSet.count(&*std::prev(InsertPos))) {
183d8e91e46SDimitry Andric #ifndef NDEBUG
184c0981da4SDimitry Andric       // Validation check
185d8e91e46SDimitry Andric       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
186d8e91e46SDimitry Andric         assert(!AfterSet.count(&*std::prev(Pos)));
187d8e91e46SDimitry Andric #endif
188d8e91e46SDimitry Andric       break;
189d8e91e46SDimitry Andric     }
190d8e91e46SDimitry Andric     --InsertPos;
191d8e91e46SDimitry Andric   }
192d8e91e46SDimitry Andric   return InsertPos;
193d8e91e46SDimitry Andric }
194d8e91e46SDimitry Andric 
195d8e91e46SDimitry Andric // Returns an iterator to the latest position possible within the MBB,
196d8e91e46SDimitry Andric // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
197d8e91e46SDimitry Andric // contains instructions that should go before the marker, and AfterSet contains
198d8e91e46SDimitry Andric // ones that should go after the marker. In this function, BeforeSet is only
199c0981da4SDimitry Andric // used for validation checking.
200b60736ecSDimitry Andric template <typename Container>
201d8e91e46SDimitry Andric static MachineBasicBlock::iterator
getLatestInsertPos(MachineBasicBlock * MBB,const Container & BeforeSet,const Container & AfterSet)202b60736ecSDimitry Andric getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
203b60736ecSDimitry Andric                    const Container &AfterSet) {
204d8e91e46SDimitry Andric   auto InsertPos = MBB->begin();
205d8e91e46SDimitry Andric   while (InsertPos != MBB->end()) {
206d8e91e46SDimitry Andric     if (AfterSet.count(&*InsertPos)) {
207d8e91e46SDimitry Andric #ifndef NDEBUG
208c0981da4SDimitry Andric       // Validation check
209d8e91e46SDimitry Andric       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
210d8e91e46SDimitry Andric         assert(!BeforeSet.count(&*Pos));
211d8e91e46SDimitry Andric #endif
212d8e91e46SDimitry Andric       break;
213d8e91e46SDimitry Andric     }
214d8e91e46SDimitry Andric     ++InsertPos;
215d8e91e46SDimitry Andric   }
216d8e91e46SDimitry Andric   return InsertPos;
217d8e91e46SDimitry Andric }
218d8e91e46SDimitry Andric 
registerScope(MachineInstr * Begin,MachineInstr * End)219d8e91e46SDimitry Andric void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
220d8e91e46SDimitry Andric                                            MachineInstr *End) {
221d8e91e46SDimitry Andric   BeginToEnd[Begin] = End;
222d8e91e46SDimitry Andric   EndToBegin[End] = Begin;
223d8e91e46SDimitry Andric }
224d8e91e46SDimitry Andric 
225344a3780SDimitry Andric // When 'End' is not an 'end_try' but 'delegate, EHPad is nullptr.
registerTryScope(MachineInstr * Begin,MachineInstr * End,MachineBasicBlock * EHPad)226d8e91e46SDimitry Andric void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
227d8e91e46SDimitry Andric                                               MachineInstr *End,
228d8e91e46SDimitry Andric                                               MachineBasicBlock *EHPad) {
229d8e91e46SDimitry Andric   registerScope(Begin, End);
230d8e91e46SDimitry Andric   TryToEHPad[Begin] = EHPad;
231d8e91e46SDimitry Andric   EHPadToTry[EHPad] = Begin;
232d8e91e46SDimitry Andric }
233d8e91e46SDimitry Andric 
unregisterScope(MachineInstr * Begin)234e6d15924SDimitry Andric void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
235e6d15924SDimitry Andric   assert(BeginToEnd.count(Begin));
236e6d15924SDimitry Andric   MachineInstr *End = BeginToEnd[Begin];
237e6d15924SDimitry Andric   assert(EndToBegin.count(End));
238e6d15924SDimitry Andric   BeginToEnd.erase(Begin);
239e6d15924SDimitry Andric   EndToBegin.erase(End);
240e6d15924SDimitry Andric   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
241e6d15924SDimitry Andric   if (EHPad) {
242e6d15924SDimitry Andric     assert(EHPadToTry.count(EHPad));
243e6d15924SDimitry Andric     TryToEHPad.erase(Begin);
244e6d15924SDimitry Andric     EHPadToTry.erase(EHPad);
245e6d15924SDimitry Andric   }
246d8e91e46SDimitry Andric }
247d8e91e46SDimitry Andric 
248dd58ef01SDimitry Andric /// Insert a BLOCK marker for branches to MBB (if needed).
249e6d15924SDimitry Andric // TODO Consider a more generalized way of handling block (and also loop and
250e6d15924SDimitry Andric // try) signatures when we implement the multi-value proposal later.
placeBlockMarker(MachineBasicBlock & MBB)251d8e91e46SDimitry Andric void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
252e6d15924SDimitry Andric   assert(!MBB.isEHPad());
253d8e91e46SDimitry Andric   MachineFunction &MF = *MBB.getParent();
254ac9a064cSDimitry Andric   auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
255d8e91e46SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
256d8e91e46SDimitry Andric   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
257d8e91e46SDimitry Andric 
258dd58ef01SDimitry Andric   // First compute the nearest common dominator of all forward non-fallthrough
259dd58ef01SDimitry Andric   // predecessors so that we minimize the time that the BLOCK is on the stack,
260dd58ef01SDimitry Andric   // which reduces overall stack height.
261dd58ef01SDimitry Andric   MachineBasicBlock *Header = nullptr;
262dd58ef01SDimitry Andric   bool IsBranchedTo = false;
263dd58ef01SDimitry Andric   int MBBNumber = MBB.getNumber();
264d8e91e46SDimitry Andric   for (MachineBasicBlock *Pred : MBB.predecessors()) {
265dd58ef01SDimitry Andric     if (Pred->getNumber() < MBBNumber) {
266dd58ef01SDimitry Andric       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
267b60736ecSDimitry Andric       if (explicitlyBranchesTo(Pred, &MBB))
268dd58ef01SDimitry Andric         IsBranchedTo = true;
269dd58ef01SDimitry Andric     }
270d8e91e46SDimitry Andric   }
271dd58ef01SDimitry Andric   if (!Header)
272dd58ef01SDimitry Andric     return;
273dd58ef01SDimitry Andric   if (!IsBranchedTo)
274dd58ef01SDimitry Andric     return;
275dd58ef01SDimitry Andric 
276dd58ef01SDimitry Andric   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
277e6d15924SDimitry Andric   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
278dd58ef01SDimitry Andric 
279dd58ef01SDimitry Andric   // If the nearest common dominator is inside a more deeply nested context,
280dd58ef01SDimitry Andric   // walk out to the nearest scope which isn't more deeply nested.
281dd58ef01SDimitry Andric   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
282dd58ef01SDimitry Andric     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
283dd58ef01SDimitry Andric       if (ScopeTop->getNumber() > Header->getNumber()) {
284dd58ef01SDimitry Andric         // Skip over an intervening scope.
285e6d15924SDimitry Andric         I = std::next(ScopeTop->getIterator());
286dd58ef01SDimitry Andric       } else {
287dd58ef01SDimitry Andric         // We found a scope level at an appropriate depth.
288dd58ef01SDimitry Andric         Header = ScopeTop;
289dd58ef01SDimitry Andric         break;
290dd58ef01SDimitry Andric       }
291dd58ef01SDimitry Andric     }
292dd58ef01SDimitry Andric   }
293dd58ef01SDimitry Andric 
294dd58ef01SDimitry Andric   // Decide where in Header to put the BLOCK.
295d8e91e46SDimitry Andric 
296d8e91e46SDimitry Andric   // Instructions that should go before the BLOCK.
297d8e91e46SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
298d8e91e46SDimitry Andric   // Instructions that should go after the BLOCK.
299d8e91e46SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> AfterSet;
300d8e91e46SDimitry Andric   for (const auto &MI : *Header) {
301e6d15924SDimitry Andric     // If there is a previously placed LOOP marker and the bottom block of the
302e6d15924SDimitry Andric     // loop is above MBB, it should be after the BLOCK, because the loop is
303e6d15924SDimitry Andric     // nested in this BLOCK. Otherwise it should be before the BLOCK.
304e6d15924SDimitry Andric     if (MI.getOpcode() == WebAssembly::LOOP) {
305e6d15924SDimitry Andric       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
306e6d15924SDimitry Andric       if (MBB.getNumber() > LoopBottom->getNumber())
307d8e91e46SDimitry Andric         AfterSet.insert(&MI);
308d8e91e46SDimitry Andric #ifndef NDEBUG
309d8e91e46SDimitry Andric       else
310d8e91e46SDimitry Andric         BeforeSet.insert(&MI);
311d8e91e46SDimitry Andric #endif
312d8e91e46SDimitry Andric     }
313d8e91e46SDimitry Andric 
314cfca06d7SDimitry Andric     // If there is a previously placed BLOCK/TRY marker and its corresponding
315cfca06d7SDimitry Andric     // END marker is before the current BLOCK's END marker, that should be
316cfca06d7SDimitry Andric     // placed after this BLOCK. Otherwise it should be placed before this BLOCK
317cfca06d7SDimitry Andric     // marker.
318e6d15924SDimitry Andric     if (MI.getOpcode() == WebAssembly::BLOCK ||
319cfca06d7SDimitry Andric         MI.getOpcode() == WebAssembly::TRY) {
320cfca06d7SDimitry Andric       if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
321d8e91e46SDimitry Andric         AfterSet.insert(&MI);
322cfca06d7SDimitry Andric #ifndef NDEBUG
323cfca06d7SDimitry Andric       else
324cfca06d7SDimitry Andric         BeforeSet.insert(&MI);
325cfca06d7SDimitry Andric #endif
326cfca06d7SDimitry Andric     }
327d8e91e46SDimitry Andric 
328d8e91e46SDimitry Andric #ifndef NDEBUG
329d8e91e46SDimitry Andric     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
330d8e91e46SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
331d8e91e46SDimitry Andric         MI.getOpcode() == WebAssembly::END_LOOP ||
332d8e91e46SDimitry Andric         MI.getOpcode() == WebAssembly::END_TRY)
333d8e91e46SDimitry Andric       BeforeSet.insert(&MI);
334d8e91e46SDimitry Andric #endif
335d8e91e46SDimitry Andric 
336d8e91e46SDimitry Andric     // Terminators should go after the BLOCK.
337d8e91e46SDimitry Andric     if (MI.isTerminator())
338d8e91e46SDimitry Andric       AfterSet.insert(&MI);
339d8e91e46SDimitry Andric   }
340d8e91e46SDimitry Andric 
341d8e91e46SDimitry Andric   // Local expression tree should go after the BLOCK.
342d8e91e46SDimitry Andric   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
343d8e91e46SDimitry Andric        --I) {
344d8e91e46SDimitry Andric     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
345d8e91e46SDimitry Andric       continue;
346d8e91e46SDimitry Andric     if (WebAssembly::isChild(*std::prev(I), MFI))
347d8e91e46SDimitry Andric       AfterSet.insert(&*std::prev(I));
348d8e91e46SDimitry Andric     else
349d8e91e46SDimitry Andric       break;
350dd58ef01SDimitry Andric   }
351dd58ef01SDimitry Andric 
352dd58ef01SDimitry Andric   // Add the BLOCK.
3531d5ae102SDimitry Andric   WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
354e6d15924SDimitry Andric   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
355eb11fae6SDimitry Andric   MachineInstr *Begin =
356eb11fae6SDimitry Andric       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
357b915e9e0SDimitry Andric               TII.get(WebAssembly::BLOCK))
358e6d15924SDimitry Andric           .addImm(int64_t(ReturnType));
359050e163aSDimitry Andric 
360d8e91e46SDimitry Andric   // Decide where in Header to put the END_BLOCK.
361d8e91e46SDimitry Andric   BeforeSet.clear();
362d8e91e46SDimitry Andric   AfterSet.clear();
363d8e91e46SDimitry Andric   for (auto &MI : MBB) {
364d8e91e46SDimitry Andric #ifndef NDEBUG
365d8e91e46SDimitry Andric     // END_BLOCK should precede existing LOOP and TRY markers.
366d8e91e46SDimitry Andric     if (MI.getOpcode() == WebAssembly::LOOP ||
367d8e91e46SDimitry Andric         MI.getOpcode() == WebAssembly::TRY)
368d8e91e46SDimitry Andric       AfterSet.insert(&MI);
369d8e91e46SDimitry Andric #endif
370d8e91e46SDimitry Andric 
371d8e91e46SDimitry Andric     // If there is a previously placed END_LOOP marker and the header of the
372d8e91e46SDimitry Andric     // loop is above this block's header, the END_LOOP should be placed after
373d8e91e46SDimitry Andric     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
374d8e91e46SDimitry Andric     // should be placed before the BLOCK. The same for END_TRY.
375d8e91e46SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_LOOP ||
376d8e91e46SDimitry Andric         MI.getOpcode() == WebAssembly::END_TRY) {
377d8e91e46SDimitry Andric       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
378d8e91e46SDimitry Andric         BeforeSet.insert(&MI);
379d8e91e46SDimitry Andric #ifndef NDEBUG
380d8e91e46SDimitry Andric       else
381d8e91e46SDimitry Andric         AfterSet.insert(&MI);
382d8e91e46SDimitry Andric #endif
383d8e91e46SDimitry Andric     }
384d8e91e46SDimitry Andric   }
385d8e91e46SDimitry Andric 
386050e163aSDimitry Andric   // Mark the end of the block.
387e6d15924SDimitry Andric   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
388eb11fae6SDimitry Andric   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
389b915e9e0SDimitry Andric                               TII.get(WebAssembly::END_BLOCK));
390d8e91e46SDimitry Andric   registerScope(Begin, End);
391dd58ef01SDimitry Andric 
392dd58ef01SDimitry Andric   // Track the farthest-spanning scope that ends at this point.
393b60736ecSDimitry Andric   updateScopeTops(Header, &MBB);
394dd58ef01SDimitry Andric }
395dd58ef01SDimitry Andric 
396dd58ef01SDimitry Andric /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
placeLoopMarker(MachineBasicBlock & MBB)397d8e91e46SDimitry Andric void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
398d8e91e46SDimitry Andric   MachineFunction &MF = *MBB.getParent();
399ac9a064cSDimitry Andric   const auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
400b60736ecSDimitry Andric   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
401b60736ecSDimitry Andric   SortRegionInfo SRI(MLI, WEI);
402d8e91e46SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
403d8e91e46SDimitry Andric 
404dd58ef01SDimitry Andric   MachineLoop *Loop = MLI.getLoopFor(&MBB);
405dd58ef01SDimitry Andric   if (!Loop || Loop->getHeader() != &MBB)
406dd58ef01SDimitry Andric     return;
407dd58ef01SDimitry Andric 
408dd58ef01SDimitry Andric   // The operand of a LOOP is the first block after the loop. If the loop is the
409dd58ef01SDimitry Andric   // bottom of the function, insert a dummy block at the end.
410b60736ecSDimitry Andric   MachineBasicBlock *Bottom = SRI.getBottom(Loop);
411e6d15924SDimitry Andric   auto Iter = std::next(Bottom->getIterator());
412dd58ef01SDimitry Andric   if (Iter == MF.end()) {
413e6d15924SDimitry Andric     getAppendixBlock(MF);
414e6d15924SDimitry Andric     Iter = std::next(Bottom->getIterator());
415dd58ef01SDimitry Andric   }
416dd58ef01SDimitry Andric   MachineBasicBlock *AfterLoop = &*Iter;
417dd58ef01SDimitry Andric 
418d8e91e46SDimitry Andric   // Decide where in Header to put the LOOP.
419d8e91e46SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
420d8e91e46SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> AfterSet;
421d8e91e46SDimitry Andric   for (const auto &MI : MBB) {
422d8e91e46SDimitry Andric     // LOOP marker should be after any existing loop that ends here. Otherwise
423d8e91e46SDimitry Andric     // we assume the instruction belongs to the loop.
424d8e91e46SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_LOOP)
425d8e91e46SDimitry Andric       BeforeSet.insert(&MI);
426d8e91e46SDimitry Andric #ifndef NDEBUG
427d8e91e46SDimitry Andric     else
428d8e91e46SDimitry Andric       AfterSet.insert(&MI);
429d8e91e46SDimitry Andric #endif
430d8e91e46SDimitry Andric   }
431d8e91e46SDimitry Andric 
432d8e91e46SDimitry Andric   // Mark the beginning of the loop.
433e6d15924SDimitry Andric   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
434eb11fae6SDimitry Andric   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
435b915e9e0SDimitry Andric                                 TII.get(WebAssembly::LOOP))
4361d5ae102SDimitry Andric                             .addImm(int64_t(WebAssembly::BlockType::Void));
437050e163aSDimitry Andric 
438d8e91e46SDimitry Andric   // Decide where in Header to put the END_LOOP.
439d8e91e46SDimitry Andric   BeforeSet.clear();
440d8e91e46SDimitry Andric   AfterSet.clear();
441d8e91e46SDimitry Andric #ifndef NDEBUG
442d8e91e46SDimitry Andric   for (const auto &MI : MBB)
443d8e91e46SDimitry Andric     // Existing END_LOOP markers belong to parent loops of this loop
444d8e91e46SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_LOOP)
445d8e91e46SDimitry Andric       AfterSet.insert(&MI);
446d8e91e46SDimitry Andric #endif
447d8e91e46SDimitry Andric 
448d8e91e46SDimitry Andric   // Mark the end of the loop (using arbitrary debug location that branched to
449d8e91e46SDimitry Andric   // the loop end as its location).
450e6d15924SDimitry Andric   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
451e6d15924SDimitry Andric   DebugLoc EndDL = AfterLoop->pred_empty()
452e6d15924SDimitry Andric                        ? DebugLoc()
453e6d15924SDimitry Andric                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
454d8e91e46SDimitry Andric   MachineInstr *End =
455d8e91e46SDimitry Andric       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
456d8e91e46SDimitry Andric   registerScope(Begin, End);
457dd58ef01SDimitry Andric 
458dd58ef01SDimitry Andric   assert((!ScopeTops[AfterLoop->getNumber()] ||
459dd58ef01SDimitry Andric           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
46001095a5dSDimitry Andric          "With block sorting the outermost loop for a block should be first.");
461b60736ecSDimitry Andric   updateScopeTops(&MBB, AfterLoop);
462dd58ef01SDimitry Andric }
463dd58ef01SDimitry Andric 
placeTryMarker(MachineBasicBlock & MBB)464d8e91e46SDimitry Andric void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
465e6d15924SDimitry Andric   assert(MBB.isEHPad());
466d8e91e46SDimitry Andric   MachineFunction &MF = *MBB.getParent();
467ac9a064cSDimitry Andric   auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
468d8e91e46SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
469ac9a064cSDimitry Andric   const auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
470d8e91e46SDimitry Andric   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
471b60736ecSDimitry Andric   SortRegionInfo SRI(MLI, WEI);
472d8e91e46SDimitry Andric   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
473d8e91e46SDimitry Andric 
474d8e91e46SDimitry Andric   // Compute the nearest common dominator of all unwind predecessors
475d8e91e46SDimitry Andric   MachineBasicBlock *Header = nullptr;
476d8e91e46SDimitry Andric   int MBBNumber = MBB.getNumber();
477d8e91e46SDimitry Andric   for (auto *Pred : MBB.predecessors()) {
478d8e91e46SDimitry Andric     if (Pred->getNumber() < MBBNumber) {
479d8e91e46SDimitry Andric       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
480e6d15924SDimitry Andric       assert(!explicitlyBranchesTo(Pred, &MBB) &&
481d8e91e46SDimitry Andric              "Explicit branch to an EH pad!");
482d8e91e46SDimitry Andric     }
483d8e91e46SDimitry Andric   }
484d8e91e46SDimitry Andric   if (!Header)
485d8e91e46SDimitry Andric     return;
486d8e91e46SDimitry Andric 
487d8e91e46SDimitry Andric   // If this try is at the bottom of the function, insert a dummy block at the
488d8e91e46SDimitry Andric   // end.
489d8e91e46SDimitry Andric   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
490d8e91e46SDimitry Andric   assert(WE);
491b60736ecSDimitry Andric   MachineBasicBlock *Bottom = SRI.getBottom(WE);
492d8e91e46SDimitry Andric 
493e6d15924SDimitry Andric   auto Iter = std::next(Bottom->getIterator());
494d8e91e46SDimitry Andric   if (Iter == MF.end()) {
495e6d15924SDimitry Andric     getAppendixBlock(MF);
496e6d15924SDimitry Andric     Iter = std::next(Bottom->getIterator());
497d8e91e46SDimitry Andric   }
498e6d15924SDimitry Andric   MachineBasicBlock *Cont = &*Iter;
499d8e91e46SDimitry Andric 
500e6d15924SDimitry Andric   assert(Cont != &MF.front());
501e6d15924SDimitry Andric   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
502d8e91e46SDimitry Andric 
503d8e91e46SDimitry Andric   // If the nearest common dominator is inside a more deeply nested context,
504d8e91e46SDimitry Andric   // walk out to the nearest scope which isn't more deeply nested.
505d8e91e46SDimitry Andric   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
506d8e91e46SDimitry Andric     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
507d8e91e46SDimitry Andric       if (ScopeTop->getNumber() > Header->getNumber()) {
508d8e91e46SDimitry Andric         // Skip over an intervening scope.
509e6d15924SDimitry Andric         I = std::next(ScopeTop->getIterator());
510d8e91e46SDimitry Andric       } else {
511d8e91e46SDimitry Andric         // We found a scope level at an appropriate depth.
512d8e91e46SDimitry Andric         Header = ScopeTop;
513d8e91e46SDimitry Andric         break;
514d8e91e46SDimitry Andric       }
515d8e91e46SDimitry Andric     }
516d8e91e46SDimitry Andric   }
517d8e91e46SDimitry Andric 
518d8e91e46SDimitry Andric   // Decide where in Header to put the TRY.
519d8e91e46SDimitry Andric 
520e6d15924SDimitry Andric   // Instructions that should go before the TRY.
521d8e91e46SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
522e6d15924SDimitry Andric   // Instructions that should go after the TRY.
523d8e91e46SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> AfterSet;
524d8e91e46SDimitry Andric   for (const auto &MI : *Header) {
525e6d15924SDimitry Andric     // If there is a previously placed LOOP marker and the bottom block of the
526e6d15924SDimitry Andric     // loop is above MBB, it should be after the TRY, because the loop is nested
527e6d15924SDimitry Andric     // in this TRY. Otherwise it should be before the TRY.
528d8e91e46SDimitry Andric     if (MI.getOpcode() == WebAssembly::LOOP) {
529e6d15924SDimitry Andric       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
530e6d15924SDimitry Andric       if (MBB.getNumber() > LoopBottom->getNumber())
531d8e91e46SDimitry Andric         AfterSet.insert(&MI);
532d8e91e46SDimitry Andric #ifndef NDEBUG
533d8e91e46SDimitry Andric       else
534d8e91e46SDimitry Andric         BeforeSet.insert(&MI);
535d8e91e46SDimitry Andric #endif
536d8e91e46SDimitry Andric     }
537d8e91e46SDimitry Andric 
538e6d15924SDimitry Andric     // All previously inserted BLOCK/TRY markers should be after the TRY because
539e6d15924SDimitry Andric     // they are all nested trys.
540e6d15924SDimitry Andric     if (MI.getOpcode() == WebAssembly::BLOCK ||
541e6d15924SDimitry Andric         MI.getOpcode() == WebAssembly::TRY)
542d8e91e46SDimitry Andric       AfterSet.insert(&MI);
543d8e91e46SDimitry Andric 
544d8e91e46SDimitry Andric #ifndef NDEBUG
545e6d15924SDimitry Andric     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
546e6d15924SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
547e6d15924SDimitry Andric         MI.getOpcode() == WebAssembly::END_LOOP ||
548d8e91e46SDimitry Andric         MI.getOpcode() == WebAssembly::END_TRY)
549d8e91e46SDimitry Andric       BeforeSet.insert(&MI);
550d8e91e46SDimitry Andric #endif
551d8e91e46SDimitry Andric 
552d8e91e46SDimitry Andric     // Terminators should go after the TRY.
553d8e91e46SDimitry Andric     if (MI.isTerminator())
554d8e91e46SDimitry Andric       AfterSet.insert(&MI);
555d8e91e46SDimitry Andric   }
556d8e91e46SDimitry Andric 
5571d5ae102SDimitry Andric   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
5581d5ae102SDimitry Andric   // contain the call within it. So the call should go after the TRY. The
5591d5ae102SDimitry Andric   // exception is when the header's terminator is a rethrow instruction, in
5601d5ae102SDimitry Andric   // which case that instruction, not a call instruction before it, is gonna
5611d5ae102SDimitry Andric   // throw.
5621d5ae102SDimitry Andric   MachineInstr *ThrowingCall = nullptr;
5631d5ae102SDimitry Andric   if (MBB.isPredecessor(Header)) {
5641d5ae102SDimitry Andric     auto TermPos = Header->getFirstTerminator();
5651d5ae102SDimitry Andric     if (TermPos == Header->end() ||
5661d5ae102SDimitry Andric         TermPos->getOpcode() != WebAssembly::RETHROW) {
5671d5ae102SDimitry Andric       for (auto &MI : reverse(*Header)) {
5681d5ae102SDimitry Andric         if (MI.isCall()) {
5691d5ae102SDimitry Andric           AfterSet.insert(&MI);
5701d5ae102SDimitry Andric           ThrowingCall = &MI;
5711d5ae102SDimitry Andric           // Possibly throwing calls are usually wrapped by EH_LABEL
5721d5ae102SDimitry Andric           // instructions. We don't want to split them and the call.
5731d5ae102SDimitry Andric           if (MI.getIterator() != Header->begin() &&
5741d5ae102SDimitry Andric               std::prev(MI.getIterator())->isEHLabel()) {
5751d5ae102SDimitry Andric             AfterSet.insert(&*std::prev(MI.getIterator()));
5761d5ae102SDimitry Andric             ThrowingCall = &*std::prev(MI.getIterator());
5771d5ae102SDimitry Andric           }
5781d5ae102SDimitry Andric           break;
5791d5ae102SDimitry Andric         }
5801d5ae102SDimitry Andric       }
5811d5ae102SDimitry Andric     }
5821d5ae102SDimitry Andric   }
5831d5ae102SDimitry Andric 
584d8e91e46SDimitry Andric   // Local expression tree should go after the TRY.
5851d5ae102SDimitry Andric   // For BLOCK placement, we start the search from the previous instruction of a
5861d5ae102SDimitry Andric   // BB's terminator, but in TRY's case, we should start from the previous
5871d5ae102SDimitry Andric   // instruction of a call that can throw, or a EH_LABEL that precedes the call,
5881d5ae102SDimitry Andric   // because the return values of the call's previous instructions can be
5891d5ae102SDimitry Andric   // stackified and consumed by the throwing call.
5901d5ae102SDimitry Andric   auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
5911d5ae102SDimitry Andric                                     : Header->getFirstTerminator();
5921d5ae102SDimitry Andric   for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
593d8e91e46SDimitry Andric     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
594d8e91e46SDimitry Andric       continue;
595d8e91e46SDimitry Andric     if (WebAssembly::isChild(*std::prev(I), MFI))
596d8e91e46SDimitry Andric       AfterSet.insert(&*std::prev(I));
597d8e91e46SDimitry Andric     else
598d8e91e46SDimitry Andric       break;
599d8e91e46SDimitry Andric   }
600d8e91e46SDimitry Andric 
601d8e91e46SDimitry Andric   // Add the TRY.
602e6d15924SDimitry Andric   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
603d8e91e46SDimitry Andric   MachineInstr *Begin =
604d8e91e46SDimitry Andric       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
605d8e91e46SDimitry Andric               TII.get(WebAssembly::TRY))
6061d5ae102SDimitry Andric           .addImm(int64_t(WebAssembly::BlockType::Void));
607d8e91e46SDimitry Andric 
608d8e91e46SDimitry Andric   // Decide where in Header to put the END_TRY.
609d8e91e46SDimitry Andric   BeforeSet.clear();
610d8e91e46SDimitry Andric   AfterSet.clear();
611e6d15924SDimitry Andric   for (const auto &MI : *Cont) {
612d8e91e46SDimitry Andric #ifndef NDEBUG
613e6d15924SDimitry Andric     // END_TRY should precede existing LOOP and BLOCK markers.
614e6d15924SDimitry Andric     if (MI.getOpcode() == WebAssembly::LOOP ||
615e6d15924SDimitry Andric         MI.getOpcode() == WebAssembly::BLOCK)
616d8e91e46SDimitry Andric       AfterSet.insert(&MI);
617d8e91e46SDimitry Andric 
618d8e91e46SDimitry Andric     // All END_TRY markers placed earlier belong to exceptions that contains
619d8e91e46SDimitry Andric     // this one.
620d8e91e46SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_TRY)
621d8e91e46SDimitry Andric       AfterSet.insert(&MI);
622d8e91e46SDimitry Andric #endif
623d8e91e46SDimitry Andric 
624d8e91e46SDimitry Andric     // If there is a previously placed END_LOOP marker and its header is after
625d8e91e46SDimitry Andric     // where TRY marker is, this loop is contained within the 'catch' part, so
626d8e91e46SDimitry Andric     // the END_TRY marker should go after that. Otherwise, the whole try-catch
627d8e91e46SDimitry Andric     // is contained within this loop, so the END_TRY should go before that.
628d8e91e46SDimitry Andric     if (MI.getOpcode() == WebAssembly::END_LOOP) {
629e6d15924SDimitry Andric       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
630e6d15924SDimitry Andric       // are in the same BB, LOOP is always before TRY.
631e6d15924SDimitry Andric       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
632d8e91e46SDimitry Andric         BeforeSet.insert(&MI);
633d8e91e46SDimitry Andric #ifndef NDEBUG
634d8e91e46SDimitry Andric       else
635d8e91e46SDimitry Andric         AfterSet.insert(&MI);
636d8e91e46SDimitry Andric #endif
637d8e91e46SDimitry Andric     }
638e6d15924SDimitry Andric 
639e6d15924SDimitry Andric     // It is not possible for an END_BLOCK to be already in this block.
640d8e91e46SDimitry Andric   }
641d8e91e46SDimitry Andric 
642d8e91e46SDimitry Andric   // Mark the end of the TRY.
643e6d15924SDimitry Andric   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
644d8e91e46SDimitry Andric   MachineInstr *End =
645e6d15924SDimitry Andric       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
646d8e91e46SDimitry Andric               TII.get(WebAssembly::END_TRY));
647d8e91e46SDimitry Andric   registerTryScope(Begin, End, &MBB);
648d8e91e46SDimitry Andric 
649e6d15924SDimitry Andric   // Track the farthest-spanning scope that ends at this point. We create two
650e6d15924SDimitry Andric   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
651e6d15924SDimitry Andric   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
652e6d15924SDimitry Andric   // markers should not span across 'catch'. For example, this should not
653e6d15924SDimitry Andric   // happen:
654e6d15924SDimitry Andric   //
655e6d15924SDimitry Andric   // try
656e6d15924SDimitry Andric   //   block     --|  (X)
657e6d15924SDimitry Andric   // catch         |
658e6d15924SDimitry Andric   //   end_block --|
659e6d15924SDimitry Andric   // end_try
660b60736ecSDimitry Andric   for (auto *End : {&MBB, Cont})
661b60736ecSDimitry Andric     updateScopeTops(Header, End);
662e6d15924SDimitry Andric }
663e6d15924SDimitry Andric 
removeUnnecessaryInstrs(MachineFunction & MF)664e6d15924SDimitry Andric void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
665e6d15924SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
666e6d15924SDimitry Andric 
667e6d15924SDimitry Andric   // When there is an unconditional branch right before a catch instruction and
668e6d15924SDimitry Andric   // it branches to the end of end_try marker, we don't need the branch, because
669b1c73532SDimitry Andric   // if there is no exception, the control flow transfers to that point anyway.
670e6d15924SDimitry Andric   // bb0:
671e6d15924SDimitry Andric   //   try
672e6d15924SDimitry Andric   //     ...
673e6d15924SDimitry Andric   //     br bb2      <- Not necessary
674b60736ecSDimitry Andric   // bb1 (ehpad):
675e6d15924SDimitry Andric   //   catch
676e6d15924SDimitry Andric   //     ...
677b60736ecSDimitry Andric   // bb2:            <- Continuation BB
678e6d15924SDimitry Andric   //   end
679b60736ecSDimitry Andric   //
680b60736ecSDimitry Andric   // A more involved case: When the BB where 'end' is located is an another EH
681b60736ecSDimitry Andric   // pad, the Cont (= continuation) BB is that EH pad's 'end' BB. For example,
682b60736ecSDimitry Andric   // bb0:
683b60736ecSDimitry Andric   //   try
684b60736ecSDimitry Andric   //     try
685b60736ecSDimitry Andric   //       ...
686b60736ecSDimitry Andric   //       br bb3      <- Not necessary
687b60736ecSDimitry Andric   // bb1 (ehpad):
688b60736ecSDimitry Andric   //     catch
689b60736ecSDimitry Andric   // bb2 (ehpad):
690b60736ecSDimitry Andric   //     end
691b60736ecSDimitry Andric   //   catch
692b60736ecSDimitry Andric   //     ...
693b60736ecSDimitry Andric   // bb3:            <- Continuation BB
694b60736ecSDimitry Andric   //   end
695b60736ecSDimitry Andric   //
696b60736ecSDimitry Andric   // When the EH pad at hand is bb1, its matching end_try is in bb2. But it is
697b60736ecSDimitry Andric   // another EH pad, so bb0's continuation BB becomes bb3. So 'br bb3' in the
698b60736ecSDimitry Andric   // code can be deleted. This is why we run 'while' until 'Cont' is not an EH
699b60736ecSDimitry Andric   // pad.
700e6d15924SDimitry Andric   for (auto &MBB : MF) {
701e6d15924SDimitry Andric     if (!MBB.isEHPad())
702e6d15924SDimitry Andric       continue;
703e6d15924SDimitry Andric 
704e6d15924SDimitry Andric     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
705e6d15924SDimitry Andric     SmallVector<MachineOperand, 4> Cond;
706e6d15924SDimitry Andric     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
707b60736ecSDimitry Andric 
708b60736ecSDimitry Andric     MachineBasicBlock *Cont = &MBB;
709b60736ecSDimitry Andric     while (Cont->isEHPad()) {
710b60736ecSDimitry Andric       MachineInstr *Try = EHPadToTry[Cont];
711b60736ecSDimitry Andric       MachineInstr *EndTry = BeginToEnd[Try];
712344a3780SDimitry Andric       // We started from an EH pad, so the end marker cannot be a delegate
713344a3780SDimitry Andric       assert(EndTry->getOpcode() != WebAssembly::DELEGATE);
714b60736ecSDimitry Andric       Cont = EndTry->getParent();
715b60736ecSDimitry Andric     }
716b60736ecSDimitry Andric 
717e6d15924SDimitry Andric     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
718cfca06d7SDimitry Andric     // This condition means either
719cfca06d7SDimitry Andric     // 1. This BB ends with a single unconditional branch whose destinaion is
720cfca06d7SDimitry Andric     //    Cont.
721cfca06d7SDimitry Andric     // 2. This BB ends with a conditional branch followed by an unconditional
722cfca06d7SDimitry Andric     //    branch, and the unconditional branch's destination is Cont.
723cfca06d7SDimitry Andric     // In both cases, we want to remove the last (= unconditional) branch.
724e6d15924SDimitry Andric     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
725cfca06d7SDimitry Andric                        (!Cond.empty() && FBB && FBB == Cont))) {
726cfca06d7SDimitry Andric       bool ErasedUncondBr = false;
727cfca06d7SDimitry Andric       (void)ErasedUncondBr;
728cfca06d7SDimitry Andric       for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
729cfca06d7SDimitry Andric            I != E; --I) {
730cfca06d7SDimitry Andric         auto PrevI = std::prev(I);
731cfca06d7SDimitry Andric         if (PrevI->isTerminator()) {
732cfca06d7SDimitry Andric           assert(PrevI->getOpcode() == WebAssembly::BR);
733cfca06d7SDimitry Andric           PrevI->eraseFromParent();
734cfca06d7SDimitry Andric           ErasedUncondBr = true;
735cfca06d7SDimitry Andric           break;
736cfca06d7SDimitry Andric         }
737cfca06d7SDimitry Andric       }
738cfca06d7SDimitry Andric       assert(ErasedUncondBr && "Unconditional branch not erased!");
739cfca06d7SDimitry Andric     }
740e6d15924SDimitry Andric   }
741e6d15924SDimitry Andric 
742e6d15924SDimitry Andric   // When there are block / end_block markers that overlap with try / end_try
743e6d15924SDimitry Andric   // markers, and the block and try markers' return types are the same, the
744e6d15924SDimitry Andric   // block /end_block markers are not necessary, because try / end_try markers
745e6d15924SDimitry Andric   // also can serve as boundaries for branches.
746e6d15924SDimitry Andric   // block         <- Not necessary
747e6d15924SDimitry Andric   //   try
748e6d15924SDimitry Andric   //     ...
749e6d15924SDimitry Andric   //   catch
750e6d15924SDimitry Andric   //     ...
751e6d15924SDimitry Andric   //   end
752e6d15924SDimitry Andric   // end           <- Not necessary
753e6d15924SDimitry Andric   SmallVector<MachineInstr *, 32> ToDelete;
754e6d15924SDimitry Andric   for (auto &MBB : MF) {
755e6d15924SDimitry Andric     for (auto &MI : MBB) {
756e6d15924SDimitry Andric       if (MI.getOpcode() != WebAssembly::TRY)
757e6d15924SDimitry Andric         continue;
758e6d15924SDimitry Andric       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
759344a3780SDimitry Andric       if (EndTry->getOpcode() == WebAssembly::DELEGATE)
760344a3780SDimitry Andric         continue;
761344a3780SDimitry Andric 
762e6d15924SDimitry Andric       MachineBasicBlock *TryBB = Try->getParent();
763e6d15924SDimitry Andric       MachineBasicBlock *Cont = EndTry->getParent();
764e6d15924SDimitry Andric       int64_t RetType = Try->getOperand(0).getImm();
765e6d15924SDimitry Andric       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
766e6d15924SDimitry Andric            B != TryBB->begin() && E != Cont->end() &&
767e6d15924SDimitry Andric            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
768e6d15924SDimitry Andric            E->getOpcode() == WebAssembly::END_BLOCK &&
769e6d15924SDimitry Andric            std::prev(B)->getOperand(0).getImm() == RetType;
770e6d15924SDimitry Andric            --B, ++E) {
771e6d15924SDimitry Andric         ToDelete.push_back(&*std::prev(B));
772e6d15924SDimitry Andric         ToDelete.push_back(&*E);
773e6d15924SDimitry Andric       }
774e6d15924SDimitry Andric     }
775e6d15924SDimitry Andric   }
776e6d15924SDimitry Andric   for (auto *MI : ToDelete) {
777e6d15924SDimitry Andric     if (MI->getOpcode() == WebAssembly::BLOCK)
778e6d15924SDimitry Andric       unregisterScope(MI);
779e6d15924SDimitry Andric     MI->eraseFromParent();
780e6d15924SDimitry Andric   }
781e6d15924SDimitry Andric }
782e6d15924SDimitry Andric 
7831d5ae102SDimitry Andric // When MBB is split into MBB and Split, we should unstackify defs in MBB that
7841d5ae102SDimitry Andric // have their uses in Split.
unstackifyVRegsUsedInSplitBB(MachineBasicBlock & MBB,MachineBasicBlock & Split)785344a3780SDimitry Andric static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB,
786344a3780SDimitry Andric                                          MachineBasicBlock &Split) {
787b60736ecSDimitry Andric   MachineFunction &MF = *MBB.getParent();
788b60736ecSDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
789b60736ecSDimitry Andric   auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
790b60736ecSDimitry Andric   auto &MRI = MF.getRegInfo();
791b60736ecSDimitry Andric 
7921d5ae102SDimitry Andric   for (auto &MI : Split) {
7931d5ae102SDimitry Andric     for (auto &MO : MI.explicit_uses()) {
794e3b55780SDimitry Andric       if (!MO.isReg() || MO.getReg().isPhysical())
7951d5ae102SDimitry Andric         continue;
7961d5ae102SDimitry Andric       if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
7971d5ae102SDimitry Andric         if (Def->getParent() == &MBB)
7981d5ae102SDimitry Andric           MFI.unstackifyVReg(MO.getReg());
7991d5ae102SDimitry Andric     }
8001d5ae102SDimitry Andric   }
801cfca06d7SDimitry Andric 
802cfca06d7SDimitry Andric   // In RegStackify, when a register definition is used multiple times,
803cfca06d7SDimitry Andric   //    Reg = INST ...
804cfca06d7SDimitry Andric   //    INST ..., Reg, ...
805cfca06d7SDimitry Andric   //    INST ..., Reg, ...
806cfca06d7SDimitry Andric   //    INST ..., Reg, ...
807cfca06d7SDimitry Andric   //
808cfca06d7SDimitry Andric   // we introduce a TEE, which has the following form:
809cfca06d7SDimitry Andric   //    DefReg = INST ...
810cfca06d7SDimitry Andric   //    TeeReg, Reg = TEE_... DefReg
811cfca06d7SDimitry Andric   //    INST ..., TeeReg, ...
812cfca06d7SDimitry Andric   //    INST ..., Reg, ...
813cfca06d7SDimitry Andric   //    INST ..., Reg, ...
814cfca06d7SDimitry Andric   // with DefReg and TeeReg stackified but Reg not stackified.
815cfca06d7SDimitry Andric   //
816cfca06d7SDimitry Andric   // But the invariant that TeeReg should be stackified can be violated while we
817cfca06d7SDimitry Andric   // unstackify registers in the split BB above. In this case, we convert TEEs
818cfca06d7SDimitry Andric   // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
819cfca06d7SDimitry Andric   //    DefReg = INST ...
820cfca06d7SDimitry Andric   //    TeeReg = COPY DefReg
821cfca06d7SDimitry Andric   //    Reg = COPY DefReg
822cfca06d7SDimitry Andric   //    INST ..., TeeReg, ...
823cfca06d7SDimitry Andric   //    INST ..., Reg, ...
824cfca06d7SDimitry Andric   //    INST ..., Reg, ...
825c0981da4SDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
826cfca06d7SDimitry Andric     if (!WebAssembly::isTee(MI.getOpcode()))
827cfca06d7SDimitry Andric       continue;
828cfca06d7SDimitry Andric     Register TeeReg = MI.getOperand(0).getReg();
829cfca06d7SDimitry Andric     Register Reg = MI.getOperand(1).getReg();
830cfca06d7SDimitry Andric     Register DefReg = MI.getOperand(2).getReg();
831cfca06d7SDimitry Andric     if (!MFI.isVRegStackified(TeeReg)) {
832cfca06d7SDimitry Andric       // Now we are not using TEE anymore, so unstackify DefReg too
833cfca06d7SDimitry Andric       MFI.unstackifyVReg(DefReg);
8341f917f69SDimitry Andric       unsigned CopyOpc =
8351f917f69SDimitry Andric           WebAssembly::getCopyOpcodeForRegClass(MRI.getRegClass(DefReg));
836cfca06d7SDimitry Andric       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
837cfca06d7SDimitry Andric           .addReg(DefReg);
838cfca06d7SDimitry Andric       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
839cfca06d7SDimitry Andric       MI.eraseFromParent();
840cfca06d7SDimitry Andric     }
841cfca06d7SDimitry Andric   }
8421d5ae102SDimitry Andric }
8431d5ae102SDimitry Andric 
844344a3780SDimitry Andric // Wrap the given range of instruction with try-delegate. RangeBegin and
845344a3780SDimitry Andric // RangeEnd are inclusive.
addTryDelegate(MachineInstr * RangeBegin,MachineInstr * RangeEnd,MachineBasicBlock * DelegateDest)846344a3780SDimitry Andric void WebAssemblyCFGStackify::addTryDelegate(MachineInstr *RangeBegin,
847344a3780SDimitry Andric                                             MachineInstr *RangeEnd,
848344a3780SDimitry Andric                                             MachineBasicBlock *DelegateDest) {
849344a3780SDimitry Andric   auto *BeginBB = RangeBegin->getParent();
850344a3780SDimitry Andric   auto *EndBB = RangeEnd->getParent();
851344a3780SDimitry Andric   MachineFunction &MF = *BeginBB->getParent();
852344a3780SDimitry Andric   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
853344a3780SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
854344a3780SDimitry Andric 
855344a3780SDimitry Andric   // Local expression tree before the first call of this range should go
856344a3780SDimitry Andric   // after the nested TRY.
857344a3780SDimitry Andric   SmallPtrSet<const MachineInstr *, 4> AfterSet;
858344a3780SDimitry Andric   AfterSet.insert(RangeBegin);
859344a3780SDimitry Andric   for (auto I = MachineBasicBlock::iterator(RangeBegin), E = BeginBB->begin();
860344a3780SDimitry Andric        I != E; --I) {
861344a3780SDimitry Andric     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
862344a3780SDimitry Andric       continue;
863344a3780SDimitry Andric     if (WebAssembly::isChild(*std::prev(I), MFI))
864344a3780SDimitry Andric       AfterSet.insert(&*std::prev(I));
865344a3780SDimitry Andric     else
866344a3780SDimitry Andric       break;
867e6d15924SDimitry Andric   }
868d8e91e46SDimitry Andric 
869344a3780SDimitry Andric   // Create the nested try instruction.
870344a3780SDimitry Andric   auto TryPos = getLatestInsertPos(
871344a3780SDimitry Andric       BeginBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet);
872344a3780SDimitry Andric   MachineInstr *Try = BuildMI(*BeginBB, TryPos, RangeBegin->getDebugLoc(),
873344a3780SDimitry Andric                               TII.get(WebAssembly::TRY))
874344a3780SDimitry Andric                           .addImm(int64_t(WebAssembly::BlockType::Void));
875344a3780SDimitry Andric 
876344a3780SDimitry Andric   // Create a BB to insert the 'delegate' instruction.
877344a3780SDimitry Andric   MachineBasicBlock *DelegateBB = MF.CreateMachineBasicBlock();
878344a3780SDimitry Andric   // If the destination of 'delegate' is not the caller, adds the destination to
879344a3780SDimitry Andric   // the BB's successors.
880344a3780SDimitry Andric   if (DelegateDest != FakeCallerBB)
881344a3780SDimitry Andric     DelegateBB->addSuccessor(DelegateDest);
882344a3780SDimitry Andric 
883344a3780SDimitry Andric   auto SplitPos = std::next(RangeEnd->getIterator());
884344a3780SDimitry Andric   if (SplitPos == EndBB->end()) {
885344a3780SDimitry Andric     // If the range's end instruction is at the end of the BB, insert the new
886344a3780SDimitry Andric     // delegate BB after the current BB.
887344a3780SDimitry Andric     MF.insert(std::next(EndBB->getIterator()), DelegateBB);
888344a3780SDimitry Andric     EndBB->addSuccessor(DelegateBB);
889344a3780SDimitry Andric 
890344a3780SDimitry Andric   } else {
891344a3780SDimitry Andric     // When the split pos is in the middle of a BB, we split the BB into two and
892344a3780SDimitry Andric     // put the 'delegate' BB in between. We normally create a split BB and make
893344a3780SDimitry Andric     // it a successor of the original BB (PostSplit == true), but in case the BB
894344a3780SDimitry Andric     // is an EH pad and the split pos is before 'catch', we should preserve the
895344a3780SDimitry Andric     // BB's property, including that it is an EH pad, in the later part of the
896344a3780SDimitry Andric     // BB, where 'catch' is. In this case we set PostSplit to false.
897344a3780SDimitry Andric     bool PostSplit = true;
898344a3780SDimitry Andric     if (EndBB->isEHPad()) {
899344a3780SDimitry Andric       for (auto I = MachineBasicBlock::iterator(SplitPos), E = EndBB->end();
900344a3780SDimitry Andric            I != E; ++I) {
901344a3780SDimitry Andric         if (WebAssembly::isCatch(I->getOpcode())) {
902344a3780SDimitry Andric           PostSplit = false;
903050e163aSDimitry Andric           break;
904050e163aSDimitry Andric         }
905344a3780SDimitry Andric       }
906344a3780SDimitry Andric     }
907344a3780SDimitry Andric 
908344a3780SDimitry Andric     MachineBasicBlock *PreBB = nullptr, *PostBB = nullptr;
909344a3780SDimitry Andric     if (PostSplit) {
910344a3780SDimitry Andric       // If the range's end instruction is in the middle of the BB, we split the
911344a3780SDimitry Andric       // BB into two and insert the delegate BB in between.
912344a3780SDimitry Andric       // - Before:
913344a3780SDimitry Andric       // bb:
914344a3780SDimitry Andric       //   range_end
915344a3780SDimitry Andric       //   other_insts
916344a3780SDimitry Andric       //
917344a3780SDimitry Andric       // - After:
918344a3780SDimitry Andric       // pre_bb: (previous 'bb')
919344a3780SDimitry Andric       //   range_end
920344a3780SDimitry Andric       // delegate_bb: (new)
921344a3780SDimitry Andric       //   delegate
922344a3780SDimitry Andric       // post_bb: (new)
923344a3780SDimitry Andric       //   other_insts
924344a3780SDimitry Andric       PreBB = EndBB;
925344a3780SDimitry Andric       PostBB = MF.CreateMachineBasicBlock();
926344a3780SDimitry Andric       MF.insert(std::next(PreBB->getIterator()), PostBB);
927344a3780SDimitry Andric       MF.insert(std::next(PreBB->getIterator()), DelegateBB);
928344a3780SDimitry Andric       PostBB->splice(PostBB->end(), PreBB, SplitPos, PreBB->end());
929344a3780SDimitry Andric       PostBB->transferSuccessors(PreBB);
930344a3780SDimitry Andric     } else {
931344a3780SDimitry Andric       // - Before:
932344a3780SDimitry Andric       // ehpad:
933344a3780SDimitry Andric       //   range_end
934344a3780SDimitry Andric       //   catch
935344a3780SDimitry Andric       //   ...
936344a3780SDimitry Andric       //
937344a3780SDimitry Andric       // - After:
938344a3780SDimitry Andric       // pre_bb: (new)
939344a3780SDimitry Andric       //   range_end
940344a3780SDimitry Andric       // delegate_bb: (new)
941344a3780SDimitry Andric       //   delegate
942344a3780SDimitry Andric       // post_bb: (previous 'ehpad')
943344a3780SDimitry Andric       //   catch
944344a3780SDimitry Andric       //   ...
945344a3780SDimitry Andric       assert(EndBB->isEHPad());
946344a3780SDimitry Andric       PreBB = MF.CreateMachineBasicBlock();
947344a3780SDimitry Andric       PostBB = EndBB;
948344a3780SDimitry Andric       MF.insert(PostBB->getIterator(), PreBB);
949344a3780SDimitry Andric       MF.insert(PostBB->getIterator(), DelegateBB);
950344a3780SDimitry Andric       PreBB->splice(PreBB->end(), PostBB, PostBB->begin(), SplitPos);
951344a3780SDimitry Andric       // We don't need to transfer predecessors of the EH pad to 'PreBB',
952344a3780SDimitry Andric       // because an EH pad's predecessors are all through unwind edges and they
953344a3780SDimitry Andric       // should still unwind to the EH pad, not PreBB.
954344a3780SDimitry Andric     }
955344a3780SDimitry Andric     unstackifyVRegsUsedInSplitBB(*PreBB, *PostBB);
956344a3780SDimitry Andric     PreBB->addSuccessor(DelegateBB);
957344a3780SDimitry Andric     PreBB->addSuccessor(PostBB);
958344a3780SDimitry Andric   }
959344a3780SDimitry Andric 
960344a3780SDimitry Andric   // Add 'delegate' instruction in the delegate BB created above.
961344a3780SDimitry Andric   MachineInstr *Delegate = BuildMI(DelegateBB, RangeEnd->getDebugLoc(),
962344a3780SDimitry Andric                                    TII.get(WebAssembly::DELEGATE))
963344a3780SDimitry Andric                                .addMBB(DelegateDest);
964344a3780SDimitry Andric   registerTryScope(Try, Delegate, nullptr);
965344a3780SDimitry Andric }
966344a3780SDimitry Andric 
fixCallUnwindMismatches(MachineFunction & MF)967344a3780SDimitry Andric bool WebAssemblyCFGStackify::fixCallUnwindMismatches(MachineFunction &MF) {
968344a3780SDimitry Andric   // Linearizing the control flow by placing TRY / END_TRY markers can create
969344a3780SDimitry Andric   // mismatches in unwind destinations for throwing instructions, such as calls.
970344a3780SDimitry Andric   //
971344a3780SDimitry Andric   // We use the 'delegate' instruction to fix the unwind mismatches. 'delegate'
972344a3780SDimitry Andric   // instruction delegates an exception to an outer 'catch'. It can target not
973344a3780SDimitry Andric   // only 'catch' but all block-like structures including another 'delegate',
974344a3780SDimitry Andric   // but with slightly different semantics than branches. When it targets a
975344a3780SDimitry Andric   // 'catch', it will delegate the exception to that catch. It is being
976344a3780SDimitry Andric   // discussed how to define the semantics when 'delegate''s target is a non-try
977344a3780SDimitry Andric   // block: it will either be a validation failure or it will target the next
978344a3780SDimitry Andric   // outer try-catch. But anyway our LLVM backend currently does not generate
979344a3780SDimitry Andric   // such code. The example below illustrates where the 'delegate' instruction
980344a3780SDimitry Andric   // in the middle will delegate the exception to, depending on the value of N.
981344a3780SDimitry Andric   // try
982344a3780SDimitry Andric   //   try
983344a3780SDimitry Andric   //     block
984344a3780SDimitry Andric   //       try
985344a3780SDimitry Andric   //         try
986344a3780SDimitry Andric   //           call @foo
987344a3780SDimitry Andric   //         delegate N    ;; Where will this delegate to?
988344a3780SDimitry Andric   //       catch           ;; N == 0
989344a3780SDimitry Andric   //       end
990344a3780SDimitry Andric   //     end               ;; N == 1 (invalid; will not be generated)
991344a3780SDimitry Andric   //   delegate            ;; N == 2
992344a3780SDimitry Andric   // catch                 ;; N == 3
993344a3780SDimitry Andric   // end
994344a3780SDimitry Andric   //                       ;; N == 4 (to caller)
995344a3780SDimitry Andric 
996344a3780SDimitry Andric   // 1. When an instruction may throw, but the EH pad it will unwind to can be
997344a3780SDimitry Andric   //    different from the original CFG.
998344a3780SDimitry Andric   //
999344a3780SDimitry Andric   // Example: we have the following CFG:
1000344a3780SDimitry Andric   // bb0:
1001344a3780SDimitry Andric   //   call @foo    ; if it throws, unwind to bb2
1002344a3780SDimitry Andric   // bb1:
1003344a3780SDimitry Andric   //   call @bar    ; if it throws, unwind to bb3
1004344a3780SDimitry Andric   // bb2 (ehpad):
1005344a3780SDimitry Andric   //   catch
1006344a3780SDimitry Andric   //   ...
1007344a3780SDimitry Andric   // bb3 (ehpad)
1008344a3780SDimitry Andric   //   catch
1009344a3780SDimitry Andric   //   ...
1010344a3780SDimitry Andric   //
1011344a3780SDimitry Andric   // And the CFG is sorted in this order. Then after placing TRY markers, it
1012344a3780SDimitry Andric   // will look like: (BB markers are omitted)
1013344a3780SDimitry Andric   // try
1014344a3780SDimitry Andric   //   try
1015344a3780SDimitry Andric   //     call @foo
1016344a3780SDimitry Andric   //     call @bar   ;; if it throws, unwind to bb3
1017344a3780SDimitry Andric   //   catch         ;; ehpad (bb2)
1018344a3780SDimitry Andric   //     ...
1019344a3780SDimitry Andric   //   end_try
1020344a3780SDimitry Andric   // catch           ;; ehpad (bb3)
1021344a3780SDimitry Andric   //   ...
1022344a3780SDimitry Andric   // end_try
1023344a3780SDimitry Andric   //
1024344a3780SDimitry Andric   // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it
1025344a3780SDimitry Andric   // is supposed to end up. We solve this problem by wrapping the mismatching
1026344a3780SDimitry Andric   // call with an inner try-delegate that rethrows the exception to the right
1027344a3780SDimitry Andric   // 'catch'.
1028344a3780SDimitry Andric   //
1029344a3780SDimitry Andric   // try
1030344a3780SDimitry Andric   //   try
1031344a3780SDimitry Andric   //     call @foo
1032344a3780SDimitry Andric   //     try               ;; (new)
1033344a3780SDimitry Andric   //       call @bar
1034344a3780SDimitry Andric   //     delegate 1 (bb3)  ;; (new)
1035344a3780SDimitry Andric   //   catch               ;; ehpad (bb2)
1036344a3780SDimitry Andric   //     ...
1037344a3780SDimitry Andric   //   end_try
1038344a3780SDimitry Andric   // catch                 ;; ehpad (bb3)
1039344a3780SDimitry Andric   //   ...
1040344a3780SDimitry Andric   // end_try
1041344a3780SDimitry Andric   //
1042344a3780SDimitry Andric   // ---
1043344a3780SDimitry Andric   // 2. The same as 1, but in this case an instruction unwinds to a caller
1044344a3780SDimitry Andric   //    function and not another EH pad.
1045344a3780SDimitry Andric   //
1046344a3780SDimitry Andric   // Example: we have the following CFG:
1047344a3780SDimitry Andric   // bb0:
1048344a3780SDimitry Andric   //   call @foo       ; if it throws, unwind to bb2
1049344a3780SDimitry Andric   // bb1:
1050344a3780SDimitry Andric   //   call @bar       ; if it throws, unwind to caller
1051344a3780SDimitry Andric   // bb2 (ehpad):
1052344a3780SDimitry Andric   //   catch
1053344a3780SDimitry Andric   //   ...
1054344a3780SDimitry Andric   //
1055344a3780SDimitry Andric   // And the CFG is sorted in this order. Then after placing TRY markers, it
1056344a3780SDimitry Andric   // will look like:
1057344a3780SDimitry Andric   // try
1058344a3780SDimitry Andric   //   call @foo
1059344a3780SDimitry Andric   //   call @bar     ;; if it throws, unwind to caller
1060344a3780SDimitry Andric   // catch           ;; ehpad (bb2)
1061344a3780SDimitry Andric   //   ...
1062344a3780SDimitry Andric   // end_try
1063344a3780SDimitry Andric   //
1064344a3780SDimitry Andric   // Now if bar() throws, it is going to end up ip in bb2, when it is supposed
1065344a3780SDimitry Andric   // throw up to the caller. We solve this problem in the same way, but in this
1066344a3780SDimitry Andric   // case 'delegate's immediate argument is the number of block depths + 1,
1067344a3780SDimitry Andric   // which means it rethrows to the caller.
1068344a3780SDimitry Andric   // try
1069344a3780SDimitry Andric   //   call @foo
1070344a3780SDimitry Andric   //   try                  ;; (new)
1071344a3780SDimitry Andric   //     call @bar
1072344a3780SDimitry Andric   //   delegate 1 (caller)  ;; (new)
1073344a3780SDimitry Andric   // catch                  ;; ehpad (bb2)
1074344a3780SDimitry Andric   //   ...
1075344a3780SDimitry Andric   // end_try
1076344a3780SDimitry Andric   //
1077344a3780SDimitry Andric   // Before rewriteDepthImmediates, delegate's argument is a BB. In case of the
1078344a3780SDimitry Andric   // caller, it will take a fake BB generated by getFakeCallerBlock(), which
1079344a3780SDimitry Andric   // will be converted to a correct immediate argument later.
1080344a3780SDimitry Andric   //
1081344a3780SDimitry Andric   // In case there are multiple calls in a BB that may throw to the caller, they
1082344a3780SDimitry Andric   // can be wrapped together in one nested try-delegate scope. (In 1, this
1083344a3780SDimitry Andric   // couldn't happen, because may-throwing instruction there had an unwind
1084344a3780SDimitry Andric   // destination, i.e., it was an invoke before, and there could be only one
1085344a3780SDimitry Andric   // invoke within a BB.)
1086344a3780SDimitry Andric 
1087344a3780SDimitry Andric   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
1088344a3780SDimitry Andric   // Range of intructions to be wrapped in a new nested try/catch. A range
1089344a3780SDimitry Andric   // exists in a single BB and does not span multiple BBs.
1090344a3780SDimitry Andric   using TryRange = std::pair<MachineInstr *, MachineInstr *>;
1091344a3780SDimitry Andric   // In original CFG, <unwind destination BB, a vector of try ranges>
1092344a3780SDimitry Andric   DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges;
1093344a3780SDimitry Andric 
1094344a3780SDimitry Andric   // Gather possibly throwing calls (i.e., previously invokes) whose current
1095344a3780SDimitry Andric   // unwind destination is not the same as the original CFG. (Case 1)
1096344a3780SDimitry Andric 
1097344a3780SDimitry Andric   for (auto &MBB : reverse(MF)) {
1098344a3780SDimitry Andric     bool SeenThrowableInstInBB = false;
1099344a3780SDimitry Andric     for (auto &MI : reverse(MBB)) {
1100344a3780SDimitry Andric       if (MI.getOpcode() == WebAssembly::TRY)
1101344a3780SDimitry Andric         EHPadStack.pop_back();
1102344a3780SDimitry Andric       else if (WebAssembly::isCatch(MI.getOpcode()))
1103344a3780SDimitry Andric         EHPadStack.push_back(MI.getParent());
1104344a3780SDimitry Andric 
1105344a3780SDimitry Andric       // In this loop we only gather calls that have an EH pad to unwind. So
1106344a3780SDimitry Andric       // there will be at most 1 such call (= invoke) in a BB, so after we've
1107344a3780SDimitry Andric       // seen one, we can skip the rest of BB. Also if MBB has no EH pad
1108344a3780SDimitry Andric       // successor or MI does not throw, this is not an invoke.
1109344a3780SDimitry Andric       if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() ||
1110344a3780SDimitry Andric           !WebAssembly::mayThrow(MI))
1111344a3780SDimitry Andric         continue;
1112344a3780SDimitry Andric       SeenThrowableInstInBB = true;
1113344a3780SDimitry Andric 
1114344a3780SDimitry Andric       // If the EH pad on the stack top is where this instruction should unwind
1115344a3780SDimitry Andric       // next, we're good.
1116344a3780SDimitry Andric       MachineBasicBlock *UnwindDest = getFakeCallerBlock(MF);
1117344a3780SDimitry Andric       for (auto *Succ : MBB.successors()) {
1118344a3780SDimitry Andric         // Even though semantically a BB can have multiple successors in case an
1119344a3780SDimitry Andric         // exception is not caught by a catchpad, in our backend implementation
1120344a3780SDimitry Andric         // it is guaranteed that a BB can have at most one EH pad successor. For
1121344a3780SDimitry Andric         // details, refer to comments in findWasmUnwindDestinations function in
1122344a3780SDimitry Andric         // SelectionDAGBuilder.cpp.
1123344a3780SDimitry Andric         if (Succ->isEHPad()) {
1124344a3780SDimitry Andric           UnwindDest = Succ;
1125344a3780SDimitry Andric           break;
1126344a3780SDimitry Andric         }
1127344a3780SDimitry Andric       }
1128344a3780SDimitry Andric       if (EHPadStack.back() == UnwindDest)
1129344a3780SDimitry Andric         continue;
1130344a3780SDimitry Andric 
1131344a3780SDimitry Andric       // Include EH_LABELs in the range before and afer the invoke
1132344a3780SDimitry Andric       MachineInstr *RangeBegin = &MI, *RangeEnd = &MI;
1133344a3780SDimitry Andric       if (RangeBegin->getIterator() != MBB.begin() &&
1134344a3780SDimitry Andric           std::prev(RangeBegin->getIterator())->isEHLabel())
1135344a3780SDimitry Andric         RangeBegin = &*std::prev(RangeBegin->getIterator());
1136344a3780SDimitry Andric       if (std::next(RangeEnd->getIterator()) != MBB.end() &&
1137344a3780SDimitry Andric           std::next(RangeEnd->getIterator())->isEHLabel())
1138344a3780SDimitry Andric         RangeEnd = &*std::next(RangeEnd->getIterator());
1139344a3780SDimitry Andric 
1140344a3780SDimitry Andric       // If not, record the range.
1141344a3780SDimitry Andric       UnwindDestToTryRanges[UnwindDest].push_back(
1142344a3780SDimitry Andric           TryRange(RangeBegin, RangeEnd));
1143344a3780SDimitry Andric       LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = " << MBB.getName()
1144344a3780SDimitry Andric                         << "\nCall = " << MI
1145344a3780SDimitry Andric                         << "\nOriginal dest = " << UnwindDest->getName()
1146344a3780SDimitry Andric                         << "  Current dest = " << EHPadStack.back()->getName()
1147344a3780SDimitry Andric                         << "\n\n");
1148344a3780SDimitry Andric     }
1149344a3780SDimitry Andric   }
1150344a3780SDimitry Andric 
1151344a3780SDimitry Andric   assert(EHPadStack.empty());
1152344a3780SDimitry Andric 
1153344a3780SDimitry Andric   // Gather possibly throwing calls that are supposed to unwind up to the caller
1154344a3780SDimitry Andric   // if they throw, but currently unwind to an incorrect destination. Unlike the
1155344a3780SDimitry Andric   // loop above, there can be multiple calls within a BB that unwind to the
1156344a3780SDimitry Andric   // caller, which we should group together in a range. (Case 2)
1157344a3780SDimitry Andric 
1158344a3780SDimitry Andric   MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive
1159344a3780SDimitry Andric 
1160344a3780SDimitry Andric   // Record the range.
1161344a3780SDimitry Andric   auto RecordCallerMismatchRange = [&](const MachineBasicBlock *CurrentDest) {
1162344a3780SDimitry Andric     UnwindDestToTryRanges[getFakeCallerBlock(MF)].push_back(
1163344a3780SDimitry Andric         TryRange(RangeBegin, RangeEnd));
1164344a3780SDimitry Andric     LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = "
1165344a3780SDimitry Andric                       << RangeBegin->getParent()->getName()
1166344a3780SDimitry Andric                       << "\nRange begin = " << *RangeBegin
1167344a3780SDimitry Andric                       << "Range end = " << *RangeEnd
1168344a3780SDimitry Andric                       << "\nOriginal dest = caller  Current dest = "
1169344a3780SDimitry Andric                       << CurrentDest->getName() << "\n\n");
1170344a3780SDimitry Andric     RangeBegin = RangeEnd = nullptr; // Reset range pointers
1171344a3780SDimitry Andric   };
1172344a3780SDimitry Andric 
1173344a3780SDimitry Andric   for (auto &MBB : reverse(MF)) {
1174344a3780SDimitry Andric     bool SeenThrowableInstInBB = false;
1175344a3780SDimitry Andric     for (auto &MI : reverse(MBB)) {
1176344a3780SDimitry Andric       bool MayThrow = WebAssembly::mayThrow(MI);
1177344a3780SDimitry Andric 
1178344a3780SDimitry Andric       // If MBB has an EH pad successor and this is the last instruction that
1179344a3780SDimitry Andric       // may throw, this instruction unwinds to the EH pad and not to the
1180344a3780SDimitry Andric       // caller.
1181344a3780SDimitry Andric       if (MBB.hasEHPadSuccessor() && MayThrow && !SeenThrowableInstInBB)
1182344a3780SDimitry Andric         SeenThrowableInstInBB = true;
1183344a3780SDimitry Andric 
1184344a3780SDimitry Andric       // We wrap up the current range when we see a marker even if we haven't
1185344a3780SDimitry Andric       // finished a BB.
1186344a3780SDimitry Andric       else if (RangeEnd && WebAssembly::isMarker(MI.getOpcode()))
1187344a3780SDimitry Andric         RecordCallerMismatchRange(EHPadStack.back());
1188344a3780SDimitry Andric 
1189344a3780SDimitry Andric       // If EHPadStack is empty, that means it correctly unwinds to the caller
1190344a3780SDimitry Andric       // if it throws, so we're good. If MI does not throw, we're good too.
1191344a3780SDimitry Andric       else if (EHPadStack.empty() || !MayThrow) {
1192344a3780SDimitry Andric       }
1193344a3780SDimitry Andric 
1194344a3780SDimitry Andric       // We found an instruction that unwinds to the caller but currently has an
1195344a3780SDimitry Andric       // incorrect unwind destination. Create a new range or increment the
1196344a3780SDimitry Andric       // currently existing range.
1197344a3780SDimitry Andric       else {
1198344a3780SDimitry Andric         if (!RangeEnd)
1199344a3780SDimitry Andric           RangeBegin = RangeEnd = &MI;
1200344a3780SDimitry Andric         else
1201344a3780SDimitry Andric           RangeBegin = &MI;
1202344a3780SDimitry Andric       }
1203344a3780SDimitry Andric 
1204344a3780SDimitry Andric       // Update EHPadStack.
1205344a3780SDimitry Andric       if (MI.getOpcode() == WebAssembly::TRY)
1206344a3780SDimitry Andric         EHPadStack.pop_back();
1207344a3780SDimitry Andric       else if (WebAssembly::isCatch(MI.getOpcode()))
1208344a3780SDimitry Andric         EHPadStack.push_back(MI.getParent());
1209344a3780SDimitry Andric     }
1210344a3780SDimitry Andric 
1211344a3780SDimitry Andric     if (RangeEnd)
1212344a3780SDimitry Andric       RecordCallerMismatchRange(EHPadStack.back());
1213344a3780SDimitry Andric   }
1214344a3780SDimitry Andric 
1215344a3780SDimitry Andric   assert(EHPadStack.empty());
1216344a3780SDimitry Andric 
1217344a3780SDimitry Andric   // We don't have any unwind destination mismatches to resolve.
1218344a3780SDimitry Andric   if (UnwindDestToTryRanges.empty())
1219344a3780SDimitry Andric     return false;
1220344a3780SDimitry Andric 
1221344a3780SDimitry Andric   // Now we fix the mismatches by wrapping calls with inner try-delegates.
1222344a3780SDimitry Andric   for (auto &P : UnwindDestToTryRanges) {
1223344a3780SDimitry Andric     NumCallUnwindMismatches += P.second.size();
1224344a3780SDimitry Andric     MachineBasicBlock *UnwindDest = P.first;
1225344a3780SDimitry Andric     auto &TryRanges = P.second;
1226344a3780SDimitry Andric 
1227344a3780SDimitry Andric     for (auto Range : TryRanges) {
1228344a3780SDimitry Andric       MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr;
1229344a3780SDimitry Andric       std::tie(RangeBegin, RangeEnd) = Range;
1230344a3780SDimitry Andric       auto *MBB = RangeBegin->getParent();
1231344a3780SDimitry Andric 
1232344a3780SDimitry Andric       // If this BB has an EH pad successor, i.e., ends with an 'invoke', now we
1233344a3780SDimitry Andric       // are going to wrap the invoke with try-delegate, making the 'delegate'
1234344a3780SDimitry Andric       // BB the new successor instead, so remove the EH pad succesor here. The
1235344a3780SDimitry Andric       // BB may not have an EH pad successor if calls in this BB throw to the
1236344a3780SDimitry Andric       // caller.
1237344a3780SDimitry Andric       MachineBasicBlock *EHPad = nullptr;
1238344a3780SDimitry Andric       for (auto *Succ : MBB->successors()) {
1239344a3780SDimitry Andric         if (Succ->isEHPad()) {
1240344a3780SDimitry Andric           EHPad = Succ;
1241344a3780SDimitry Andric           break;
1242344a3780SDimitry Andric         }
1243344a3780SDimitry Andric       }
1244344a3780SDimitry Andric       if (EHPad)
1245344a3780SDimitry Andric         MBB->removeSuccessor(EHPad);
1246344a3780SDimitry Andric 
1247344a3780SDimitry Andric       addTryDelegate(RangeBegin, RangeEnd, UnwindDest);
1248344a3780SDimitry Andric     }
1249344a3780SDimitry Andric   }
1250344a3780SDimitry Andric 
1251344a3780SDimitry Andric   return true;
1252344a3780SDimitry Andric }
1253344a3780SDimitry Andric 
fixCatchUnwindMismatches(MachineFunction & MF)1254344a3780SDimitry Andric bool WebAssemblyCFGStackify::fixCatchUnwindMismatches(MachineFunction &MF) {
1255344a3780SDimitry Andric   // There is another kind of unwind destination mismatches besides call unwind
1256344a3780SDimitry Andric   // mismatches, which we will call "catch unwind mismatches". See this example
1257344a3780SDimitry Andric   // after the marker placement:
1258344a3780SDimitry Andric   // try
1259344a3780SDimitry Andric   //   try
1260344a3780SDimitry Andric   //     call @foo
1261344a3780SDimitry Andric   //   catch __cpp_exception  ;; ehpad A (next unwind dest: caller)
1262344a3780SDimitry Andric   //     ...
1263344a3780SDimitry Andric   //   end_try
1264344a3780SDimitry Andric   // catch_all                ;; ehpad B
1265344a3780SDimitry Andric   //   ...
1266344a3780SDimitry Andric   // end_try
1267344a3780SDimitry Andric   //
1268344a3780SDimitry Andric   // 'call @foo's unwind destination is the ehpad A. But suppose 'call @foo'
1269344a3780SDimitry Andric   // throws a foreign exception that is not caught by ehpad A, and its next
1270344a3780SDimitry Andric   // destination should be the caller. But after control flow linearization,
1271344a3780SDimitry Andric   // another EH pad can be placed in between (e.g. ehpad B here), making the
1272344a3780SDimitry Andric   // next unwind destination incorrect. In this case, the  foreign exception
1273344a3780SDimitry Andric   // will instead go to ehpad B and will be caught there instead. In this
1274344a3780SDimitry Andric   // example the correct next unwind destination is the caller, but it can be
1275344a3780SDimitry Andric   // another outer catch in other cases.
1276344a3780SDimitry Andric   //
1277344a3780SDimitry Andric   // There is no specific 'call' or 'throw' instruction to wrap with a
1278344a3780SDimitry Andric   // try-delegate, so we wrap the whole try-catch-end with a try-delegate and
1279344a3780SDimitry Andric   // make it rethrow to the right destination, as in the example below:
1280344a3780SDimitry Andric   // try
1281344a3780SDimitry Andric   //   try                     ;; (new)
1282344a3780SDimitry Andric   //     try
1283344a3780SDimitry Andric   //       call @foo
1284344a3780SDimitry Andric   //     catch __cpp_exception ;; ehpad A (next unwind dest: caller)
1285344a3780SDimitry Andric   //       ...
1286344a3780SDimitry Andric   //     end_try
1287344a3780SDimitry Andric   //   delegate 1 (caller)     ;; (new)
1288344a3780SDimitry Andric   // catch_all                 ;; ehpad B
1289344a3780SDimitry Andric   //   ...
1290344a3780SDimitry Andric   // end_try
1291344a3780SDimitry Andric 
1292344a3780SDimitry Andric   const auto *EHInfo = MF.getWasmEHFuncInfo();
12937fa27ce4SDimitry Andric   assert(EHInfo);
1294344a3780SDimitry Andric   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
1295344a3780SDimitry Andric   // For EH pads that have catch unwind mismatches, a map of <EH pad, its
1296344a3780SDimitry Andric   // correct unwind destination>.
1297344a3780SDimitry Andric   DenseMap<MachineBasicBlock *, MachineBasicBlock *> EHPadToUnwindDest;
1298344a3780SDimitry Andric 
1299344a3780SDimitry Andric   for (auto &MBB : reverse(MF)) {
1300344a3780SDimitry Andric     for (auto &MI : reverse(MBB)) {
1301344a3780SDimitry Andric       if (MI.getOpcode() == WebAssembly::TRY)
1302344a3780SDimitry Andric         EHPadStack.pop_back();
1303344a3780SDimitry Andric       else if (MI.getOpcode() == WebAssembly::DELEGATE)
1304344a3780SDimitry Andric         EHPadStack.push_back(&MBB);
1305344a3780SDimitry Andric       else if (WebAssembly::isCatch(MI.getOpcode())) {
1306344a3780SDimitry Andric         auto *EHPad = &MBB;
1307344a3780SDimitry Andric 
1308344a3780SDimitry Andric         // catch_all always catches an exception, so we don't need to do
1309344a3780SDimitry Andric         // anything
1310344a3780SDimitry Andric         if (MI.getOpcode() == WebAssembly::CATCH_ALL) {
1311344a3780SDimitry Andric         }
1312344a3780SDimitry Andric 
1313344a3780SDimitry Andric         // This can happen when the unwind dest was removed during the
1314344a3780SDimitry Andric         // optimization, e.g. because it was unreachable.
1315344a3780SDimitry Andric         else if (EHPadStack.empty() && EHInfo->hasUnwindDest(EHPad)) {
1316344a3780SDimitry Andric           LLVM_DEBUG(dbgs() << "EHPad (" << EHPad->getName()
1317344a3780SDimitry Andric                             << "'s unwind destination does not exist anymore"
1318344a3780SDimitry Andric                             << "\n\n");
1319344a3780SDimitry Andric         }
1320344a3780SDimitry Andric 
1321344a3780SDimitry Andric         // The EHPad's next unwind destination is the caller, but we incorrectly
1322344a3780SDimitry Andric         // unwind to another EH pad.
1323344a3780SDimitry Andric         else if (!EHPadStack.empty() && !EHInfo->hasUnwindDest(EHPad)) {
1324344a3780SDimitry Andric           EHPadToUnwindDest[EHPad] = getFakeCallerBlock(MF);
1325344a3780SDimitry Andric           LLVM_DEBUG(dbgs()
1326344a3780SDimitry Andric                      << "- Catch unwind mismatch:\nEHPad = " << EHPad->getName()
1327344a3780SDimitry Andric                      << "  Original dest = caller  Current dest = "
1328344a3780SDimitry Andric                      << EHPadStack.back()->getName() << "\n\n");
1329344a3780SDimitry Andric         }
1330344a3780SDimitry Andric 
1331344a3780SDimitry Andric         // The EHPad's next unwind destination is an EH pad, whereas we
1332344a3780SDimitry Andric         // incorrectly unwind to another EH pad.
1333344a3780SDimitry Andric         else if (!EHPadStack.empty() && EHInfo->hasUnwindDest(EHPad)) {
1334344a3780SDimitry Andric           auto *UnwindDest = EHInfo->getUnwindDest(EHPad);
1335344a3780SDimitry Andric           if (EHPadStack.back() != UnwindDest) {
1336344a3780SDimitry Andric             EHPadToUnwindDest[EHPad] = UnwindDest;
1337344a3780SDimitry Andric             LLVM_DEBUG(dbgs() << "- Catch unwind mismatch:\nEHPad = "
1338344a3780SDimitry Andric                               << EHPad->getName() << "  Original dest = "
1339344a3780SDimitry Andric                               << UnwindDest->getName() << "  Current dest = "
1340344a3780SDimitry Andric                               << EHPadStack.back()->getName() << "\n\n");
1341344a3780SDimitry Andric           }
1342344a3780SDimitry Andric         }
1343344a3780SDimitry Andric 
1344344a3780SDimitry Andric         EHPadStack.push_back(EHPad);
1345344a3780SDimitry Andric       }
1346344a3780SDimitry Andric     }
1347344a3780SDimitry Andric   }
1348344a3780SDimitry Andric 
1349344a3780SDimitry Andric   assert(EHPadStack.empty());
1350344a3780SDimitry Andric   if (EHPadToUnwindDest.empty())
1351344a3780SDimitry Andric     return false;
1352344a3780SDimitry Andric   NumCatchUnwindMismatches += EHPadToUnwindDest.size();
1353344a3780SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 4> NewEndTryBBs;
1354344a3780SDimitry Andric 
1355344a3780SDimitry Andric   for (auto &P : EHPadToUnwindDest) {
1356344a3780SDimitry Andric     MachineBasicBlock *EHPad = P.first;
1357344a3780SDimitry Andric     MachineBasicBlock *UnwindDest = P.second;
1358344a3780SDimitry Andric     MachineInstr *Try = EHPadToTry[EHPad];
1359344a3780SDimitry Andric     MachineInstr *EndTry = BeginToEnd[Try];
1360344a3780SDimitry Andric     addTryDelegate(Try, EndTry, UnwindDest);
1361344a3780SDimitry Andric     NewEndTryBBs.insert(EndTry->getParent());
1362344a3780SDimitry Andric   }
1363344a3780SDimitry Andric 
1364344a3780SDimitry Andric   // Adding a try-delegate wrapping an existing try-catch-end can make existing
1365344a3780SDimitry Andric   // branch destination BBs invalid. For example,
1366344a3780SDimitry Andric   //
1367344a3780SDimitry Andric   // - Before:
1368344a3780SDimitry Andric   // bb0:
1369344a3780SDimitry Andric   //   block
1370344a3780SDimitry Andric   //     br bb3
1371344a3780SDimitry Andric   // bb1:
1372344a3780SDimitry Andric   //     try
1373344a3780SDimitry Andric   //       ...
1374344a3780SDimitry Andric   // bb2: (ehpad)
1375344a3780SDimitry Andric   //     catch
1376344a3780SDimitry Andric   // bb3:
1377344a3780SDimitry Andric   //     end_try
1378344a3780SDimitry Andric   //   end_block   ;; 'br bb3' targets here
1379344a3780SDimitry Andric   //
1380344a3780SDimitry Andric   // Suppose this try-catch-end has a catch unwind mismatch, so we need to wrap
1381344a3780SDimitry Andric   // this with a try-delegate. Then this becomes:
1382344a3780SDimitry Andric   //
1383344a3780SDimitry Andric   // - After:
1384344a3780SDimitry Andric   // bb0:
1385344a3780SDimitry Andric   //   block
1386344a3780SDimitry Andric   //     br bb3    ;; invalid destination!
1387344a3780SDimitry Andric   // bb1:
1388344a3780SDimitry Andric   //     try       ;; (new instruction)
1389344a3780SDimitry Andric   //       try
1390344a3780SDimitry Andric   //         ...
1391344a3780SDimitry Andric   // bb2: (ehpad)
1392344a3780SDimitry Andric   //       catch
1393344a3780SDimitry Andric   // bb3:
1394344a3780SDimitry Andric   //       end_try ;; 'br bb3' still incorrectly targets here!
1395344a3780SDimitry Andric   // delegate_bb:  ;; (new BB)
1396344a3780SDimitry Andric   //     delegate  ;; (new instruction)
1397344a3780SDimitry Andric   // split_bb:     ;; (new BB)
1398344a3780SDimitry Andric   //   end_block
1399344a3780SDimitry Andric   //
1400344a3780SDimitry Andric   // Now 'br bb3' incorrectly branches to an inner scope.
1401344a3780SDimitry Andric   //
1402344a3780SDimitry Andric   // As we can see in this case, when branches target a BB that has both
1403344a3780SDimitry Andric   // 'end_try' and 'end_block' and the BB is split to insert a 'delegate', we
1404344a3780SDimitry Andric   // have to remap existing branch destinations so that they target not the
1405344a3780SDimitry Andric   // 'end_try' BB but the new 'end_block' BB. There can be multiple 'delegate's
1406344a3780SDimitry Andric   // in between, so we try to find the next BB with 'end_block' instruction. In
1407344a3780SDimitry Andric   // this example, the 'br bb3' instruction should be remapped to 'br split_bb'.
1408344a3780SDimitry Andric   for (auto &MBB : MF) {
1409344a3780SDimitry Andric     for (auto &MI : MBB) {
1410344a3780SDimitry Andric       if (MI.isTerminator()) {
1411344a3780SDimitry Andric         for (auto &MO : MI.operands()) {
1412344a3780SDimitry Andric           if (MO.isMBB() && NewEndTryBBs.count(MO.getMBB())) {
1413344a3780SDimitry Andric             auto *BrDest = MO.getMBB();
1414344a3780SDimitry Andric             bool FoundEndBlock = false;
1415344a3780SDimitry Andric             for (; std::next(BrDest->getIterator()) != MF.end();
1416344a3780SDimitry Andric                  BrDest = BrDest->getNextNode()) {
1417344a3780SDimitry Andric               for (const auto &MI : *BrDest) {
1418344a3780SDimitry Andric                 if (MI.getOpcode() == WebAssembly::END_BLOCK) {
1419344a3780SDimitry Andric                   FoundEndBlock = true;
1420344a3780SDimitry Andric                   break;
1421344a3780SDimitry Andric                 }
1422344a3780SDimitry Andric               }
1423344a3780SDimitry Andric               if (FoundEndBlock)
1424344a3780SDimitry Andric                 break;
1425344a3780SDimitry Andric             }
1426344a3780SDimitry Andric             assert(FoundEndBlock);
1427344a3780SDimitry Andric             MO.setMBB(BrDest);
1428344a3780SDimitry Andric           }
1429344a3780SDimitry Andric         }
1430344a3780SDimitry Andric       }
1431344a3780SDimitry Andric     }
1432344a3780SDimitry Andric   }
1433344a3780SDimitry Andric 
1434344a3780SDimitry Andric   return true;
1435344a3780SDimitry Andric }
1436344a3780SDimitry Andric 
recalculateScopeTops(MachineFunction & MF)1437344a3780SDimitry Andric void WebAssemblyCFGStackify::recalculateScopeTops(MachineFunction &MF) {
1438344a3780SDimitry Andric   // Renumber BBs and recalculate ScopeTop info because new BBs might have been
1439344a3780SDimitry Andric   // created and inserted during fixing unwind mismatches.
1440344a3780SDimitry Andric   MF.RenumberBlocks();
1441344a3780SDimitry Andric   ScopeTops.clear();
1442344a3780SDimitry Andric   ScopeTops.resize(MF.getNumBlockIDs());
1443344a3780SDimitry Andric   for (auto &MBB : reverse(MF)) {
1444344a3780SDimitry Andric     for (auto &MI : reverse(MBB)) {
1445344a3780SDimitry Andric       if (ScopeTops[MBB.getNumber()])
1446344a3780SDimitry Andric         break;
1447344a3780SDimitry Andric       switch (MI.getOpcode()) {
1448344a3780SDimitry Andric       case WebAssembly::END_BLOCK:
1449344a3780SDimitry Andric       case WebAssembly::END_LOOP:
1450344a3780SDimitry Andric       case WebAssembly::END_TRY:
1451344a3780SDimitry Andric       case WebAssembly::DELEGATE:
1452344a3780SDimitry Andric         updateScopeTops(EndToBegin[&MI]->getParent(), &MBB);
1453344a3780SDimitry Andric         break;
1454344a3780SDimitry Andric       case WebAssembly::CATCH:
1455344a3780SDimitry Andric       case WebAssembly::CATCH_ALL:
1456344a3780SDimitry Andric         updateScopeTops(EHPadToTry[&MBB]->getParent(), &MBB);
1457344a3780SDimitry Andric         break;
1458344a3780SDimitry Andric       }
1459344a3780SDimitry Andric     }
1460344a3780SDimitry Andric   }
1461050e163aSDimitry Andric }
1462050e163aSDimitry Andric 
1463b915e9e0SDimitry Andric /// In normal assembly languages, when the end of a function is unreachable,
1464b915e9e0SDimitry Andric /// because the function ends in an infinite loop or a noreturn call or similar,
1465b915e9e0SDimitry Andric /// it isn't necessary to worry about the function return type at the end of
1466b915e9e0SDimitry Andric /// the function, because it's never reached. However, in WebAssembly, blocks
1467b915e9e0SDimitry Andric /// that end at the function end need to have a return type signature that
1468b915e9e0SDimitry Andric /// matches the function signature, even though it's unreachable. This function
1469b915e9e0SDimitry Andric /// checks for such cases and fixes up the signatures.
fixEndsAtEndOfFunction(MachineFunction & MF)1470d8e91e46SDimitry Andric void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
1471d8e91e46SDimitry Andric   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
1472b915e9e0SDimitry Andric 
1473b915e9e0SDimitry Andric   if (MFI.getResults().empty())
1474b915e9e0SDimitry Andric     return;
1475b915e9e0SDimitry Andric 
14761d5ae102SDimitry Andric   // MCInstLower will add the proper types to multivalue signatures based on the
14771d5ae102SDimitry Andric   // function return type
14781d5ae102SDimitry Andric   WebAssembly::BlockType RetType =
14791d5ae102SDimitry Andric       MFI.getResults().size() > 1
14801d5ae102SDimitry Andric           ? WebAssembly::BlockType::Multivalue
14811d5ae102SDimitry Andric           : WebAssembly::BlockType(
14821d5ae102SDimitry Andric                 WebAssembly::toValType(MFI.getResults().front()));
1483b915e9e0SDimitry Andric 
1484b60736ecSDimitry Andric   SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist;
1485b60736ecSDimitry Andric   Worklist.push_back(MF.rbegin()->rbegin());
1486b60736ecSDimitry Andric 
1487b60736ecSDimitry Andric   auto Process = [&](MachineBasicBlock::reverse_iterator It) {
1488b60736ecSDimitry Andric     auto *MBB = It->getParent();
1489b60736ecSDimitry Andric     while (It != MBB->rend()) {
1490b60736ecSDimitry Andric       MachineInstr &MI = *It++;
1491eb11fae6SDimitry Andric       if (MI.isPosition() || MI.isDebugInstr())
1492b915e9e0SDimitry Andric         continue;
14931d5ae102SDimitry Andric       switch (MI.getOpcode()) {
1494b60736ecSDimitry Andric       case WebAssembly::END_TRY: {
1495b60736ecSDimitry Andric         // If a 'try''s return type is fixed, both its try body and catch body
1496b60736ecSDimitry Andric         // should satisfy the return type, so we need to search 'end'
1497b60736ecSDimitry Andric         // instructions before its corresponding 'catch' too.
1498b60736ecSDimitry Andric         auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
1499b60736ecSDimitry Andric         assert(EHPad);
1500b60736ecSDimitry Andric         auto NextIt =
1501b60736ecSDimitry Andric             std::next(WebAssembly::findCatch(EHPad)->getReverseIterator());
1502b60736ecSDimitry Andric         if (NextIt != EHPad->rend())
1503b60736ecSDimitry Andric           Worklist.push_back(NextIt);
1504e3b55780SDimitry Andric         [[fallthrough]];
1505b60736ecSDimitry Andric       }
15061d5ae102SDimitry Andric       case WebAssembly::END_BLOCK:
15071d5ae102SDimitry Andric       case WebAssembly::END_LOOP:
1508344a3780SDimitry Andric       case WebAssembly::DELEGATE:
1509e6d15924SDimitry Andric         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
1510b915e9e0SDimitry Andric         continue;
15111d5ae102SDimitry Andric       default:
1512b60736ecSDimitry Andric         // Something other than an `end`. We're done for this BB.
1513b915e9e0SDimitry Andric         return;
1514b915e9e0SDimitry Andric       }
1515b915e9e0SDimitry Andric     }
1516b60736ecSDimitry Andric     // We've reached the beginning of a BB. Continue the search in the previous
1517b60736ecSDimitry Andric     // BB.
1518b60736ecSDimitry Andric     Worklist.push_back(MBB->getPrevNode()->rbegin());
1519b60736ecSDimitry Andric   };
1520b60736ecSDimitry Andric 
1521b60736ecSDimitry Andric   while (!Worklist.empty())
1522b60736ecSDimitry Andric     Process(Worklist.pop_back_val());
15231d5ae102SDimitry Andric }
1524b915e9e0SDimitry Andric 
152571d5a254SDimitry Andric // WebAssembly functions end with an end instruction, as if the function body
152671d5a254SDimitry Andric // were a block.
appendEndToFunction(MachineFunction & MF,const WebAssemblyInstrInfo & TII)1527e6d15924SDimitry Andric static void appendEndToFunction(MachineFunction &MF,
152871d5a254SDimitry Andric                                 const WebAssemblyInstrInfo &TII) {
1529eb11fae6SDimitry Andric   BuildMI(MF.back(), MF.back().end(),
1530eb11fae6SDimitry Andric           MF.back().findPrevDebugLoc(MF.back().end()),
153171d5a254SDimitry Andric           TII.get(WebAssembly::END_FUNCTION));
153271d5a254SDimitry Andric }
153371d5a254SDimitry Andric 
1534d8e91e46SDimitry Andric /// Insert LOOP/TRY/BLOCK markers at appropriate places.
placeMarkers(MachineFunction & MF)1535d8e91e46SDimitry Andric void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
1536d8e91e46SDimitry Andric   // We allocate one more than the number of blocks in the function to
1537d8e91e46SDimitry Andric   // accommodate for the possible fake block we may insert at the end.
1538d8e91e46SDimitry Andric   ScopeTops.resize(MF.getNumBlockIDs() + 1);
1539dd58ef01SDimitry Andric   // Place the LOOP for MBB if MBB is the header of a loop.
1540d8e91e46SDimitry Andric   for (auto &MBB : MF)
1541d8e91e46SDimitry Andric     placeLoopMarker(MBB);
1542e6d15924SDimitry Andric 
1543e6d15924SDimitry Andric   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1544e6d15924SDimitry Andric   for (auto &MBB : MF) {
1545e6d15924SDimitry Andric     if (MBB.isEHPad()) {
1546d8e91e46SDimitry Andric       // Place the TRY for MBB if MBB is the EH pad of an exception.
1547d8e91e46SDimitry Andric       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1548d8e91e46SDimitry Andric           MF.getFunction().hasPersonalityFn())
1549d8e91e46SDimitry Andric         placeTryMarker(MBB);
1550e6d15924SDimitry Andric     } else {
1551dd58ef01SDimitry Andric       // Place the BLOCK for MBB if MBB is branched to from above.
1552d8e91e46SDimitry Andric       placeBlockMarker(MBB);
1553dd58ef01SDimitry Andric     }
1554e6d15924SDimitry Andric   }
1555e6d15924SDimitry Andric   // Fix mismatches in unwind destinations induced by linearizing the code.
15561d5ae102SDimitry Andric   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1557344a3780SDimitry Andric       MF.getFunction().hasPersonalityFn()) {
1558344a3780SDimitry Andric     bool Changed = fixCallUnwindMismatches(MF);
1559344a3780SDimitry Andric     Changed |= fixCatchUnwindMismatches(MF);
1560344a3780SDimitry Andric     if (Changed)
1561344a3780SDimitry Andric       recalculateScopeTops(MF);
1562344a3780SDimitry Andric   }
1563344a3780SDimitry Andric }
1564344a3780SDimitry Andric 
getBranchDepth(const SmallVectorImpl<EndMarkerInfo> & Stack,const MachineBasicBlock * MBB)1565344a3780SDimitry Andric unsigned WebAssemblyCFGStackify::getBranchDepth(
1566344a3780SDimitry Andric     const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
1567344a3780SDimitry Andric   unsigned Depth = 0;
1568344a3780SDimitry Andric   for (auto X : reverse(Stack)) {
1569344a3780SDimitry Andric     if (X.first == MBB)
1570344a3780SDimitry Andric       break;
1571344a3780SDimitry Andric     ++Depth;
1572344a3780SDimitry Andric   }
1573344a3780SDimitry Andric   assert(Depth < Stack.size() && "Branch destination should be in scope");
1574344a3780SDimitry Andric   return Depth;
1575344a3780SDimitry Andric }
1576344a3780SDimitry Andric 
getDelegateDepth(const SmallVectorImpl<EndMarkerInfo> & Stack,const MachineBasicBlock * MBB)1577344a3780SDimitry Andric unsigned WebAssemblyCFGStackify::getDelegateDepth(
1578344a3780SDimitry Andric     const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
1579344a3780SDimitry Andric   if (MBB == FakeCallerBB)
1580344a3780SDimitry Andric     return Stack.size();
1581344a3780SDimitry Andric   // Delegate's destination is either a catch or a another delegate BB. When the
1582344a3780SDimitry Andric   // destination is another delegate, we can compute the argument in the same
1583344a3780SDimitry Andric   // way as branches, because the target delegate BB only contains the single
1584344a3780SDimitry Andric   // delegate instruction.
1585344a3780SDimitry Andric   if (!MBB->isEHPad()) // Target is a delegate BB
1586344a3780SDimitry Andric     return getBranchDepth(Stack, MBB);
1587344a3780SDimitry Andric 
1588344a3780SDimitry Andric   // When the delegate's destination is a catch BB, we need to use its
1589344a3780SDimitry Andric   // corresponding try's end_try BB because Stack contains each marker's end BB.
1590344a3780SDimitry Andric   // Also we need to check if the end marker instruction matches, because a
1591344a3780SDimitry Andric   // single BB can contain multiple end markers, like this:
1592344a3780SDimitry Andric   // bb:
1593344a3780SDimitry Andric   //   END_BLOCK
1594344a3780SDimitry Andric   //   END_TRY
1595344a3780SDimitry Andric   //   END_BLOCK
1596344a3780SDimitry Andric   //   END_TRY
1597344a3780SDimitry Andric   //   ...
1598344a3780SDimitry Andric   //
1599344a3780SDimitry Andric   // In case of branches getting the immediate that targets any of these is
1600344a3780SDimitry Andric   // fine, but delegate has to exactly target the correct try.
1601344a3780SDimitry Andric   unsigned Depth = 0;
1602344a3780SDimitry Andric   const MachineInstr *EndTry = BeginToEnd[EHPadToTry[MBB]];
1603344a3780SDimitry Andric   for (auto X : reverse(Stack)) {
1604344a3780SDimitry Andric     if (X.first == EndTry->getParent() && X.second == EndTry)
1605344a3780SDimitry Andric       break;
1606344a3780SDimitry Andric     ++Depth;
1607344a3780SDimitry Andric   }
1608344a3780SDimitry Andric   assert(Depth < Stack.size() && "Delegate destination should be in scope");
1609344a3780SDimitry Andric   return Depth;
1610344a3780SDimitry Andric }
1611344a3780SDimitry Andric 
getRethrowDepth(const SmallVectorImpl<EndMarkerInfo> & Stack,const MachineBasicBlock * EHPadToRethrow)1612344a3780SDimitry Andric unsigned WebAssemblyCFGStackify::getRethrowDepth(
1613344a3780SDimitry Andric     const SmallVectorImpl<EndMarkerInfo> &Stack,
1614f65bf063SDimitry Andric     const MachineBasicBlock *EHPadToRethrow) {
1615344a3780SDimitry Andric   unsigned Depth = 0;
1616344a3780SDimitry Andric   for (auto X : reverse(Stack)) {
1617344a3780SDimitry Andric     const MachineInstr *End = X.second;
1618344a3780SDimitry Andric     if (End->getOpcode() == WebAssembly::END_TRY) {
1619344a3780SDimitry Andric       auto *EHPad = TryToEHPad[EndToBegin[End]];
1620f65bf063SDimitry Andric       if (EHPadToRethrow == EHPad)
1621344a3780SDimitry Andric         break;
1622344a3780SDimitry Andric     }
1623344a3780SDimitry Andric     ++Depth;
1624344a3780SDimitry Andric   }
1625344a3780SDimitry Andric   assert(Depth < Stack.size() && "Rethrow destination should be in scope");
1626344a3780SDimitry Andric   return Depth;
1627e6d15924SDimitry Andric }
1628dd58ef01SDimitry Andric 
rewriteDepthImmediates(MachineFunction & MF)1629d8e91e46SDimitry Andric void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
1630050e163aSDimitry Andric   // Now rewrite references to basic blocks to be depth immediates.
1631344a3780SDimitry Andric   SmallVector<EndMarkerInfo, 8> Stack;
1632050e163aSDimitry Andric   for (auto &MBB : reverse(MF)) {
1633c0981da4SDimitry Andric     for (MachineInstr &MI : llvm::reverse(MBB)) {
1634050e163aSDimitry Andric       switch (MI.getOpcode()) {
1635050e163aSDimitry Andric       case WebAssembly::BLOCK:
1636d8e91e46SDimitry Andric       case WebAssembly::TRY:
1637344a3780SDimitry Andric         assert(ScopeTops[Stack.back().first->getNumber()]->getNumber() <=
1638d8e91e46SDimitry Andric                    MBB.getNumber() &&
1639d8e91e46SDimitry Andric                "Block/try marker should be balanced");
1640d8e91e46SDimitry Andric         Stack.pop_back();
1641d8e91e46SDimitry Andric         break;
1642d8e91e46SDimitry Andric 
1643050e163aSDimitry Andric       case WebAssembly::LOOP:
1644344a3780SDimitry Andric         assert(Stack.back().first == &MBB && "Loop top should be balanced");
1645050e163aSDimitry Andric         Stack.pop_back();
1646050e163aSDimitry Andric         break;
1647d8e91e46SDimitry Andric 
1648050e163aSDimitry Andric       case WebAssembly::END_BLOCK:
1649f65bf063SDimitry Andric       case WebAssembly::END_TRY:
1650344a3780SDimitry Andric         Stack.push_back(std::make_pair(&MBB, &MI));
1651050e163aSDimitry Andric         break;
1652d8e91e46SDimitry Andric 
1653050e163aSDimitry Andric       case WebAssembly::END_LOOP:
1654344a3780SDimitry Andric         Stack.push_back(std::make_pair(EndToBegin[&MI]->getParent(), &MI));
1655344a3780SDimitry Andric         break;
1656344a3780SDimitry Andric 
1657050e163aSDimitry Andric       default:
1658050e163aSDimitry Andric         if (MI.isTerminator()) {
1659050e163aSDimitry Andric           // Rewrite MBB operands to be depth immediates.
1660050e163aSDimitry Andric           SmallVector<MachineOperand, 4> Ops(MI.operands());
1661050e163aSDimitry Andric           while (MI.getNumOperands() > 0)
1662145449b1SDimitry Andric             MI.removeOperand(MI.getNumOperands() - 1);
1663050e163aSDimitry Andric           for (auto MO : Ops) {
1664344a3780SDimitry Andric             if (MO.isMBB()) {
1665344a3780SDimitry Andric               if (MI.getOpcode() == WebAssembly::DELEGATE)
1666344a3780SDimitry Andric                 MO = MachineOperand::CreateImm(
1667344a3780SDimitry Andric                     getDelegateDepth(Stack, MO.getMBB()));
1668f65bf063SDimitry Andric               else if (MI.getOpcode() == WebAssembly::RETHROW)
1669f65bf063SDimitry Andric                 MO = MachineOperand::CreateImm(
1670f65bf063SDimitry Andric                     getRethrowDepth(Stack, MO.getMBB()));
1671344a3780SDimitry Andric               else
1672344a3780SDimitry Andric                 MO = MachineOperand::CreateImm(
1673344a3780SDimitry Andric                     getBranchDepth(Stack, MO.getMBB()));
1674344a3780SDimitry Andric             }
1675050e163aSDimitry Andric             MI.addOperand(MF, MO);
1676dd58ef01SDimitry Andric           }
1677050e163aSDimitry Andric         }
1678344a3780SDimitry Andric 
1679344a3780SDimitry Andric         if (MI.getOpcode() == WebAssembly::DELEGATE)
1680344a3780SDimitry Andric           Stack.push_back(std::make_pair(&MBB, &MI));
1681050e163aSDimitry Andric         break;
1682050e163aSDimitry Andric       }
1683050e163aSDimitry Andric     }
1684050e163aSDimitry Andric   }
1685050e163aSDimitry Andric   assert(Stack.empty() && "Control flow should be balanced");
1686d8e91e46SDimitry Andric }
1687b915e9e0SDimitry Andric 
cleanupFunctionData(MachineFunction & MF)1688344a3780SDimitry Andric void WebAssemblyCFGStackify::cleanupFunctionData(MachineFunction &MF) {
1689344a3780SDimitry Andric   if (FakeCallerBB)
169077fc4c14SDimitry Andric     MF.deleteMachineBasicBlock(FakeCallerBB);
1691344a3780SDimitry Andric   AppendixBB = FakeCallerBB = nullptr;
1692344a3780SDimitry Andric }
1693344a3780SDimitry Andric 
releaseMemory()1694d8e91e46SDimitry Andric void WebAssemblyCFGStackify::releaseMemory() {
1695d8e91e46SDimitry Andric   ScopeTops.clear();
1696d8e91e46SDimitry Andric   BeginToEnd.clear();
1697d8e91e46SDimitry Andric   EndToBegin.clear();
1698d8e91e46SDimitry Andric   TryToEHPad.clear();
1699d8e91e46SDimitry Andric   EHPadToTry.clear();
1700050e163aSDimitry Andric }
1701dd58ef01SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)1702dd58ef01SDimitry Andric bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
1703eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
1704dd58ef01SDimitry Andric                        "********** Function: "
1705dd58ef01SDimitry Andric                     << MF.getName() << '\n');
1706e6d15924SDimitry Andric   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1707dd58ef01SDimitry Andric 
1708d8e91e46SDimitry Andric   releaseMemory();
1709d8e91e46SDimitry Andric 
1710b915e9e0SDimitry Andric   // Liveness is not tracked for VALUE_STACK physreg.
1711050e163aSDimitry Andric   MF.getRegInfo().invalidateLiveness();
1712dd58ef01SDimitry Andric 
1713d8e91e46SDimitry Andric   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
1714d8e91e46SDimitry Andric   placeMarkers(MF);
1715d8e91e46SDimitry Andric 
1716e6d15924SDimitry Andric   // Remove unnecessary instructions possibly introduced by try/end_trys.
1717e6d15924SDimitry Andric   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1718e6d15924SDimitry Andric       MF.getFunction().hasPersonalityFn())
1719e6d15924SDimitry Andric     removeUnnecessaryInstrs(MF);
1720e6d15924SDimitry Andric 
1721d8e91e46SDimitry Andric   // Convert MBB operands in terminators to relative depth immediates.
1722d8e91e46SDimitry Andric   rewriteDepthImmediates(MF);
1723d8e91e46SDimitry Andric 
1724d8e91e46SDimitry Andric   // Fix up block/loop/try signatures at the end of the function to conform to
1725d8e91e46SDimitry Andric   // WebAssembly's rules.
1726d8e91e46SDimitry Andric   fixEndsAtEndOfFunction(MF);
1727d8e91e46SDimitry Andric 
1728d8e91e46SDimitry Andric   // Add an end instruction at the end of the function body.
1729d8e91e46SDimitry Andric   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1730d8e91e46SDimitry Andric   if (!MF.getSubtarget<WebAssemblySubtarget>()
1731d8e91e46SDimitry Andric            .getTargetTriple()
1732d8e91e46SDimitry Andric            .isOSBinFormatELF())
1733e6d15924SDimitry Andric     appendEndToFunction(MF, TII);
1734dd58ef01SDimitry Andric 
1735344a3780SDimitry Andric   cleanupFunctionData(MF);
1736344a3780SDimitry Andric 
1737e6d15924SDimitry Andric   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1738dd58ef01SDimitry Andric   return true;
1739dd58ef01SDimitry Andric }
1740