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