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 "MCTargetDesc/WebAssemblyMCTargetDesc.h"
25 #include "WebAssembly.h"
26 #include "WebAssemblyExceptionInfo.h"
27 #include "WebAssemblyMachineFunctionInfo.h"
28 #include "WebAssemblySubtarget.h"
29 #include "WebAssemblyUtilities.h"
30 #include "llvm/CodeGen/MachineDominators.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/CodeGen/WasmEHFuncInfo.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <cstring>
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "wasm-cfg-stackify"
44 
45 namespace {
46 class WebAssemblyCFGStackify final : public MachineFunctionPass {
47   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
48 
49   void getAnalysisUsage(AnalysisUsage &AU) const override {
50     AU.addRequired<MachineDominatorTree>();
51     AU.addRequired<MachineLoopInfo>();
52     AU.addRequired<WebAssemblyExceptionInfo>();
53     MachineFunctionPass::getAnalysisUsage(AU);
54   }
55 
56   bool runOnMachineFunction(MachineFunction &MF) override;
57 
58   // For each block whose label represents the end of a scope, record the block
59   // which holds the beginning of the scope. This will allow us to quickly skip
60   // over scoped regions when walking blocks.
61   SmallVector<MachineBasicBlock *, 8> ScopeTops;
62 
63   void placeMarkers(MachineFunction &MF);
64   void placeBlockMarker(MachineBasicBlock &MBB);
65   void placeLoopMarker(MachineBasicBlock &MBB);
66   void placeTryMarker(MachineBasicBlock &MBB);
67   void removeUnnecessaryInstrs(MachineFunction &MF);
68   void rewriteDepthImmediates(MachineFunction &MF);
69   void fixEndsAtEndOfFunction(MachineFunction &MF);
70 
71   // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY).
72   DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
73   // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY.
74   DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
75   // <TRY marker, EH pad> map
76   DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
77   // <EH pad, TRY marker> map
78   DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
79 
80   // Helper functions to register / unregister scope information created by
81   // marker instructions.
82   void registerScope(MachineInstr *Begin, MachineInstr *End);
83   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
84                         MachineBasicBlock *EHPad);
85   void unregisterScope(MachineInstr *Begin);
86 
87 public:
88   static char ID; // Pass identification, replacement for typeid
89   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
90   ~WebAssemblyCFGStackify() override { releaseMemory(); }
91   void releaseMemory() override;
92 };
93 } // end anonymous namespace
94 
95 char WebAssemblyCFGStackify::ID = 0;
96 INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
97                 "Insert BLOCK and LOOP markers for WebAssembly scopes", false,
98                 false)
99 
100 FunctionPass *llvm::createWebAssemblyCFGStackify() {
101   return new WebAssemblyCFGStackify();
102 }
103 
104 /// Test whether Pred has any terminators explicitly branching to MBB, as
105 /// opposed to falling through. Note that it's possible (eg. in unoptimized
106 /// code) for a branch instruction to both branch to a block and fallthrough
107 /// to it, so we check the actual branch operands to see if there are any
108 /// explicit mentions.
109 static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
110                                  MachineBasicBlock *MBB) {
111   for (MachineInstr &MI : Pred->terminators())
112     for (MachineOperand &MO : MI.explicit_operands())
113       if (MO.isMBB() && MO.getMBB() == MBB)
114         return true;
115   return false;
116 }
117 
118 // Returns an iterator to the earliest position possible within the MBB,
119 // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
120 // contains instructions that should go before the marker, and AfterSet contains
121 // ones that should go after the marker. In this function, AfterSet is only
122 // used for sanity checking.
123 static MachineBasicBlock::iterator
124 getEarliestInsertPos(MachineBasicBlock *MBB,
125                      const SmallPtrSet<const MachineInstr *, 4> &BeforeSet,
126                      const SmallPtrSet<const MachineInstr *, 4> &AfterSet) {
127   auto InsertPos = MBB->end();
128   while (InsertPos != MBB->begin()) {
129     if (BeforeSet.count(&*std::prev(InsertPos))) {
130 #ifndef NDEBUG
131       // Sanity check
132       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
133         assert(!AfterSet.count(&*std::prev(Pos)));
134 #endif
135       break;
136     }
137     --InsertPos;
138   }
139   return InsertPos;
140 }
141 
142 // Returns an iterator to the latest position possible within the MBB,
143 // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
144 // contains instructions that should go before the marker, and AfterSet contains
145 // ones that should go after the marker. In this function, BeforeSet is only
146 // used for sanity checking.
147 static MachineBasicBlock::iterator
148 getLatestInsertPos(MachineBasicBlock *MBB,
149                    const SmallPtrSet<const MachineInstr *, 4> &BeforeSet,
150                    const SmallPtrSet<const MachineInstr *, 4> &AfterSet) {
151   auto InsertPos = MBB->begin();
152   while (InsertPos != MBB->end()) {
153     if (AfterSet.count(&*InsertPos)) {
154 #ifndef NDEBUG
155       // Sanity check
156       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
157         assert(!BeforeSet.count(&*Pos));
158 #endif
159       break;
160     }
161     ++InsertPos;
162   }
163   return InsertPos;
164 }
165 
166 void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
167                                            MachineInstr *End) {
168   BeginToEnd[Begin] = End;
169   EndToBegin[End] = Begin;
170 }
171 
172 void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
173                                               MachineInstr *End,
174                                               MachineBasicBlock *EHPad) {
175   registerScope(Begin, End);
176   TryToEHPad[Begin] = EHPad;
177   EHPadToTry[EHPad] = Begin;
178 }
179 
180 void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
181   assert(BeginToEnd.count(Begin));
182   MachineInstr *End = BeginToEnd[Begin];
183   assert(EndToBegin.count(End));
184   BeginToEnd.erase(Begin);
185   EndToBegin.erase(End);
186   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
187   if (EHPad) {
188     assert(EHPadToTry.count(EHPad));
189     TryToEHPad.erase(Begin);
190     EHPadToTry.erase(EHPad);
191   }
192 }
193 
194 /// Insert a BLOCK marker for branches to MBB (if needed).
195 void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
196   assert(!MBB.isEHPad());
197   MachineFunction &MF = *MBB.getParent();
198   auto &MDT = getAnalysis<MachineDominatorTree>();
199   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
200   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
201 
202   // First compute the nearest common dominator of all forward non-fallthrough
203   // predecessors so that we minimize the time that the BLOCK is on the stack,
204   // which reduces overall stack height.
205   MachineBasicBlock *Header = nullptr;
206   bool IsBranchedTo = false;
207   bool IsBrOnExn = false;
208   MachineInstr *BrOnExn = nullptr;
209   int MBBNumber = MBB.getNumber();
210   for (MachineBasicBlock *Pred : MBB.predecessors()) {
211     if (Pred->getNumber() < MBBNumber) {
212       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
213       if (explicitlyBranchesTo(Pred, &MBB)) {
214         IsBranchedTo = true;
215         if (Pred->getFirstTerminator()->getOpcode() == WebAssembly::BR_ON_EXN) {
216           IsBrOnExn = true;
217           assert(!BrOnExn && "There should be only one br_on_exn per block");
218           BrOnExn = &*Pred->getFirstTerminator();
219         }
220       }
221     }
222   }
223   if (!Header)
224     return;
225   if (!IsBranchedTo)
226     return;
227 
228   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
229   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
230 
231   // If the nearest common dominator is inside a more deeply nested context,
232   // walk out to the nearest scope which isn't more deeply nested.
233   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
234     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
235       if (ScopeTop->getNumber() > Header->getNumber()) {
236         // Skip over an intervening scope.
237         I = std::next(ScopeTop->getIterator());
238       } else {
239         // We found a scope level at an appropriate depth.
240         Header = ScopeTop;
241         break;
242       }
243     }
244   }
245 
246   // Decide where in Header to put the BLOCK.
247 
248   // Instructions that should go before the BLOCK.
249   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
250   // Instructions that should go after the BLOCK.
251   SmallPtrSet<const MachineInstr *, 4> AfterSet;
252   for (const auto &MI : *Header) {
253     // If there is a previously placed LOOP marker and the bottom block of the
254     // loop is above MBB, it should be after the BLOCK, because the loop is
255     // nested in this BLOCK. Otherwise it should be before the BLOCK.
256     if (MI.getOpcode() == WebAssembly::LOOP) {
257       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
258       if (MBB.getNumber() > LoopBottom->getNumber())
259         AfterSet.insert(&MI);
260 #ifndef NDEBUG
261       else
262         BeforeSet.insert(&MI);
263 #endif
264     }
265 
266     // All previously inserted BLOCK/TRY markers should be after the BLOCK
267     // because they are all nested blocks.
268     if (MI.getOpcode() == WebAssembly::BLOCK ||
269         MI.getOpcode() == WebAssembly::TRY)
270       AfterSet.insert(&MI);
271 
272 #ifndef NDEBUG
273     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
274     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
275         MI.getOpcode() == WebAssembly::END_LOOP ||
276         MI.getOpcode() == WebAssembly::END_TRY)
277       BeforeSet.insert(&MI);
278 #endif
279 
280     // Terminators should go after the BLOCK.
281     if (MI.isTerminator())
282       AfterSet.insert(&MI);
283   }
284 
285   // Local expression tree should go after the BLOCK.
286   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
287        --I) {
288     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
289       continue;
290     if (WebAssembly::isChild(*std::prev(I), MFI))
291       AfterSet.insert(&*std::prev(I));
292     else
293       break;
294   }
295 
296   // Add the BLOCK.
297 
298   // 'br_on_exn' extracts except_ref object and pushes variable number of values
299   // depending on its tag. For C++ exception, its a single i32 value, and the
300   // generated code will be in the form of:
301   // block i32
302   //   br_on_exn 0, $__cpp_exception
303   //   rethrow
304   // end_block
305   WebAssembly::ExprType ReturnType = WebAssembly::ExprType::Void;
306   if (IsBrOnExn) {
307     const char *TagName = BrOnExn->getOperand(1).getSymbolName();
308     if (std::strcmp(TagName, "__cpp_exception") != 0)
309       llvm_unreachable("Only C++ exception is supported");
310     ReturnType = WebAssembly::ExprType::I32;
311   }
312 
313   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
314   MachineInstr *Begin =
315       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
316               TII.get(WebAssembly::BLOCK))
317           .addImm(int64_t(ReturnType));
318 
319   // Decide where in Header to put the END_BLOCK.
320   BeforeSet.clear();
321   AfterSet.clear();
322   for (auto &MI : MBB) {
323 #ifndef NDEBUG
324     // END_BLOCK should precede existing LOOP and TRY markers.
325     if (MI.getOpcode() == WebAssembly::LOOP ||
326         MI.getOpcode() == WebAssembly::TRY)
327       AfterSet.insert(&MI);
328 #endif
329 
330     // If there is a previously placed END_LOOP marker and the header of the
331     // loop is above this block's header, the END_LOOP should be placed after
332     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
333     // should be placed before the BLOCK. The same for END_TRY.
334     if (MI.getOpcode() == WebAssembly::END_LOOP ||
335         MI.getOpcode() == WebAssembly::END_TRY) {
336       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
337         BeforeSet.insert(&MI);
338 #ifndef NDEBUG
339       else
340         AfterSet.insert(&MI);
341 #endif
342     }
343   }
344 
345   // Mark the end of the block.
346   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
347   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
348                               TII.get(WebAssembly::END_BLOCK));
349   registerScope(Begin, End);
350 
351   // Track the farthest-spanning scope that ends at this point.
352   int Number = MBB.getNumber();
353   if (!ScopeTops[Number] ||
354       ScopeTops[Number]->getNumber() > Header->getNumber())
355     ScopeTops[Number] = Header;
356 }
357 
358 /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
359 void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
360   MachineFunction &MF = *MBB.getParent();
361   const auto &MLI = getAnalysis<MachineLoopInfo>();
362   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
363 
364   MachineLoop *Loop = MLI.getLoopFor(&MBB);
365   if (!Loop || Loop->getHeader() != &MBB)
366     return;
367 
368   // The operand of a LOOP is the first block after the loop. If the loop is the
369   // bottom of the function, insert a dummy block at the end.
370   MachineBasicBlock *Bottom = WebAssembly::getBottom(Loop);
371   auto Iter = std::next(Bottom->getIterator());
372   if (Iter == MF.end()) {
373     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
374     // Give it a fake predecessor so that AsmPrinter prints its label.
375     Label->addSuccessor(Label);
376     MF.push_back(Label);
377     Iter = std::next(Bottom->getIterator());
378   }
379   MachineBasicBlock *AfterLoop = &*Iter;
380 
381   // Decide where in Header to put the LOOP.
382   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
383   SmallPtrSet<const MachineInstr *, 4> AfterSet;
384   for (const auto &MI : MBB) {
385     // LOOP marker should be after any existing loop that ends here. Otherwise
386     // we assume the instruction belongs to the loop.
387     if (MI.getOpcode() == WebAssembly::END_LOOP)
388       BeforeSet.insert(&MI);
389 #ifndef NDEBUG
390     else
391       AfterSet.insert(&MI);
392 #endif
393   }
394 
395   // Mark the beginning of the loop.
396   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
397   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
398                                 TII.get(WebAssembly::LOOP))
399                             .addImm(int64_t(WebAssembly::ExprType::Void));
400 
401   // Decide where in Header to put the END_LOOP.
402   BeforeSet.clear();
403   AfterSet.clear();
404 #ifndef NDEBUG
405   for (const auto &MI : MBB)
406     // Existing END_LOOP markers belong to parent loops of this loop
407     if (MI.getOpcode() == WebAssembly::END_LOOP)
408       AfterSet.insert(&MI);
409 #endif
410 
411   // Mark the end of the loop (using arbitrary debug location that branched to
412   // the loop end as its location).
413   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
414   DebugLoc EndDL = (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
415   MachineInstr *End =
416       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
417   registerScope(Begin, End);
418 
419   assert((!ScopeTops[AfterLoop->getNumber()] ||
420           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
421          "With block sorting the outermost loop for a block should be first.");
422   if (!ScopeTops[AfterLoop->getNumber()])
423     ScopeTops[AfterLoop->getNumber()] = &MBB;
424 }
425 
426 void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
427   assert(MBB.isEHPad());
428   MachineFunction &MF = *MBB.getParent();
429   auto &MDT = getAnalysis<MachineDominatorTree>();
430   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
431   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
432   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
433 
434   // Compute the nearest common dominator of all unwind predecessors
435   MachineBasicBlock *Header = nullptr;
436   int MBBNumber = MBB.getNumber();
437   for (auto *Pred : MBB.predecessors()) {
438     if (Pred->getNumber() < MBBNumber) {
439       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
440       assert(!explicitlyBranchesTo(Pred, &MBB) &&
441              "Explicit branch to an EH pad!");
442     }
443   }
444   if (!Header)
445     return;
446 
447   // If this try is at the bottom of the function, insert a dummy block at the
448   // end.
449   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
450   assert(WE);
451   MachineBasicBlock *Bottom = WebAssembly::getBottom(WE);
452 
453   auto Iter = std::next(Bottom->getIterator());
454   if (Iter == MF.end()) {
455     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
456     // Give it a fake predecessor so that AsmPrinter prints its label.
457     Label->addSuccessor(Label);
458     MF.push_back(Label);
459     Iter = std::next(Bottom->getIterator());
460   }
461   MachineBasicBlock *Cont = &*Iter;
462 
463   assert(Cont != &MF.front());
464   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
465 
466   // If the nearest common dominator is inside a more deeply nested context,
467   // walk out to the nearest scope which isn't more deeply nested.
468   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
469     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
470       if (ScopeTop->getNumber() > Header->getNumber()) {
471         // Skip over an intervening scope.
472         I = std::next(ScopeTop->getIterator());
473       } else {
474         // We found a scope level at an appropriate depth.
475         Header = ScopeTop;
476         break;
477       }
478     }
479   }
480 
481   // Decide where in Header to put the TRY.
482 
483   // Instructions that should go before the TRY.
484   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
485   // Instructions that should go after the TRY.
486   SmallPtrSet<const MachineInstr *, 4> AfterSet;
487   for (const auto &MI : *Header) {
488     // If there is a previously placed LOOP marker and the bottom block of the
489     // loop is above MBB, it should be after the TRY, because the loop is nested
490     // in this TRY. Otherwise it should be before the TRY.
491     if (MI.getOpcode() == WebAssembly::LOOP) {
492       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
493       if (MBB.getNumber() > LoopBottom->getNumber())
494         AfterSet.insert(&MI);
495 #ifndef NDEBUG
496       else
497         BeforeSet.insert(&MI);
498 #endif
499     }
500 
501     // All previously inserted BLOCK/TRY markers should be after the TRY because
502     // they are all nested trys.
503     if (MI.getOpcode() == WebAssembly::BLOCK ||
504         MI.getOpcode() == WebAssembly::TRY)
505       AfterSet.insert(&MI);
506 
507 #ifndef NDEBUG
508     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
509     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
510         MI.getOpcode() == WebAssembly::END_LOOP ||
511         MI.getOpcode() == WebAssembly::END_TRY)
512       BeforeSet.insert(&MI);
513 #endif
514 
515     // Terminators should go after the TRY.
516     if (MI.isTerminator())
517       AfterSet.insert(&MI);
518   }
519 
520   // Local expression tree should go after the TRY.
521   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
522        --I) {
523     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
524       continue;
525     if (WebAssembly::isChild(*std::prev(I), MFI))
526       AfterSet.insert(&*std::prev(I));
527     else
528       break;
529   }
530 
531   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
532   // contain the call within it. So the call should go after the TRY. The
533   // exception is when the header's terminator is a rethrow instruction, in
534   // which case that instruction, not a call instruction before it, is gonna
535   // throw.
536   if (MBB.isPredecessor(Header)) {
537     auto TermPos = Header->getFirstTerminator();
538     if (TermPos == Header->end() ||
539         TermPos->getOpcode() != WebAssembly::RETHROW) {
540       for (const auto &MI : reverse(*Header)) {
541         if (MI.isCall()) {
542           AfterSet.insert(&MI);
543           // Possibly throwing calls are usually wrapped by EH_LABEL
544           // instructions. We don't want to split them and the call.
545           if (MI.getIterator() != Header->begin() &&
546               std::prev(MI.getIterator())->isEHLabel())
547             AfterSet.insert(&*std::prev(MI.getIterator()));
548           break;
549         }
550       }
551     }
552   }
553 
554   // Add the TRY.
555   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
556   MachineInstr *Begin =
557       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
558               TII.get(WebAssembly::TRY))
559           .addImm(int64_t(WebAssembly::ExprType::Void));
560 
561   // Decide where in Header to put the END_TRY.
562   BeforeSet.clear();
563   AfterSet.clear();
564   for (const auto &MI : *Cont) {
565 #ifndef NDEBUG
566     // END_TRY should precede existing LOOP and BLOCK markers.
567     if (MI.getOpcode() == WebAssembly::LOOP ||
568         MI.getOpcode() == WebAssembly::BLOCK)
569       AfterSet.insert(&MI);
570 
571     // All END_TRY markers placed earlier belong to exceptions that contains
572     // this one.
573     if (MI.getOpcode() == WebAssembly::END_TRY)
574       AfterSet.insert(&MI);
575 #endif
576 
577     // If there is a previously placed END_LOOP marker and its header is after
578     // where TRY marker is, this loop is contained within the 'catch' part, so
579     // the END_TRY marker should go after that. Otherwise, the whole try-catch
580     // is contained within this loop, so the END_TRY should go before that.
581     if (MI.getOpcode() == WebAssembly::END_LOOP) {
582       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
583         BeforeSet.insert(&MI);
584 #ifndef NDEBUG
585       else
586         AfterSet.insert(&MI);
587 #endif
588     }
589 
590     // It is not possible for an END_BLOCK to be already in this block.
591   }
592 
593   // Mark the end of the TRY.
594   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
595   MachineInstr *End =
596       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
597               TII.get(WebAssembly::END_TRY));
598   registerTryScope(Begin, End, &MBB);
599 
600   // Track the farthest-spanning scope that ends at this point. We create two
601   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
602   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
603   // markers should not span across 'catch'. For example, this should not
604   // happen:
605   //
606   // try
607   //   block     --|  (X)
608   // catch         |
609   //   end_block --|
610   // end_try
611   for (int Number : {Cont->getNumber(), MBB.getNumber()}) {
612     if (!ScopeTops[Number] ||
613         ScopeTops[Number]->getNumber() > Header->getNumber())
614       ScopeTops[Number] = Header;
615   }
616 }
617 
618 void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
619   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
620 
621   // When there is an unconditional branch right before a catch instruction and
622   // it branches to the end of end_try marker, we don't need the branch, because
623   // it there is no exception, the control flow transfers to that point anyway.
624   // bb0:
625   //   try
626   //     ...
627   //     br bb2      <- Not necessary
628   // bb1:
629   //   catch
630   //     ...
631   // bb2:
632   //   end
633   for (auto &MBB : MF) {
634     if (!MBB.isEHPad())
635       continue;
636 
637     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
638     SmallVector<MachineOperand, 4> Cond;
639     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
640     MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent();
641     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
642     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
643                        (!Cond.empty() && FBB && FBB == Cont)))
644       TII.removeBranch(*EHPadLayoutPred);
645   }
646 
647   // When there are block / end_block markers that overlap with try / end_try
648   // markers, and the block and try markers' return types are the same, the
649   // block /end_block markers are not necessary, because try / end_try markers
650   // also can serve as boundaries for branches.
651   // block         <- Not necessary
652   //   try
653   //     ...
654   //   catch
655   //     ...
656   //   end
657   // end           <- Not necessary
658   SmallVector<MachineInstr *, 32> ToDelete;
659   for (auto &MBB : MF) {
660     for (auto &MI : MBB) {
661       if (MI.getOpcode() != WebAssembly::TRY)
662         continue;
663 
664       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
665       MachineBasicBlock *TryBB = Try->getParent();
666       MachineBasicBlock *Cont = EndTry->getParent();
667       int64_t RetType = Try->getOperand(0).getImm();
668       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
669            B != TryBB->begin() && E != Cont->end() &&
670            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
671            E->getOpcode() == WebAssembly::END_BLOCK &&
672            std::prev(B)->getOperand(0).getImm() == RetType;
673            --B, ++E) {
674         ToDelete.push_back(&*std::prev(B));
675         ToDelete.push_back(&*E);
676       }
677     }
678   }
679   for (auto *MI : ToDelete) {
680     if (MI->getOpcode() == WebAssembly::BLOCK)
681       unregisterScope(MI);
682     MI->eraseFromParent();
683   }
684 }
685 
686 static unsigned
687 getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
688          const MachineBasicBlock *MBB) {
689   unsigned Depth = 0;
690   for (auto X : reverse(Stack)) {
691     if (X == MBB)
692       break;
693     ++Depth;
694   }
695   assert(Depth < Stack.size() && "Branch destination should be in scope");
696   return Depth;
697 }
698 
699 /// In normal assembly languages, when the end of a function is unreachable,
700 /// because the function ends in an infinite loop or a noreturn call or similar,
701 /// it isn't necessary to worry about the function return type at the end of
702 /// the function, because it's never reached. However, in WebAssembly, blocks
703 /// that end at the function end need to have a return type signature that
704 /// matches the function signature, even though it's unreachable. This function
705 /// checks for such cases and fixes up the signatures.
706 void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
707   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
708   assert(MFI.getResults().size() <= 1);
709 
710   if (MFI.getResults().empty())
711     return;
712 
713   WebAssembly::ExprType RetType;
714   switch (MFI.getResults().front().SimpleTy) {
715   case MVT::i32:
716     RetType = WebAssembly::ExprType::I32;
717     break;
718   case MVT::i64:
719     RetType = WebAssembly::ExprType::I64;
720     break;
721   case MVT::f32:
722     RetType = WebAssembly::ExprType::F32;
723     break;
724   case MVT::f64:
725     RetType = WebAssembly::ExprType::F64;
726     break;
727   case MVT::v16i8:
728   case MVT::v8i16:
729   case MVT::v4i32:
730   case MVT::v2i64:
731   case MVT::v4f32:
732   case MVT::v2f64:
733     RetType = WebAssembly::ExprType::V128;
734     break;
735   case MVT::ExceptRef:
736     RetType = WebAssembly::ExprType::ExceptRef;
737     break;
738   default:
739     llvm_unreachable("unexpected return type");
740   }
741 
742   for (MachineBasicBlock &MBB : reverse(MF)) {
743     for (MachineInstr &MI : reverse(MBB)) {
744       if (MI.isPosition() || MI.isDebugInstr())
745         continue;
746       if (MI.getOpcode() == WebAssembly::END_BLOCK) {
747         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
748         continue;
749       }
750       if (MI.getOpcode() == WebAssembly::END_LOOP) {
751         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
752         continue;
753       }
754       // Something other than an `end`. We're done.
755       return;
756     }
757   }
758 }
759 
760 // WebAssembly functions end with an end instruction, as if the function body
761 // were a block.
762 static void appendEndToFunction(MachineFunction &MF,
763                                 const WebAssemblyInstrInfo &TII) {
764   BuildMI(MF.back(), MF.back().end(),
765           MF.back().findPrevDebugLoc(MF.back().end()),
766           TII.get(WebAssembly::END_FUNCTION));
767 }
768 
769 /// Insert LOOP/TRY/BLOCK markers at appropriate places.
770 void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
771   // We allocate one more than the number of blocks in the function to
772   // accommodate for the possible fake block we may insert at the end.
773   ScopeTops.resize(MF.getNumBlockIDs() + 1);
774   // Place the LOOP for MBB if MBB is the header of a loop.
775   for (auto &MBB : MF)
776     placeLoopMarker(MBB);
777 
778   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
779   for (auto &MBB : MF) {
780     if (MBB.isEHPad()) {
781       // Place the TRY for MBB if MBB is the EH pad of an exception.
782       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
783           MF.getFunction().hasPersonalityFn())
784         placeTryMarker(MBB);
785     } else {
786       // Place the BLOCK for MBB if MBB is branched to from above.
787       placeBlockMarker(MBB);
788     }
789   }
790 }
791 
792 void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
793   // Now rewrite references to basic blocks to be depth immediates.
794   SmallVector<const MachineBasicBlock *, 8> Stack;
795   for (auto &MBB : reverse(MF)) {
796     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) {
797       MachineInstr &MI = *I;
798       switch (MI.getOpcode()) {
799       case WebAssembly::BLOCK:
800       case WebAssembly::TRY:
801         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <=
802                    MBB.getNumber() &&
803                "Block/try marker should be balanced");
804         Stack.pop_back();
805         break;
806 
807       case WebAssembly::LOOP:
808         assert(Stack.back() == &MBB && "Loop top should be balanced");
809         Stack.pop_back();
810         break;
811 
812       case WebAssembly::END_BLOCK:
813       case WebAssembly::END_TRY:
814         Stack.push_back(&MBB);
815         break;
816 
817       case WebAssembly::END_LOOP:
818         Stack.push_back(EndToBegin[&MI]->getParent());
819         break;
820 
821       default:
822         if (MI.isTerminator()) {
823           // Rewrite MBB operands to be depth immediates.
824           SmallVector<MachineOperand, 4> Ops(MI.operands());
825           while (MI.getNumOperands() > 0)
826             MI.RemoveOperand(MI.getNumOperands() - 1);
827           for (auto MO : Ops) {
828             if (MO.isMBB())
829               MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB()));
830             MI.addOperand(MF, MO);
831           }
832         }
833         break;
834       }
835     }
836   }
837   assert(Stack.empty() && "Control flow should be balanced");
838 }
839 
840 void WebAssemblyCFGStackify::releaseMemory() {
841   ScopeTops.clear();
842   BeginToEnd.clear();
843   EndToBegin.clear();
844   TryToEHPad.clear();
845   EHPadToTry.clear();
846 }
847 
848 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
849   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
850                        "********** Function: "
851                     << MF.getName() << '\n');
852   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
853 
854   releaseMemory();
855 
856   // Liveness is not tracked for VALUE_STACK physreg.
857   MF.getRegInfo().invalidateLiveness();
858 
859   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
860   placeMarkers(MF);
861 
862   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
863       MF.getFunction().hasPersonalityFn())
864     // Remove unnecessary instructions.
865     removeUnnecessaryInstrs(MF);
866 
867   // Convert MBB operands in terminators to relative depth immediates.
868   rewriteDepthImmediates(MF);
869 
870   // Fix up block/loop/try signatures at the end of the function to conform to
871   // WebAssembly's rules.
872   fixEndsAtEndOfFunction(MF);
873 
874   // Add an end instruction at the end of the function body.
875   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
876   if (!MF.getSubtarget<WebAssemblySubtarget>()
877            .getTargetTriple()
878            .isOSBinFormatELF())
879     appendEndToFunction(MF, TII);
880 
881   return true;
882 }
883