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