xref: /freebsd/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyCFGStackify.cpp (revision 415efcecd8b80f68e76376ef2b854cb6f5c84b5a)
1 //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements a CFG stacking pass.
11 ///
12 /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes,
13 /// since scope boundaries serve as the labels for WebAssembly's control
14 /// transfers.
15 ///
16 /// This is sufficient to convert arbitrary CFGs into a form that works on
17 /// WebAssembly, provided that all loops are single-entry.
18 ///
19 /// In case we use exceptions, this pass also fixes mismatches in unwind
20 /// destinations created during transforming CFG into wasm structured format.
21 ///
22 //===----------------------------------------------------------------------===//
23 
24 #include "Utils/WebAssemblyTypeUtilities.h"
25 #include "WebAssembly.h"
26 #include "WebAssemblyExceptionInfo.h"
27 #include "WebAssemblyMachineFunctionInfo.h"
28 #include "WebAssemblySortRegion.h"
29 #include "WebAssemblySubtarget.h"
30 #include "WebAssemblyUtilities.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/CodeGen/MachineDominators.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/WasmEHFuncInfo.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 using namespace llvm;
39 using WebAssembly::SortRegionInfo;
40 
41 #define DEBUG_TYPE "wasm-cfg-stackify"
42 
43 STATISTIC(NumCallUnwindMismatches, "Number of call unwind mismatches found");
44 STATISTIC(NumCatchUnwindMismatches, "Number of catch unwind mismatches found");
45 
46 namespace {
47 class WebAssemblyCFGStackify final : public MachineFunctionPass {
getPassName() const48   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
49 
getAnalysisUsage(AnalysisUsage & AU) const50   void getAnalysisUsage(AnalysisUsage &AU) const override {
51     AU.addRequired<MachineDominatorTreeWrapperPass>();
52     AU.addRequired<MachineLoopInfoWrapperPass>();
53     AU.addRequired<WebAssemblyExceptionInfo>();
54     MachineFunctionPass::getAnalysisUsage(AU);
55   }
56 
57   bool runOnMachineFunction(MachineFunction &MF) override;
58 
59   // For each block whose label represents the end of a scope, record the block
60   // which holds the beginning of the scope. This will allow us to quickly skip
61   // over scoped regions when walking blocks.
62   SmallVector<MachineBasicBlock *, 8> ScopeTops;
updateScopeTops(MachineBasicBlock * Begin,MachineBasicBlock * End)63   void updateScopeTops(MachineBasicBlock *Begin, MachineBasicBlock *End) {
64     int EndNo = End->getNumber();
65     if (!ScopeTops[EndNo] || ScopeTops[EndNo]->getNumber() > Begin->getNumber())
66       ScopeTops[EndNo] = Begin;
67   }
68 
69   // Placing markers.
70   void placeMarkers(MachineFunction &MF);
71   void placeBlockMarker(MachineBasicBlock &MBB);
72   void placeLoopMarker(MachineBasicBlock &MBB);
73   void placeTryMarker(MachineBasicBlock &MBB);
74 
75   // Exception handling related functions
76   bool fixCallUnwindMismatches(MachineFunction &MF);
77   bool fixCatchUnwindMismatches(MachineFunction &MF);
78   void addTryDelegate(MachineInstr *RangeBegin, MachineInstr *RangeEnd,
79                       MachineBasicBlock *DelegateDest);
80   void recalculateScopeTops(MachineFunction &MF);
81   void removeUnnecessaryInstrs(MachineFunction &MF);
82 
83   // Wrap-up
84   using EndMarkerInfo =
85       std::pair<const MachineBasicBlock *, const MachineInstr *>;
86   unsigned getBranchDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
87                           const MachineBasicBlock *MBB);
88   unsigned getDelegateDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
89                             const MachineBasicBlock *MBB);
90   unsigned getRethrowDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
91                            const MachineBasicBlock *EHPadToRethrow);
92   void rewriteDepthImmediates(MachineFunction &MF);
93   void fixEndsAtEndOfFunction(MachineFunction &MF);
94   void cleanupFunctionData(MachineFunction &MF);
95 
96   // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY) or DELEGATE
97   // (in case of TRY).
98   DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
99   // For each END_(BLOCK|LOOP|TRY) or DELEGATE, the corresponding
100   // BLOCK|LOOP|TRY.
101   DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
102   // <TRY marker, EH pad> map
103   DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
104   // <EH pad, TRY marker> map
105   DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
106 
107   // We need an appendix block to place 'end_loop' or 'end_try' marker when the
108   // loop / exception bottom block is the last block in a function
109   MachineBasicBlock *AppendixBB = nullptr;
getAppendixBlock(MachineFunction & MF)110   MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
111     if (!AppendixBB) {
112       AppendixBB = MF.CreateMachineBasicBlock();
113       // Give it a fake predecessor so that AsmPrinter prints its label.
114       AppendixBB->addSuccessor(AppendixBB);
115       MF.push_back(AppendixBB);
116     }
117     return AppendixBB;
118   }
119 
120   // Before running rewriteDepthImmediates function, 'delegate' has a BB as its
121   // destination operand. getFakeCallerBlock() returns a fake BB that will be
122   // used for the operand when 'delegate' needs to rethrow to the caller. This
123   // will be rewritten as an immediate value that is the number of block depths
124   // + 1 in rewriteDepthImmediates, and this fake BB will be removed at the end
125   // of the pass.
126   MachineBasicBlock *FakeCallerBB = nullptr;
getFakeCallerBlock(MachineFunction & MF)127   MachineBasicBlock *getFakeCallerBlock(MachineFunction &MF) {
128     if (!FakeCallerBB)
129       FakeCallerBB = MF.CreateMachineBasicBlock();
130     return FakeCallerBB;
131   }
132 
133   // Helper functions to register / unregister scope information created by
134   // marker instructions.
135   void registerScope(MachineInstr *Begin, MachineInstr *End);
136   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
137                         MachineBasicBlock *EHPad);
138   void unregisterScope(MachineInstr *Begin);
139 
140 public:
141   static char ID; // Pass identification, replacement for typeid
WebAssemblyCFGStackify()142   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
~WebAssemblyCFGStackify()143   ~WebAssemblyCFGStackify() override { releaseMemory(); }
144   void releaseMemory() override;
145 };
146 } // end anonymous namespace
147 
148 char WebAssemblyCFGStackify::ID = 0;
149 INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
150                 "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false,
151                 false)
152 
createWebAssemblyCFGStackify()153 FunctionPass *llvm::createWebAssemblyCFGStackify() {
154   return new WebAssemblyCFGStackify();
155 }
156 
157 /// Test whether Pred has any terminators explicitly branching to MBB, as
158 /// opposed to falling through. Note that it's possible (eg. in unoptimized
159 /// code) for a branch instruction to both branch to a block and fallthrough
160 /// to it, so we check the actual branch operands to see if there are any
161 /// explicit mentions.
explicitlyBranchesTo(MachineBasicBlock * Pred,MachineBasicBlock * MBB)162 static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
163                                  MachineBasicBlock *MBB) {
164   for (MachineInstr &MI : Pred->terminators())
165     for (MachineOperand &MO : MI.explicit_operands())
166       if (MO.isMBB() && MO.getMBB() == MBB)
167         return true;
168   return false;
169 }
170 
171 // Returns an iterator to the earliest position possible within the MBB,
172 // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
173 // contains instructions that should go before the marker, and AfterSet contains
174 // ones that should go after the marker. In this function, AfterSet is only
175 // used for validation checking.
176 template <typename Container>
177 static MachineBasicBlock::iterator
getEarliestInsertPos(MachineBasicBlock * MBB,const Container & BeforeSet,const Container & AfterSet)178 getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
179                      const Container &AfterSet) {
180   auto InsertPos = MBB->end();
181   while (InsertPos != MBB->begin()) {
182     if (BeforeSet.count(&*std::prev(InsertPos))) {
183 #ifndef NDEBUG
184       // Validation check
185       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
186         assert(!AfterSet.count(&*std::prev(Pos)));
187 #endif
188       break;
189     }
190     --InsertPos;
191   }
192   return InsertPos;
193 }
194 
195 // Returns an iterator to the latest position possible within the MBB,
196 // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
197 // contains instructions that should go before the marker, and AfterSet contains
198 // ones that should go after the marker. In this function, BeforeSet is only
199 // used for validation checking.
200 template <typename Container>
201 static MachineBasicBlock::iterator
getLatestInsertPos(MachineBasicBlock * MBB,const Container & BeforeSet,const Container & AfterSet)202 getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
203                    const Container &AfterSet) {
204   auto InsertPos = MBB->begin();
205   while (InsertPos != MBB->end()) {
206     if (AfterSet.count(&*InsertPos)) {
207 #ifndef NDEBUG
208       // Validation check
209       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
210         assert(!BeforeSet.count(&*Pos));
211 #endif
212       break;
213     }
214     ++InsertPos;
215   }
216   return InsertPos;
217 }
218 
registerScope(MachineInstr * Begin,MachineInstr * End)219 void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
220                                            MachineInstr *End) {
221   BeginToEnd[Begin] = End;
222   EndToBegin[End] = Begin;
223 }
224 
225 // When 'End' is not an 'end_try' but 'delegate, EHPad is nullptr.
registerTryScope(MachineInstr * Begin,MachineInstr * End,MachineBasicBlock * EHPad)226 void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
227                                               MachineInstr *End,
228                                               MachineBasicBlock *EHPad) {
229   registerScope(Begin, End);
230   TryToEHPad[Begin] = EHPad;
231   EHPadToTry[EHPad] = Begin;
232 }
233 
unregisterScope(MachineInstr * Begin)234 void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
235   assert(BeginToEnd.count(Begin));
236   MachineInstr *End = BeginToEnd[Begin];
237   assert(EndToBegin.count(End));
238   BeginToEnd.erase(Begin);
239   EndToBegin.erase(End);
240   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
241   if (EHPad) {
242     assert(EHPadToTry.count(EHPad));
243     TryToEHPad.erase(Begin);
244     EHPadToTry.erase(EHPad);
245   }
246 }
247 
248 /// Insert a BLOCK marker for branches to MBB (if needed).
249 // TODO Consider a more generalized way of handling block (and also loop and
250 // try) signatures when we implement the multi-value proposal later.
placeBlockMarker(MachineBasicBlock & MBB)251 void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
252   assert(!MBB.isEHPad());
253   MachineFunction &MF = *MBB.getParent();
254   auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
255   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
256   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
257 
258   // First compute the nearest common dominator of all forward non-fallthrough
259   // predecessors so that we minimize the time that the BLOCK is on the stack,
260   // which reduces overall stack height.
261   MachineBasicBlock *Header = nullptr;
262   bool IsBranchedTo = false;
263   int MBBNumber = MBB.getNumber();
264   for (MachineBasicBlock *Pred : MBB.predecessors()) {
265     if (Pred->getNumber() < MBBNumber) {
266       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
267       if (explicitlyBranchesTo(Pred, &MBB))
268         IsBranchedTo = true;
269     }
270   }
271   if (!Header)
272     return;
273   if (!IsBranchedTo)
274     return;
275 
276   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
277   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
278 
279   // If the nearest common dominator is inside a more deeply nested context,
280   // walk out to the nearest scope which isn't more deeply nested.
281   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
282     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
283       if (ScopeTop->getNumber() > Header->getNumber()) {
284         // Skip over an intervening scope.
285         I = std::next(ScopeTop->getIterator());
286       } else {
287         // We found a scope level at an appropriate depth.
288         Header = ScopeTop;
289         break;
290       }
291     }
292   }
293 
294   // Decide where in Header to put the BLOCK.
295 
296   // Instructions that should go before the BLOCK.
297   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
298   // Instructions that should go after the BLOCK.
299   SmallPtrSet<const MachineInstr *, 4> AfterSet;
300   for (const auto &MI : *Header) {
301     // If there is a previously placed LOOP marker and the bottom block of the
302     // loop is above MBB, it should be after the BLOCK, because the loop is
303     // nested in this BLOCK. Otherwise it should be before the BLOCK.
304     if (MI.getOpcode() == WebAssembly::LOOP) {
305       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
306       if (MBB.getNumber() > LoopBottom->getNumber())
307         AfterSet.insert(&MI);
308 #ifndef NDEBUG
309       else
310         BeforeSet.insert(&MI);
311 #endif
312     }
313 
314     // If there is a previously placed BLOCK/TRY marker and its corresponding
315     // END marker is before the current BLOCK's END marker, that should be
316     // placed after this BLOCK. Otherwise it should be placed before this BLOCK
317     // marker.
318     if (MI.getOpcode() == WebAssembly::BLOCK ||
319         MI.getOpcode() == WebAssembly::TRY) {
320       if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
321         AfterSet.insert(&MI);
322 #ifndef NDEBUG
323       else
324         BeforeSet.insert(&MI);
325 #endif
326     }
327 
328 #ifndef NDEBUG
329     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
330     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
331         MI.getOpcode() == WebAssembly::END_LOOP ||
332         MI.getOpcode() == WebAssembly::END_TRY)
333       BeforeSet.insert(&MI);
334 #endif
335 
336     // Terminators should go after the BLOCK.
337     if (MI.isTerminator())
338       AfterSet.insert(&MI);
339   }
340 
341   // Local expression tree should go after the BLOCK.
342   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
343        --I) {
344     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
345       continue;
346     if (WebAssembly::isChild(*std::prev(I), MFI))
347       AfterSet.insert(&*std::prev(I));
348     else
349       break;
350   }
351 
352   // Add the BLOCK.
353   WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
354   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
355   MachineInstr *Begin =
356       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
357               TII.get(WebAssembly::BLOCK))
358           .addImm(int64_t(ReturnType));
359 
360   // Decide where in Header to put the END_BLOCK.
361   BeforeSet.clear();
362   AfterSet.clear();
363   for (auto &MI : MBB) {
364 #ifndef NDEBUG
365     // END_BLOCK should precede existing LOOP and TRY markers.
366     if (MI.getOpcode() == WebAssembly::LOOP ||
367         MI.getOpcode() == WebAssembly::TRY)
368       AfterSet.insert(&MI);
369 #endif
370 
371     // If there is a previously placed END_LOOP marker and the header of the
372     // loop is above this block's header, the END_LOOP should be placed after
373     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
374     // should be placed before the BLOCK. The same for END_TRY.
375     if (MI.getOpcode() == WebAssembly::END_LOOP ||
376         MI.getOpcode() == WebAssembly::END_TRY) {
377       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
378         BeforeSet.insert(&MI);
379 #ifndef NDEBUG
380       else
381         AfterSet.insert(&MI);
382 #endif
383     }
384   }
385 
386   // Mark the end of the block.
387   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
388   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
389                               TII.get(WebAssembly::END_BLOCK));
390   registerScope(Begin, End);
391 
392   // Track the farthest-spanning scope that ends at this point.
393   updateScopeTops(Header, &MBB);
394 }
395 
396 /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
placeLoopMarker(MachineBasicBlock & MBB)397 void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
398   MachineFunction &MF = *MBB.getParent();
399   const auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
400   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
401   SortRegionInfo SRI(MLI, WEI);
402   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
403 
404   MachineLoop *Loop = MLI.getLoopFor(&MBB);
405   if (!Loop || Loop->getHeader() != &MBB)
406     return;
407 
408   // The operand of a LOOP is the first block after the loop. If the loop is the
409   // bottom of the function, insert a dummy block at the end.
410   MachineBasicBlock *Bottom = SRI.getBottom(Loop);
411   auto Iter = std::next(Bottom->getIterator());
412   if (Iter == MF.end()) {
413     getAppendixBlock(MF);
414     Iter = std::next(Bottom->getIterator());
415   }
416   MachineBasicBlock *AfterLoop = &*Iter;
417 
418   // Decide where in Header to put the LOOP.
419   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
420   SmallPtrSet<const MachineInstr *, 4> AfterSet;
421   for (const auto &MI : MBB) {
422     // LOOP marker should be after any existing loop that ends here. Otherwise
423     // we assume the instruction belongs to the loop.
424     if (MI.getOpcode() == WebAssembly::END_LOOP)
425       BeforeSet.insert(&MI);
426 #ifndef NDEBUG
427     else
428       AfterSet.insert(&MI);
429 #endif
430   }
431 
432   // Mark the beginning of the loop.
433   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
434   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
435                                 TII.get(WebAssembly::LOOP))
436                             .addImm(int64_t(WebAssembly::BlockType::Void));
437 
438   // Decide where in Header to put the END_LOOP.
439   BeforeSet.clear();
440   AfterSet.clear();
441 #ifndef NDEBUG
442   for (const auto &MI : MBB)
443     // Existing END_LOOP markers belong to parent loops of this loop
444     if (MI.getOpcode() == WebAssembly::END_LOOP)
445       AfterSet.insert(&MI);
446 #endif
447 
448   // Mark the end of the loop (using arbitrary debug location that branched to
449   // the loop end as its location).
450   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
451   DebugLoc EndDL = AfterLoop->pred_empty()
452                        ? DebugLoc()
453                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
454   MachineInstr *End =
455       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
456   registerScope(Begin, End);
457 
458   assert((!ScopeTops[AfterLoop->getNumber()] ||
459           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
460          "With block sorting the outermost loop for a block should be first.");
461   updateScopeTops(&MBB, AfterLoop);
462 }
463 
placeTryMarker(MachineBasicBlock & MBB)464 void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
465   assert(MBB.isEHPad());
466   MachineFunction &MF = *MBB.getParent();
467   auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
468   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
469   const auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
470   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
471   SortRegionInfo SRI(MLI, WEI);
472   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
473 
474   // Compute the nearest common dominator of all unwind predecessors
475   MachineBasicBlock *Header = nullptr;
476   int MBBNumber = MBB.getNumber();
477   for (auto *Pred : MBB.predecessors()) {
478     if (Pred->getNumber() < MBBNumber) {
479       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
480       assert(!explicitlyBranchesTo(Pred, &MBB) &&
481              "Explicit branch to an EH pad!");
482     }
483   }
484   if (!Header)
485     return;
486 
487   // If this try is at the bottom of the function, insert a dummy block at the
488   // end.
489   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
490   assert(WE);
491   MachineBasicBlock *Bottom = SRI.getBottom(WE);
492 
493   auto Iter = std::next(Bottom->getIterator());
494   if (Iter == MF.end()) {
495     getAppendixBlock(MF);
496     Iter = std::next(Bottom->getIterator());
497   }
498   MachineBasicBlock *Cont = &*Iter;
499 
500   assert(Cont != &MF.front());
501   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
502 
503   // If the nearest common dominator is inside a more deeply nested context,
504   // walk out to the nearest scope which isn't more deeply nested.
505   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
506     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
507       if (ScopeTop->getNumber() > Header->getNumber()) {
508         // Skip over an intervening scope.
509         I = std::next(ScopeTop->getIterator());
510       } else {
511         // We found a scope level at an appropriate depth.
512         Header = ScopeTop;
513         break;
514       }
515     }
516   }
517 
518   // Decide where in Header to put the TRY.
519 
520   // Instructions that should go before the TRY.
521   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
522   // Instructions that should go after the TRY.
523   SmallPtrSet<const MachineInstr *, 4> AfterSet;
524   for (const auto &MI : *Header) {
525     // If there is a previously placed LOOP marker and the bottom block of the
526     // loop is above MBB, it should be after the TRY, because the loop is nested
527     // in this TRY. Otherwise it should be before the TRY.
528     if (MI.getOpcode() == WebAssembly::LOOP) {
529       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
530       if (MBB.getNumber() > LoopBottom->getNumber())
531         AfterSet.insert(&MI);
532 #ifndef NDEBUG
533       else
534         BeforeSet.insert(&MI);
535 #endif
536     }
537 
538     // All previously inserted BLOCK/TRY markers should be after the TRY because
539     // they are all nested trys.
540     if (MI.getOpcode() == WebAssembly::BLOCK ||
541         MI.getOpcode() == WebAssembly::TRY)
542       AfterSet.insert(&MI);
543 
544 #ifndef NDEBUG
545     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
546     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
547         MI.getOpcode() == WebAssembly::END_LOOP ||
548         MI.getOpcode() == WebAssembly::END_TRY)
549       BeforeSet.insert(&MI);
550 #endif
551 
552     // Terminators should go after the TRY.
553     if (MI.isTerminator())
554       AfterSet.insert(&MI);
555   }
556 
557   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
558   // contain the call within it. So the call should go after the TRY. The
559   // exception is when the header's terminator is a rethrow instruction, in
560   // which case that instruction, not a call instruction before it, is gonna
561   // throw.
562   MachineInstr *ThrowingCall = nullptr;
563   if (MBB.isPredecessor(Header)) {
564     auto TermPos = Header->getFirstTerminator();
565     if (TermPos == Header->end() ||
566         TermPos->getOpcode() != WebAssembly::RETHROW) {
567       for (auto &MI : reverse(*Header)) {
568         if (MI.isCall()) {
569           AfterSet.insert(&MI);
570           ThrowingCall = &MI;
571           // Possibly throwing calls are usually wrapped by EH_LABEL
572           // instructions. We don't want to split them and the call.
573           if (MI.getIterator() != Header->begin() &&
574               std::prev(MI.getIterator())->isEHLabel()) {
575             AfterSet.insert(&*std::prev(MI.getIterator()));
576             ThrowingCall = &*std::prev(MI.getIterator());
577           }
578           break;
579         }
580       }
581     }
582   }
583 
584   // Local expression tree should go after the TRY.
585   // For BLOCK placement, we start the search from the previous instruction of a
586   // BB's terminator, but in TRY's case, we should start from the previous
587   // instruction of a call that can throw, or a EH_LABEL that precedes the call,
588   // because the return values of the call's previous instructions can be
589   // stackified and consumed by the throwing call.
590   auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
591                                     : Header->getFirstTerminator();
592   for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
593     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
594       continue;
595     if (WebAssembly::isChild(*std::prev(I), MFI))
596       AfterSet.insert(&*std::prev(I));
597     else
598       break;
599   }
600 
601   // Add the TRY.
602   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
603   MachineInstr *Begin =
604       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
605               TII.get(WebAssembly::TRY))
606           .addImm(int64_t(WebAssembly::BlockType::Void));
607 
608   // Decide where in Header to put the END_TRY.
609   BeforeSet.clear();
610   AfterSet.clear();
611   for (const auto &MI : *Cont) {
612 #ifndef NDEBUG
613     // END_TRY should precede existing LOOP and BLOCK markers.
614     if (MI.getOpcode() == WebAssembly::LOOP ||
615         MI.getOpcode() == WebAssembly::BLOCK)
616       AfterSet.insert(&MI);
617 
618     // All END_TRY markers placed earlier belong to exceptions that contains
619     // this one.
620     if (MI.getOpcode() == WebAssembly::END_TRY)
621       AfterSet.insert(&MI);
622 #endif
623 
624     // If there is a previously placed END_LOOP marker and its header is after
625     // where TRY marker is, this loop is contained within the 'catch' part, so
626     // the END_TRY marker should go after that. Otherwise, the whole try-catch
627     // is contained within this loop, so the END_TRY should go before that.
628     if (MI.getOpcode() == WebAssembly::END_LOOP) {
629       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
630       // are in the same BB, LOOP is always before TRY.
631       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
632         BeforeSet.insert(&MI);
633 #ifndef NDEBUG
634       else
635         AfterSet.insert(&MI);
636 #endif
637     }
638 
639     // It is not possible for an END_BLOCK to be already in this block.
640   }
641 
642   // Mark the end of the TRY.
643   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
644   MachineInstr *End =
645       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
646               TII.get(WebAssembly::END_TRY));
647   registerTryScope(Begin, End, &MBB);
648 
649   // Track the farthest-spanning scope that ends at this point. We create two
650   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
651   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
652   // markers should not span across 'catch'. For example, this should not
653   // happen:
654   //
655   // try
656   //   block     --|  (X)
657   // catch         |
658   //   end_block --|
659   // end_try
660   for (auto *End : {&MBB, Cont})
661     updateScopeTops(Header, End);
662 }
663 
removeUnnecessaryInstrs(MachineFunction & MF)664 void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
665   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
666 
667   // When there is an unconditional branch right before a catch instruction and
668   // it branches to the end of end_try marker, we don't need the branch, because
669   // if there is no exception, the control flow transfers to that point anyway.
670   // bb0:
671   //   try
672   //     ...
673   //     br bb2      <- Not necessary
674   // bb1 (ehpad):
675   //   catch
676   //     ...
677   // bb2:            <- Continuation BB
678   //   end
679   //
680   // A more involved case: When the BB where 'end' is located is an another EH
681   // pad, the Cont (= continuation) BB is that EH pad's 'end' BB. For example,
682   // bb0:
683   //   try
684   //     try
685   //       ...
686   //       br bb3      <- Not necessary
687   // bb1 (ehpad):
688   //     catch
689   // bb2 (ehpad):
690   //     end
691   //   catch
692   //     ...
693   // bb3:            <- Continuation BB
694   //   end
695   //
696   // When the EH pad at hand is bb1, its matching end_try is in bb2. But it is
697   // another EH pad, so bb0's continuation BB becomes bb3. So 'br bb3' in the
698   // code can be deleted. This is why we run 'while' until 'Cont' is not an EH
699   // pad.
700   for (auto &MBB : MF) {
701     if (!MBB.isEHPad())
702       continue;
703 
704     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
705     SmallVector<MachineOperand, 4> Cond;
706     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
707 
708     MachineBasicBlock *Cont = &MBB;
709     while (Cont->isEHPad()) {
710       MachineInstr *Try = EHPadToTry[Cont];
711       MachineInstr *EndTry = BeginToEnd[Try];
712       // We started from an EH pad, so the end marker cannot be a delegate
713       assert(EndTry->getOpcode() != WebAssembly::DELEGATE);
714       Cont = EndTry->getParent();
715     }
716 
717     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
718     // This condition means either
719     // 1. This BB ends with a single unconditional branch whose destinaion is
720     //    Cont.
721     // 2. This BB ends with a conditional branch followed by an unconditional
722     //    branch, and the unconditional branch's destination is Cont.
723     // In both cases, we want to remove the last (= unconditional) branch.
724     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
725                        (!Cond.empty() && FBB && FBB == Cont))) {
726       bool ErasedUncondBr = false;
727       (void)ErasedUncondBr;
728       for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
729            I != E; --I) {
730         auto PrevI = std::prev(I);
731         if (PrevI->isTerminator()) {
732           assert(PrevI->getOpcode() == WebAssembly::BR);
733           PrevI->eraseFromParent();
734           ErasedUncondBr = true;
735           break;
736         }
737       }
738       assert(ErasedUncondBr && "Unconditional branch not erased!");
739     }
740   }
741 
742   // When there are block / end_block markers that overlap with try / end_try
743   // markers, and the block and try markers' return types are the same, the
744   // block /end_block markers are not necessary, because try / end_try markers
745   // also can serve as boundaries for branches.
746   // block         <- Not necessary
747   //   try
748   //     ...
749   //   catch
750   //     ...
751   //   end
752   // end           <- Not necessary
753   SmallVector<MachineInstr *, 32> ToDelete;
754   for (auto &MBB : MF) {
755     for (auto &MI : MBB) {
756       if (MI.getOpcode() != WebAssembly::TRY)
757         continue;
758       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
759       if (EndTry->getOpcode() == WebAssembly::DELEGATE)
760         continue;
761 
762       MachineBasicBlock *TryBB = Try->getParent();
763       MachineBasicBlock *Cont = EndTry->getParent();
764       int64_t RetType = Try->getOperand(0).getImm();
765       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
766            B != TryBB->begin() && E != Cont->end() &&
767            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
768            E->getOpcode() == WebAssembly::END_BLOCK &&
769            std::prev(B)->getOperand(0).getImm() == RetType;
770            --B, ++E) {
771         ToDelete.push_back(&*std::prev(B));
772         ToDelete.push_back(&*E);
773       }
774     }
775   }
776   for (auto *MI : ToDelete) {
777     if (MI->getOpcode() == WebAssembly::BLOCK)
778       unregisterScope(MI);
779     MI->eraseFromParent();
780   }
781 }
782 
783 // When MBB is split into MBB and Split, we should unstackify defs in MBB that
784 // have their uses in Split.
unstackifyVRegsUsedInSplitBB(MachineBasicBlock & MBB,MachineBasicBlock & Split)785 static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB,
786                                          MachineBasicBlock &Split) {
787   MachineFunction &MF = *MBB.getParent();
788   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
789   auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
790   auto &MRI = MF.getRegInfo();
791 
792   for (auto &MI : Split) {
793     for (auto &MO : MI.explicit_uses()) {
794       if (!MO.isReg() || MO.getReg().isPhysical())
795         continue;
796       if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
797         if (Def->getParent() == &MBB)
798           MFI.unstackifyVReg(MO.getReg());
799     }
800   }
801 
802   // In RegStackify, when a register definition is used multiple times,
803   //    Reg = INST ...
804   //    INST ..., Reg, ...
805   //    INST ..., Reg, ...
806   //    INST ..., Reg, ...
807   //
808   // we introduce a TEE, which has the following form:
809   //    DefReg = INST ...
810   //    TeeReg, Reg = TEE_... DefReg
811   //    INST ..., TeeReg, ...
812   //    INST ..., Reg, ...
813   //    INST ..., Reg, ...
814   // with DefReg and TeeReg stackified but Reg not stackified.
815   //
816   // But the invariant that TeeReg should be stackified can be violated while we
817   // unstackify registers in the split BB above. In this case, we convert TEEs
818   // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
819   //    DefReg = INST ...
820   //    TeeReg = COPY DefReg
821   //    Reg = COPY DefReg
822   //    INST ..., TeeReg, ...
823   //    INST ..., Reg, ...
824   //    INST ..., Reg, ...
825   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
826     if (!WebAssembly::isTee(MI.getOpcode()))
827       continue;
828     Register TeeReg = MI.getOperand(0).getReg();
829     Register Reg = MI.getOperand(1).getReg();
830     Register DefReg = MI.getOperand(2).getReg();
831     if (!MFI.isVRegStackified(TeeReg)) {
832       // Now we are not using TEE anymore, so unstackify DefReg too
833       MFI.unstackifyVReg(DefReg);
834       unsigned CopyOpc =
835           WebAssembly::getCopyOpcodeForRegClass(MRI.getRegClass(DefReg));
836       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
837           .addReg(DefReg);
838       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
839       MI.eraseFromParent();
840     }
841   }
842 }
843 
844 // Wrap the given range of instruction with try-delegate. RangeBegin and
845 // RangeEnd are inclusive.
addTryDelegate(MachineInstr * RangeBegin,MachineInstr * RangeEnd,MachineBasicBlock * DelegateDest)846 void WebAssemblyCFGStackify::addTryDelegate(MachineInstr *RangeBegin,
847                                             MachineInstr *RangeEnd,
848                                             MachineBasicBlock *DelegateDest) {
849   auto *BeginBB = RangeBegin->getParent();
850   auto *EndBB = RangeEnd->getParent();
851   MachineFunction &MF = *BeginBB->getParent();
852   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
853   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
854 
855   // Local expression tree before the first call of this range should go
856   // after the nested TRY.
857   SmallPtrSet<const MachineInstr *, 4> AfterSet;
858   AfterSet.insert(RangeBegin);
859   for (auto I = MachineBasicBlock::iterator(RangeBegin), E = BeginBB->begin();
860        I != E; --I) {
861     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
862       continue;
863     if (WebAssembly::isChild(*std::prev(I), MFI))
864       AfterSet.insert(&*std::prev(I));
865     else
866       break;
867   }
868 
869   // Create the nested try instruction.
870   auto TryPos = getLatestInsertPos(
871       BeginBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet);
872   MachineInstr *Try = BuildMI(*BeginBB, TryPos, RangeBegin->getDebugLoc(),
873                               TII.get(WebAssembly::TRY))
874                           .addImm(int64_t(WebAssembly::BlockType::Void));
875 
876   // Create a BB to insert the 'delegate' instruction.
877   MachineBasicBlock *DelegateBB = MF.CreateMachineBasicBlock();
878   // If the destination of 'delegate' is not the caller, adds the destination to
879   // the BB's successors.
880   if (DelegateDest != FakeCallerBB)
881     DelegateBB->addSuccessor(DelegateDest);
882 
883   auto SplitPos = std::next(RangeEnd->getIterator());
884   if (SplitPos == EndBB->end()) {
885     // If the range's end instruction is at the end of the BB, insert the new
886     // delegate BB after the current BB.
887     MF.insert(std::next(EndBB->getIterator()), DelegateBB);
888     EndBB->addSuccessor(DelegateBB);
889 
890   } else {
891     // When the split pos is in the middle of a BB, we split the BB into two and
892     // put the 'delegate' BB in between. We normally create a split BB and make
893     // it a successor of the original BB (PostSplit == true), but in case the BB
894     // is an EH pad and the split pos is before 'catch', we should preserve the
895     // BB's property, including that it is an EH pad, in the later part of the
896     // BB, where 'catch' is. In this case we set PostSplit to false.
897     bool PostSplit = true;
898     if (EndBB->isEHPad()) {
899       for (auto I = MachineBasicBlock::iterator(SplitPos), E = EndBB->end();
900            I != E; ++I) {
901         if (WebAssembly::isCatch(I->getOpcode())) {
902           PostSplit = false;
903           break;
904         }
905       }
906     }
907 
908     MachineBasicBlock *PreBB = nullptr, *PostBB = nullptr;
909     if (PostSplit) {
910       // If the range's end instruction is in the middle of the BB, we split the
911       // BB into two and insert the delegate BB in between.
912       // - Before:
913       // bb:
914       //   range_end
915       //   other_insts
916       //
917       // - After:
918       // pre_bb: (previous 'bb')
919       //   range_end
920       // delegate_bb: (new)
921       //   delegate
922       // post_bb: (new)
923       //   other_insts
924       PreBB = EndBB;
925       PostBB = MF.CreateMachineBasicBlock();
926       MF.insert(std::next(PreBB->getIterator()), PostBB);
927       MF.insert(std::next(PreBB->getIterator()), DelegateBB);
928       PostBB->splice(PostBB->end(), PreBB, SplitPos, PreBB->end());
929       PostBB->transferSuccessors(PreBB);
930     } else {
931       // - Before:
932       // ehpad:
933       //   range_end
934       //   catch
935       //   ...
936       //
937       // - After:
938       // pre_bb: (new)
939       //   range_end
940       // delegate_bb: (new)
941       //   delegate
942       // post_bb: (previous 'ehpad')
943       //   catch
944       //   ...
945       assert(EndBB->isEHPad());
946       PreBB = MF.CreateMachineBasicBlock();
947       PostBB = EndBB;
948       MF.insert(PostBB->getIterator(), PreBB);
949       MF.insert(PostBB->getIterator(), DelegateBB);
950       PreBB->splice(PreBB->end(), PostBB, PostBB->begin(), SplitPos);
951       // We don't need to transfer predecessors of the EH pad to 'PreBB',
952       // because an EH pad's predecessors are all through unwind edges and they
953       // should still unwind to the EH pad, not PreBB.
954     }
955     unstackifyVRegsUsedInSplitBB(*PreBB, *PostBB);
956     PreBB->addSuccessor(DelegateBB);
957     PreBB->addSuccessor(PostBB);
958   }
959 
960   // Add 'delegate' instruction in the delegate BB created above.
961   MachineInstr *Delegate = BuildMI(DelegateBB, RangeEnd->getDebugLoc(),
962                                    TII.get(WebAssembly::DELEGATE))
963                                .addMBB(DelegateDest);
964   registerTryScope(Try, Delegate, nullptr);
965 }
966 
fixCallUnwindMismatches(MachineFunction & MF)967 bool WebAssemblyCFGStackify::fixCallUnwindMismatches(MachineFunction &MF) {
968   // Linearizing the control flow by placing TRY / END_TRY markers can create
969   // mismatches in unwind destinations for throwing instructions, such as calls.
970   //
971   // We use the 'delegate' instruction to fix the unwind mismatches. 'delegate'
972   // instruction delegates an exception to an outer 'catch'. It can target not
973   // only 'catch' but all block-like structures including another 'delegate',
974   // but with slightly different semantics than branches. When it targets a
975   // 'catch', it will delegate the exception to that catch. It is being
976   // discussed how to define the semantics when 'delegate''s target is a non-try
977   // block: it will either be a validation failure or it will target the next
978   // outer try-catch. But anyway our LLVM backend currently does not generate
979   // such code. The example below illustrates where the 'delegate' instruction
980   // in the middle will delegate the exception to, depending on the value of N.
981   // try
982   //   try
983   //     block
984   //       try
985   //         try
986   //           call @foo
987   //         delegate N    ;; Where will this delegate to?
988   //       catch           ;; N == 0
989   //       end
990   //     end               ;; N == 1 (invalid; will not be generated)
991   //   delegate            ;; N == 2
992   // catch                 ;; N == 3
993   // end
994   //                       ;; N == 4 (to caller)
995 
996   // 1. When an instruction may throw, but the EH pad it will unwind to can be
997   //    different from the original CFG.
998   //
999   // Example: we have the following CFG:
1000   // bb0:
1001   //   call @foo    ; if it throws, unwind to bb2
1002   // bb1:
1003   //   call @bar    ; if it throws, unwind to bb3
1004   // bb2 (ehpad):
1005   //   catch
1006   //   ...
1007   // bb3 (ehpad)
1008   //   catch
1009   //   ...
1010   //
1011   // And the CFG is sorted in this order. Then after placing TRY markers, it
1012   // will look like: (BB markers are omitted)
1013   // try
1014   //   try
1015   //     call @foo
1016   //     call @bar   ;; if it throws, unwind to bb3
1017   //   catch         ;; ehpad (bb2)
1018   //     ...
1019   //   end_try
1020   // catch           ;; ehpad (bb3)
1021   //   ...
1022   // end_try
1023   //
1024   // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it
1025   // is supposed to end up. We solve this problem by wrapping the mismatching
1026   // call with an inner try-delegate that rethrows the exception to the right
1027   // 'catch'.
1028   //
1029   // try
1030   //   try
1031   //     call @foo
1032   //     try               ;; (new)
1033   //       call @bar
1034   //     delegate 1 (bb3)  ;; (new)
1035   //   catch               ;; ehpad (bb2)
1036   //     ...
1037   //   end_try
1038   // catch                 ;; ehpad (bb3)
1039   //   ...
1040   // end_try
1041   //
1042   // ---
1043   // 2. The same as 1, but in this case an instruction unwinds to a caller
1044   //    function and not another EH pad.
1045   //
1046   // Example: we have the following CFG:
1047   // bb0:
1048   //   call @foo       ; if it throws, unwind to bb2
1049   // bb1:
1050   //   call @bar       ; if it throws, unwind to caller
1051   // bb2 (ehpad):
1052   //   catch
1053   //   ...
1054   //
1055   // And the CFG is sorted in this order. Then after placing TRY markers, it
1056   // will look like:
1057   // try
1058   //   call @foo
1059   //   call @bar     ;; if it throws, unwind to caller
1060   // catch           ;; ehpad (bb2)
1061   //   ...
1062   // end_try
1063   //
1064   // Now if bar() throws, it is going to end up ip in bb2, when it is supposed
1065   // throw up to the caller. We solve this problem in the same way, but in this
1066   // case 'delegate's immediate argument is the number of block depths + 1,
1067   // which means it rethrows to the caller.
1068   // try
1069   //   call @foo
1070   //   try                  ;; (new)
1071   //     call @bar
1072   //   delegate 1 (caller)  ;; (new)
1073   // catch                  ;; ehpad (bb2)
1074   //   ...
1075   // end_try
1076   //
1077   // Before rewriteDepthImmediates, delegate's argument is a BB. In case of the
1078   // caller, it will take a fake BB generated by getFakeCallerBlock(), which
1079   // will be converted to a correct immediate argument later.
1080   //
1081   // In case there are multiple calls in a BB that may throw to the caller, they
1082   // can be wrapped together in one nested try-delegate scope. (In 1, this
1083   // couldn't happen, because may-throwing instruction there had an unwind
1084   // destination, i.e., it was an invoke before, and there could be only one
1085   // invoke within a BB.)
1086 
1087   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
1088   // Range of intructions to be wrapped in a new nested try/catch. A range
1089   // exists in a single BB and does not span multiple BBs.
1090   using TryRange = std::pair<MachineInstr *, MachineInstr *>;
1091   // In original CFG, <unwind destination BB, a vector of try ranges>
1092   DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges;
1093 
1094   // Gather possibly throwing calls (i.e., previously invokes) whose current
1095   // unwind destination is not the same as the original CFG. (Case 1)
1096 
1097   for (auto &MBB : reverse(MF)) {
1098     bool SeenThrowableInstInBB = false;
1099     for (auto &MI : reverse(MBB)) {
1100       if (MI.getOpcode() == WebAssembly::TRY)
1101         EHPadStack.pop_back();
1102       else if (WebAssembly::isCatch(MI.getOpcode()))
1103         EHPadStack.push_back(MI.getParent());
1104 
1105       // In this loop we only gather calls that have an EH pad to unwind. So
1106       // there will be at most 1 such call (= invoke) in a BB, so after we've
1107       // seen one, we can skip the rest of BB. Also if MBB has no EH pad
1108       // successor or MI does not throw, this is not an invoke.
1109       if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() ||
1110           !WebAssembly::mayThrow(MI))
1111         continue;
1112       SeenThrowableInstInBB = true;
1113 
1114       // If the EH pad on the stack top is where this instruction should unwind
1115       // next, we're good.
1116       MachineBasicBlock *UnwindDest = getFakeCallerBlock(MF);
1117       for (auto *Succ : MBB.successors()) {
1118         // Even though semantically a BB can have multiple successors in case an
1119         // exception is not caught by a catchpad, in our backend implementation
1120         // it is guaranteed that a BB can have at most one EH pad successor. For
1121         // details, refer to comments in findWasmUnwindDestinations function in
1122         // SelectionDAGBuilder.cpp.
1123         if (Succ->isEHPad()) {
1124           UnwindDest = Succ;
1125           break;
1126         }
1127       }
1128       if (EHPadStack.back() == UnwindDest)
1129         continue;
1130 
1131       // Include EH_LABELs in the range before and afer the invoke
1132       MachineInstr *RangeBegin = &MI, *RangeEnd = &MI;
1133       if (RangeBegin->getIterator() != MBB.begin() &&
1134           std::prev(RangeBegin->getIterator())->isEHLabel())
1135         RangeBegin = &*std::prev(RangeBegin->getIterator());
1136       if (std::next(RangeEnd->getIterator()) != MBB.end() &&
1137           std::next(RangeEnd->getIterator())->isEHLabel())
1138         RangeEnd = &*std::next(RangeEnd->getIterator());
1139 
1140       // If not, record the range.
1141       UnwindDestToTryRanges[UnwindDest].push_back(
1142           TryRange(RangeBegin, RangeEnd));
1143       LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = " << MBB.getName()
1144                         << "\nCall = " << MI
1145                         << "\nOriginal dest = " << UnwindDest->getName()
1146                         << "  Current dest = " << EHPadStack.back()->getName()
1147                         << "\n\n");
1148     }
1149   }
1150 
1151   assert(EHPadStack.empty());
1152 
1153   // Gather possibly throwing calls that are supposed to unwind up to the caller
1154   // if they throw, but currently unwind to an incorrect destination. Unlike the
1155   // loop above, there can be multiple calls within a BB that unwind to the
1156   // caller, which we should group together in a range. (Case 2)
1157 
1158   MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive
1159 
1160   // Record the range.
1161   auto RecordCallerMismatchRange = [&](const MachineBasicBlock *CurrentDest) {
1162     UnwindDestToTryRanges[getFakeCallerBlock(MF)].push_back(
1163         TryRange(RangeBegin, RangeEnd));
1164     LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = "
1165                       << RangeBegin->getParent()->getName()
1166                       << "\nRange begin = " << *RangeBegin
1167                       << "Range end = " << *RangeEnd
1168                       << "\nOriginal dest = caller  Current dest = "
1169                       << CurrentDest->getName() << "\n\n");
1170     RangeBegin = RangeEnd = nullptr; // Reset range pointers
1171   };
1172 
1173   for (auto &MBB : reverse(MF)) {
1174     bool SeenThrowableInstInBB = false;
1175     for (auto &MI : reverse(MBB)) {
1176       bool MayThrow = WebAssembly::mayThrow(MI);
1177 
1178       // If MBB has an EH pad successor and this is the last instruction that
1179       // may throw, this instruction unwinds to the EH pad and not to the
1180       // caller.
1181       if (MBB.hasEHPadSuccessor() && MayThrow && !SeenThrowableInstInBB)
1182         SeenThrowableInstInBB = true;
1183 
1184       // We wrap up the current range when we see a marker even if we haven't
1185       // finished a BB.
1186       else if (RangeEnd && WebAssembly::isMarker(MI.getOpcode()))
1187         RecordCallerMismatchRange(EHPadStack.back());
1188 
1189       // If EHPadStack is empty, that means it correctly unwinds to the caller
1190       // if it throws, so we're good. If MI does not throw, we're good too.
1191       else if (EHPadStack.empty() || !MayThrow) {
1192       }
1193 
1194       // We found an instruction that unwinds to the caller but currently has an
1195       // incorrect unwind destination. Create a new range or increment the
1196       // currently existing range.
1197       else {
1198         if (!RangeEnd)
1199           RangeBegin = RangeEnd = &MI;
1200         else
1201           RangeBegin = &MI;
1202       }
1203 
1204       // Update EHPadStack.
1205       if (MI.getOpcode() == WebAssembly::TRY)
1206         EHPadStack.pop_back();
1207       else if (WebAssembly::isCatch(MI.getOpcode()))
1208         EHPadStack.push_back(MI.getParent());
1209     }
1210 
1211     if (RangeEnd)
1212       RecordCallerMismatchRange(EHPadStack.back());
1213   }
1214 
1215   assert(EHPadStack.empty());
1216 
1217   // We don't have any unwind destination mismatches to resolve.
1218   if (UnwindDestToTryRanges.empty())
1219     return false;
1220 
1221   // Now we fix the mismatches by wrapping calls with inner try-delegates.
1222   for (auto &P : UnwindDestToTryRanges) {
1223     NumCallUnwindMismatches += P.second.size();
1224     MachineBasicBlock *UnwindDest = P.first;
1225     auto &TryRanges = P.second;
1226 
1227     for (auto Range : TryRanges) {
1228       MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr;
1229       std::tie(RangeBegin, RangeEnd) = Range;
1230       auto *MBB = RangeBegin->getParent();
1231 
1232       // If this BB has an EH pad successor, i.e., ends with an 'invoke', now we
1233       // are going to wrap the invoke with try-delegate, making the 'delegate'
1234       // BB the new successor instead, so remove the EH pad succesor here. The
1235       // BB may not have an EH pad successor if calls in this BB throw to the
1236       // caller.
1237       MachineBasicBlock *EHPad = nullptr;
1238       for (auto *Succ : MBB->successors()) {
1239         if (Succ->isEHPad()) {
1240           EHPad = Succ;
1241           break;
1242         }
1243       }
1244       if (EHPad)
1245         MBB->removeSuccessor(EHPad);
1246 
1247       addTryDelegate(RangeBegin, RangeEnd, UnwindDest);
1248     }
1249   }
1250 
1251   return true;
1252 }
1253 
fixCatchUnwindMismatches(MachineFunction & MF)1254 bool WebAssemblyCFGStackify::fixCatchUnwindMismatches(MachineFunction &MF) {
1255   // There is another kind of unwind destination mismatches besides call unwind
1256   // mismatches, which we will call "catch unwind mismatches". See this example
1257   // after the marker placement:
1258   // try
1259   //   try
1260   //     call @foo
1261   //   catch __cpp_exception  ;; ehpad A (next unwind dest: caller)
1262   //     ...
1263   //   end_try
1264   // catch_all                ;; ehpad B
1265   //   ...
1266   // end_try
1267   //
1268   // 'call @foo's unwind destination is the ehpad A. But suppose 'call @foo'
1269   // throws a foreign exception that is not caught by ehpad A, and its next
1270   // destination should be the caller. But after control flow linearization,
1271   // another EH pad can be placed in between (e.g. ehpad B here), making the
1272   // next unwind destination incorrect. In this case, the  foreign exception
1273   // will instead go to ehpad B and will be caught there instead. In this
1274   // example the correct next unwind destination is the caller, but it can be
1275   // another outer catch in other cases.
1276   //
1277   // There is no specific 'call' or 'throw' instruction to wrap with a
1278   // try-delegate, so we wrap the whole try-catch-end with a try-delegate and
1279   // make it rethrow to the right destination, as in the example below:
1280   // try
1281   //   try                     ;; (new)
1282   //     try
1283   //       call @foo
1284   //     catch __cpp_exception ;; ehpad A (next unwind dest: caller)
1285   //       ...
1286   //     end_try
1287   //   delegate 1 (caller)     ;; (new)
1288   // catch_all                 ;; ehpad B
1289   //   ...
1290   // end_try
1291 
1292   const auto *EHInfo = MF.getWasmEHFuncInfo();
1293   assert(EHInfo);
1294   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
1295   // For EH pads that have catch unwind mismatches, a map of <EH pad, its
1296   // correct unwind destination>.
1297   DenseMap<MachineBasicBlock *, MachineBasicBlock *> EHPadToUnwindDest;
1298 
1299   for (auto &MBB : reverse(MF)) {
1300     for (auto &MI : reverse(MBB)) {
1301       if (MI.getOpcode() == WebAssembly::TRY)
1302         EHPadStack.pop_back();
1303       else if (MI.getOpcode() == WebAssembly::DELEGATE)
1304         EHPadStack.push_back(&MBB);
1305       else if (WebAssembly::isCatch(MI.getOpcode())) {
1306         auto *EHPad = &MBB;
1307 
1308         // catch_all always catches an exception, so we don't need to do
1309         // anything
1310         if (MI.getOpcode() == WebAssembly::CATCH_ALL) {
1311         }
1312 
1313         // This can happen when the unwind dest was removed during the
1314         // optimization, e.g. because it was unreachable.
1315         else if (EHPadStack.empty() && EHInfo->hasUnwindDest(EHPad)) {
1316           LLVM_DEBUG(dbgs() << "EHPad (" << EHPad->getName()
1317                             << "'s unwind destination does not exist anymore"
1318                             << "\n\n");
1319         }
1320 
1321         // The EHPad's next unwind destination is the caller, but we incorrectly
1322         // unwind to another EH pad.
1323         else if (!EHPadStack.empty() && !EHInfo->hasUnwindDest(EHPad)) {
1324           EHPadToUnwindDest[EHPad] = getFakeCallerBlock(MF);
1325           LLVM_DEBUG(dbgs()
1326                      << "- Catch unwind mismatch:\nEHPad = " << EHPad->getName()
1327                      << "  Original dest = caller  Current dest = "
1328                      << EHPadStack.back()->getName() << "\n\n");
1329         }
1330 
1331         // The EHPad's next unwind destination is an EH pad, whereas we
1332         // incorrectly unwind to another EH pad.
1333         else if (!EHPadStack.empty() && EHInfo->hasUnwindDest(EHPad)) {
1334           auto *UnwindDest = EHInfo->getUnwindDest(EHPad);
1335           if (EHPadStack.back() != UnwindDest) {
1336             EHPadToUnwindDest[EHPad] = UnwindDest;
1337             LLVM_DEBUG(dbgs() << "- Catch unwind mismatch:\nEHPad = "
1338                               << EHPad->getName() << "  Original dest = "
1339                               << UnwindDest->getName() << "  Current dest = "
1340                               << EHPadStack.back()->getName() << "\n\n");
1341           }
1342         }
1343 
1344         EHPadStack.push_back(EHPad);
1345       }
1346     }
1347   }
1348 
1349   assert(EHPadStack.empty());
1350   if (EHPadToUnwindDest.empty())
1351     return false;
1352   NumCatchUnwindMismatches += EHPadToUnwindDest.size();
1353   SmallPtrSet<MachineBasicBlock *, 4> NewEndTryBBs;
1354 
1355   for (auto &P : EHPadToUnwindDest) {
1356     MachineBasicBlock *EHPad = P.first;
1357     MachineBasicBlock *UnwindDest = P.second;
1358     MachineInstr *Try = EHPadToTry[EHPad];
1359     MachineInstr *EndTry = BeginToEnd[Try];
1360     addTryDelegate(Try, EndTry, UnwindDest);
1361     NewEndTryBBs.insert(EndTry->getParent());
1362   }
1363 
1364   // Adding a try-delegate wrapping an existing try-catch-end can make existing
1365   // branch destination BBs invalid. For example,
1366   //
1367   // - Before:
1368   // bb0:
1369   //   block
1370   //     br bb3
1371   // bb1:
1372   //     try
1373   //       ...
1374   // bb2: (ehpad)
1375   //     catch
1376   // bb3:
1377   //     end_try
1378   //   end_block   ;; 'br bb3' targets here
1379   //
1380   // Suppose this try-catch-end has a catch unwind mismatch, so we need to wrap
1381   // this with a try-delegate. Then this becomes:
1382   //
1383   // - After:
1384   // bb0:
1385   //   block
1386   //     br bb3    ;; invalid destination!
1387   // bb1:
1388   //     try       ;; (new instruction)
1389   //       try
1390   //         ...
1391   // bb2: (ehpad)
1392   //       catch
1393   // bb3:
1394   //       end_try ;; 'br bb3' still incorrectly targets here!
1395   // delegate_bb:  ;; (new BB)
1396   //     delegate  ;; (new instruction)
1397   // split_bb:     ;; (new BB)
1398   //   end_block
1399   //
1400   // Now 'br bb3' incorrectly branches to an inner scope.
1401   //
1402   // As we can see in this case, when branches target a BB that has both
1403   // 'end_try' and 'end_block' and the BB is split to insert a 'delegate', we
1404   // have to remap existing branch destinations so that they target not the
1405   // 'end_try' BB but the new 'end_block' BB. There can be multiple 'delegate's
1406   // in between, so we try to find the next BB with 'end_block' instruction. In
1407   // this example, the 'br bb3' instruction should be remapped to 'br split_bb'.
1408   for (auto &MBB : MF) {
1409     for (auto &MI : MBB) {
1410       if (MI.isTerminator()) {
1411         for (auto &MO : MI.operands()) {
1412           if (MO.isMBB() && NewEndTryBBs.count(MO.getMBB())) {
1413             auto *BrDest = MO.getMBB();
1414             bool FoundEndBlock = false;
1415             for (; std::next(BrDest->getIterator()) != MF.end();
1416                  BrDest = BrDest->getNextNode()) {
1417               for (const auto &MI : *BrDest) {
1418                 if (MI.getOpcode() == WebAssembly::END_BLOCK) {
1419                   FoundEndBlock = true;
1420                   break;
1421                 }
1422               }
1423               if (FoundEndBlock)
1424                 break;
1425             }
1426             assert(FoundEndBlock);
1427             MO.setMBB(BrDest);
1428           }
1429         }
1430       }
1431     }
1432   }
1433 
1434   return true;
1435 }
1436 
recalculateScopeTops(MachineFunction & MF)1437 void WebAssemblyCFGStackify::recalculateScopeTops(MachineFunction &MF) {
1438   // Renumber BBs and recalculate ScopeTop info because new BBs might have been
1439   // created and inserted during fixing unwind mismatches.
1440   MF.RenumberBlocks();
1441   ScopeTops.clear();
1442   ScopeTops.resize(MF.getNumBlockIDs());
1443   for (auto &MBB : reverse(MF)) {
1444     for (auto &MI : reverse(MBB)) {
1445       if (ScopeTops[MBB.getNumber()])
1446         break;
1447       switch (MI.getOpcode()) {
1448       case WebAssembly::END_BLOCK:
1449       case WebAssembly::END_LOOP:
1450       case WebAssembly::END_TRY:
1451       case WebAssembly::DELEGATE:
1452         updateScopeTops(EndToBegin[&MI]->getParent(), &MBB);
1453         break;
1454       case WebAssembly::CATCH:
1455       case WebAssembly::CATCH_ALL:
1456         updateScopeTops(EHPadToTry[&MBB]->getParent(), &MBB);
1457         break;
1458       }
1459     }
1460   }
1461 }
1462 
1463 /// In normal assembly languages, when the end of a function is unreachable,
1464 /// because the function ends in an infinite loop or a noreturn call or similar,
1465 /// it isn't necessary to worry about the function return type at the end of
1466 /// the function, because it's never reached. However, in WebAssembly, blocks
1467 /// that end at the function end need to have a return type signature that
1468 /// matches the function signature, even though it's unreachable. This function
1469 /// checks for such cases and fixes up the signatures.
fixEndsAtEndOfFunction(MachineFunction & MF)1470 void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
1471   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
1472 
1473   if (MFI.getResults().empty())
1474     return;
1475 
1476   // MCInstLower will add the proper types to multivalue signatures based on the
1477   // function return type
1478   WebAssembly::BlockType RetType =
1479       MFI.getResults().size() > 1
1480           ? WebAssembly::BlockType::Multivalue
1481           : WebAssembly::BlockType(
1482                 WebAssembly::toValType(MFI.getResults().front()));
1483 
1484   SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist;
1485   Worklist.push_back(MF.rbegin()->rbegin());
1486 
1487   auto Process = [&](MachineBasicBlock::reverse_iterator It) {
1488     auto *MBB = It->getParent();
1489     while (It != MBB->rend()) {
1490       MachineInstr &MI = *It++;
1491       if (MI.isPosition() || MI.isDebugInstr())
1492         continue;
1493       switch (MI.getOpcode()) {
1494       case WebAssembly::END_TRY: {
1495         // If a 'try''s return type is fixed, both its try body and catch body
1496         // should satisfy the return type, so we need to search 'end'
1497         // instructions before its corresponding 'catch' too.
1498         auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
1499         assert(EHPad);
1500         auto NextIt =
1501             std::next(WebAssembly::findCatch(EHPad)->getReverseIterator());
1502         if (NextIt != EHPad->rend())
1503           Worklist.push_back(NextIt);
1504         [[fallthrough]];
1505       }
1506       case WebAssembly::END_BLOCK:
1507       case WebAssembly::END_LOOP:
1508       case WebAssembly::DELEGATE:
1509         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
1510         continue;
1511       default:
1512         // Something other than an `end`. We're done for this BB.
1513         return;
1514       }
1515     }
1516     // We've reached the beginning of a BB. Continue the search in the previous
1517     // BB.
1518     Worklist.push_back(MBB->getPrevNode()->rbegin());
1519   };
1520 
1521   while (!Worklist.empty())
1522     Process(Worklist.pop_back_val());
1523 }
1524 
1525 // WebAssembly functions end with an end instruction, as if the function body
1526 // were a block.
appendEndToFunction(MachineFunction & MF,const WebAssemblyInstrInfo & TII)1527 static void appendEndToFunction(MachineFunction &MF,
1528                                 const WebAssemblyInstrInfo &TII) {
1529   BuildMI(MF.back(), MF.back().end(),
1530           MF.back().findPrevDebugLoc(MF.back().end()),
1531           TII.get(WebAssembly::END_FUNCTION));
1532 }
1533 
1534 /// Insert LOOP/TRY/BLOCK markers at appropriate places.
placeMarkers(MachineFunction & MF)1535 void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
1536   // We allocate one more than the number of blocks in the function to
1537   // accommodate for the possible fake block we may insert at the end.
1538   ScopeTops.resize(MF.getNumBlockIDs() + 1);
1539   // Place the LOOP for MBB if MBB is the header of a loop.
1540   for (auto &MBB : MF)
1541     placeLoopMarker(MBB);
1542 
1543   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1544   for (auto &MBB : MF) {
1545     if (MBB.isEHPad()) {
1546       // Place the TRY for MBB if MBB is the EH pad of an exception.
1547       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1548           MF.getFunction().hasPersonalityFn())
1549         placeTryMarker(MBB);
1550     } else {
1551       // Place the BLOCK for MBB if MBB is branched to from above.
1552       placeBlockMarker(MBB);
1553     }
1554   }
1555   // Fix mismatches in unwind destinations induced by linearizing the code.
1556   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1557       MF.getFunction().hasPersonalityFn()) {
1558     bool Changed = fixCallUnwindMismatches(MF);
1559     Changed |= fixCatchUnwindMismatches(MF);
1560     if (Changed)
1561       recalculateScopeTops(MF);
1562   }
1563 }
1564 
getBranchDepth(const SmallVectorImpl<EndMarkerInfo> & Stack,const MachineBasicBlock * MBB)1565 unsigned WebAssemblyCFGStackify::getBranchDepth(
1566     const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
1567   unsigned Depth = 0;
1568   for (auto X : reverse(Stack)) {
1569     if (X.first == MBB)
1570       break;
1571     ++Depth;
1572   }
1573   assert(Depth < Stack.size() && "Branch destination should be in scope");
1574   return Depth;
1575 }
1576 
getDelegateDepth(const SmallVectorImpl<EndMarkerInfo> & Stack,const MachineBasicBlock * MBB)1577 unsigned WebAssemblyCFGStackify::getDelegateDepth(
1578     const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
1579   if (MBB == FakeCallerBB)
1580     return Stack.size();
1581   // Delegate's destination is either a catch or a another delegate BB. When the
1582   // destination is another delegate, we can compute the argument in the same
1583   // way as branches, because the target delegate BB only contains the single
1584   // delegate instruction.
1585   if (!MBB->isEHPad()) // Target is a delegate BB
1586     return getBranchDepth(Stack, MBB);
1587 
1588   // When the delegate's destination is a catch BB, we need to use its
1589   // corresponding try's end_try BB because Stack contains each marker's end BB.
1590   // Also we need to check if the end marker instruction matches, because a
1591   // single BB can contain multiple end markers, like this:
1592   // bb:
1593   //   END_BLOCK
1594   //   END_TRY
1595   //   END_BLOCK
1596   //   END_TRY
1597   //   ...
1598   //
1599   // In case of branches getting the immediate that targets any of these is
1600   // fine, but delegate has to exactly target the correct try.
1601   unsigned Depth = 0;
1602   const MachineInstr *EndTry = BeginToEnd[EHPadToTry[MBB]];
1603   for (auto X : reverse(Stack)) {
1604     if (X.first == EndTry->getParent() && X.second == EndTry)
1605       break;
1606     ++Depth;
1607   }
1608   assert(Depth < Stack.size() && "Delegate destination should be in scope");
1609   return Depth;
1610 }
1611 
getRethrowDepth(const SmallVectorImpl<EndMarkerInfo> & Stack,const MachineBasicBlock * EHPadToRethrow)1612 unsigned WebAssemblyCFGStackify::getRethrowDepth(
1613     const SmallVectorImpl<EndMarkerInfo> &Stack,
1614     const MachineBasicBlock *EHPadToRethrow) {
1615   unsigned Depth = 0;
1616   for (auto X : reverse(Stack)) {
1617     const MachineInstr *End = X.second;
1618     if (End->getOpcode() == WebAssembly::END_TRY) {
1619       auto *EHPad = TryToEHPad[EndToBegin[End]];
1620       if (EHPadToRethrow == EHPad)
1621         break;
1622     }
1623     ++Depth;
1624   }
1625   assert(Depth < Stack.size() && "Rethrow destination should be in scope");
1626   return Depth;
1627 }
1628 
rewriteDepthImmediates(MachineFunction & MF)1629 void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
1630   // Now rewrite references to basic blocks to be depth immediates.
1631   SmallVector<EndMarkerInfo, 8> Stack;
1632   for (auto &MBB : reverse(MF)) {
1633     for (MachineInstr &MI : llvm::reverse(MBB)) {
1634       switch (MI.getOpcode()) {
1635       case WebAssembly::BLOCK:
1636       case WebAssembly::TRY:
1637         assert(ScopeTops[Stack.back().first->getNumber()]->getNumber() <=
1638                    MBB.getNumber() &&
1639                "Block/try marker should be balanced");
1640         Stack.pop_back();
1641         break;
1642 
1643       case WebAssembly::LOOP:
1644         assert(Stack.back().first == &MBB && "Loop top should be balanced");
1645         Stack.pop_back();
1646         break;
1647 
1648       case WebAssembly::END_BLOCK:
1649       case WebAssembly::END_TRY:
1650         Stack.push_back(std::make_pair(&MBB, &MI));
1651         break;
1652 
1653       case WebAssembly::END_LOOP:
1654         Stack.push_back(std::make_pair(EndToBegin[&MI]->getParent(), &MI));
1655         break;
1656 
1657       default:
1658         if (MI.isTerminator()) {
1659           // Rewrite MBB operands to be depth immediates.
1660           SmallVector<MachineOperand, 4> Ops(MI.operands());
1661           while (MI.getNumOperands() > 0)
1662             MI.removeOperand(MI.getNumOperands() - 1);
1663           for (auto MO : Ops) {
1664             if (MO.isMBB()) {
1665               if (MI.getOpcode() == WebAssembly::DELEGATE)
1666                 MO = MachineOperand::CreateImm(
1667                     getDelegateDepth(Stack, MO.getMBB()));
1668               else if (MI.getOpcode() == WebAssembly::RETHROW)
1669                 MO = MachineOperand::CreateImm(
1670                     getRethrowDepth(Stack, MO.getMBB()));
1671               else
1672                 MO = MachineOperand::CreateImm(
1673                     getBranchDepth(Stack, MO.getMBB()));
1674             }
1675             MI.addOperand(MF, MO);
1676           }
1677         }
1678 
1679         if (MI.getOpcode() == WebAssembly::DELEGATE)
1680           Stack.push_back(std::make_pair(&MBB, &MI));
1681         break;
1682       }
1683     }
1684   }
1685   assert(Stack.empty() && "Control flow should be balanced");
1686 }
1687 
cleanupFunctionData(MachineFunction & MF)1688 void WebAssemblyCFGStackify::cleanupFunctionData(MachineFunction &MF) {
1689   if (FakeCallerBB)
1690     MF.deleteMachineBasicBlock(FakeCallerBB);
1691   AppendixBB = FakeCallerBB = nullptr;
1692 }
1693 
releaseMemory()1694 void WebAssemblyCFGStackify::releaseMemory() {
1695   ScopeTops.clear();
1696   BeginToEnd.clear();
1697   EndToBegin.clear();
1698   TryToEHPad.clear();
1699   EHPadToTry.clear();
1700 }
1701 
runOnMachineFunction(MachineFunction & MF)1702 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
1703   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
1704                        "********** Function: "
1705                     << MF.getName() << '\n');
1706   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1707 
1708   releaseMemory();
1709 
1710   // Liveness is not tracked for VALUE_STACK physreg.
1711   MF.getRegInfo().invalidateLiveness();
1712 
1713   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
1714   placeMarkers(MF);
1715 
1716   // Remove unnecessary instructions possibly introduced by try/end_trys.
1717   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1718       MF.getFunction().hasPersonalityFn())
1719     removeUnnecessaryInstrs(MF);
1720 
1721   // Convert MBB operands in terminators to relative depth immediates.
1722   rewriteDepthImmediates(MF);
1723 
1724   // Fix up block/loop/try signatures at the end of the function to conform to
1725   // WebAssembly's rules.
1726   fixEndsAtEndOfFunction(MF);
1727 
1728   // Add an end instruction at the end of the function body.
1729   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1730   if (!MF.getSubtarget<WebAssemblySubtarget>()
1731            .getTargetTriple()
1732            .isOSBinFormatELF())
1733     appendEndToFunction(MF, TII);
1734 
1735   cleanupFunctionData(MF);
1736 
1737   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1738   return true;
1739 }
1740