1 //=== WebAssemblyLateEHPrepare.cpp - WebAssembly Exception Preparation -===//
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 /// \brief Does various transformations for exception handling.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
15 #include "WebAssembly.h"
16 #include "WebAssemblySubtarget.h"
17 #include "WebAssemblyUtilities.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/WasmEHFuncInfo.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Target/TargetMachine.h"
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "wasm-late-eh-prepare"
27 
28 namespace {
29 class WebAssemblyLateEHPrepare final : public MachineFunctionPass {
30   StringRef getPassName() const override {
31     return "WebAssembly Late Prepare Exception";
32   }
33 
34   bool runOnMachineFunction(MachineFunction &MF) override;
35   bool removeUnreachableEHPads(MachineFunction &MF);
36   void recordCatchRetBBs(MachineFunction &MF);
37   bool hoistCatches(MachineFunction &MF);
38   bool addCatchAlls(MachineFunction &MF);
39   bool replaceFuncletReturns(MachineFunction &MF);
40   bool removeUnnecessaryUnreachables(MachineFunction &MF);
41   bool restoreStackPointer(MachineFunction &MF);
42 
43   MachineBasicBlock *getMatchingEHPad(MachineInstr *MI);
44   SmallPtrSet<MachineBasicBlock *, 8> CatchRetBBs;
45 
46 public:
47   static char ID; // Pass identification, replacement for typeid
48   WebAssemblyLateEHPrepare() : MachineFunctionPass(ID) {}
49 };
50 } // end anonymous namespace
51 
52 char WebAssemblyLateEHPrepare::ID = 0;
53 INITIALIZE_PASS(WebAssemblyLateEHPrepare, DEBUG_TYPE,
54                 "WebAssembly Late Exception Preparation", false, false)
55 
56 FunctionPass *llvm::createWebAssemblyLateEHPrepare() {
57   return new WebAssemblyLateEHPrepare();
58 }
59 
60 // Returns the nearest EH pad that dominates this instruction. This does not use
61 // dominator analysis; it just does BFS on its predecessors until arriving at an
62 // EH pad. This assumes valid EH scopes so the first EH pad it arrives in all
63 // possible search paths should be the same.
64 // Returns nullptr in case it does not find any EH pad in the search, or finds
65 // multiple different EH pads.
66 MachineBasicBlock *
67 WebAssemblyLateEHPrepare::getMatchingEHPad(MachineInstr *MI) {
68   MachineFunction *MF = MI->getParent()->getParent();
69   SmallVector<MachineBasicBlock *, 2> WL;
70   SmallPtrSet<MachineBasicBlock *, 2> Visited;
71   WL.push_back(MI->getParent());
72   MachineBasicBlock *EHPad = nullptr;
73   while (!WL.empty()) {
74     MachineBasicBlock *MBB = WL.pop_back_val();
75     if (Visited.count(MBB))
76       continue;
77     Visited.insert(MBB);
78     if (MBB->isEHPad()) {
79       if (EHPad && EHPad != MBB)
80         return nullptr;
81       EHPad = MBB;
82       continue;
83     }
84     if (MBB == &MF->front())
85       return nullptr;
86     for (auto *Pred : MBB->predecessors())
87       if (!CatchRetBBs.count(Pred)) // We don't go into child scopes
88         WL.push_back(Pred);
89   }
90   return EHPad;
91 }
92 
93 // Erase the specified BBs if the BB does not have any remaining predecessors,
94 // and also all its dead children.
95 template <typename Container>
96 static void eraseDeadBBsAndChildren(const Container &MBBs) {
97   SmallVector<MachineBasicBlock *, 8> WL(MBBs.begin(), MBBs.end());
98   SmallPtrSet<MachineBasicBlock *, 8> Deleted;
99   while (!WL.empty()) {
100     MachineBasicBlock *MBB = WL.pop_back_val();
101     if (Deleted.count(MBB) || !MBB->pred_empty())
102       continue;
103     SmallVector<MachineBasicBlock *, 4> Succs(MBB->successors());
104     WL.append(MBB->succ_begin(), MBB->succ_end());
105     for (auto *Succ : Succs)
106       MBB->removeSuccessor(Succ);
107     // To prevent deleting the same BB multiple times, which can happen when
108     // 'MBBs' contain both a parent and a child
109     Deleted.insert(MBB);
110     MBB->eraseFromParent();
111   }
112 }
113 
114 bool WebAssemblyLateEHPrepare::runOnMachineFunction(MachineFunction &MF) {
115   LLVM_DEBUG(dbgs() << "********** Late EH Prepare **********\n"
116                        "********** Function: "
117                     << MF.getName() << '\n');
118 
119   if (MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() !=
120       ExceptionHandling::Wasm)
121     return false;
122 
123   bool Changed = false;
124   if (MF.getFunction().hasPersonalityFn()) {
125     Changed |= removeUnreachableEHPads(MF);
126     recordCatchRetBBs(MF);
127     Changed |= hoistCatches(MF);
128     Changed |= addCatchAlls(MF);
129     Changed |= replaceFuncletReturns(MF);
130   }
131   Changed |= removeUnnecessaryUnreachables(MF);
132   if (MF.getFunction().hasPersonalityFn())
133     Changed |= restoreStackPointer(MF);
134   return Changed;
135 }
136 
137 // Remove unreachable EH pads and its children. If they remain, CFG
138 // stackification can be tricky.
139 bool WebAssemblyLateEHPrepare::removeUnreachableEHPads(MachineFunction &MF) {
140   SmallVector<MachineBasicBlock *, 4> ToDelete;
141   for (auto &MBB : MF)
142     if (MBB.isEHPad() && MBB.pred_empty())
143       ToDelete.push_back(&MBB);
144   eraseDeadBBsAndChildren(ToDelete);
145   return !ToDelete.empty();
146 }
147 
148 // Record which BB ends with catchret instruction, because this will be replaced
149 // with 'br's later. This set of catchret BBs is necessary in 'getMatchingEHPad'
150 // function.
151 void WebAssemblyLateEHPrepare::recordCatchRetBBs(MachineFunction &MF) {
152   CatchRetBBs.clear();
153   for (auto &MBB : MF) {
154     auto Pos = MBB.getFirstTerminator();
155     if (Pos == MBB.end())
156       continue;
157     MachineInstr *TI = &*Pos;
158     if (TI->getOpcode() == WebAssembly::CATCHRET)
159       CatchRetBBs.insert(&MBB);
160   }
161 }
162 
163 // Hoist catch instructions to the beginning of their matching EH pad BBs in
164 // case,
165 // (1) catch instruction is not the first instruction in EH pad.
166 // ehpad:
167 //   some_other_instruction
168 //   ...
169 //   %exn = catch 0
170 // (2) catch instruction is in a non-EH pad BB. For example,
171 // ehpad:
172 //   br bb0
173 // bb0:
174 //   %exn = catch 0
175 bool WebAssemblyLateEHPrepare::hoistCatches(MachineFunction &MF) {
176   bool Changed = false;
177   SmallVector<MachineInstr *, 16> Catches;
178   for (auto &MBB : MF)
179     for (auto &MI : MBB)
180       if (WebAssembly::isCatch(MI.getOpcode()))
181         Catches.push_back(&MI);
182 
183   for (auto *Catch : Catches) {
184     MachineBasicBlock *EHPad = getMatchingEHPad(Catch);
185     assert(EHPad && "No matching EH pad for catch");
186     auto InsertPos = EHPad->begin();
187     // Skip EH_LABELs in the beginning of an EH pad if present. We don't use
188     // these labels at the moment, but other targets also seem to have an
189     // EH_LABEL instruction in the beginning of an EH pad.
190     while (InsertPos != EHPad->end() && InsertPos->isEHLabel())
191       InsertPos++;
192     if (InsertPos == Catch)
193       continue;
194     Changed = true;
195     EHPad->insert(InsertPos, Catch->removeFromParent());
196   }
197   return Changed;
198 }
199 
200 // Add catch_all to beginning of cleanup pads.
201 bool WebAssemblyLateEHPrepare::addCatchAlls(MachineFunction &MF) {
202   bool Changed = false;
203   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
204 
205   for (auto &MBB : MF) {
206     if (!MBB.isEHPad())
207       continue;
208     auto InsertPos = MBB.begin();
209     // Skip EH_LABELs in the beginning of an EH pad if present.
210     while (InsertPos != MBB.end() && InsertPos->isEHLabel())
211       InsertPos++;
212     // This runs after hoistCatches(), so we assume that if there is a catch,
213     // that should be the non-EH label first instruction in an EH pad.
214     if (InsertPos == MBB.end() ||
215         !WebAssembly::isCatch(InsertPos->getOpcode())) {
216       Changed = true;
217       BuildMI(MBB, InsertPos, InsertPos->getDebugLoc(),
218               TII.get(WebAssembly::CATCH_ALL));
219     }
220   }
221   return Changed;
222 }
223 
224 // Replace pseudo-instructions catchret and cleanupret with br and rethrow
225 // respectively.
226 bool WebAssemblyLateEHPrepare::replaceFuncletReturns(MachineFunction &MF) {
227   bool Changed = false;
228   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
229 
230   for (auto &MBB : MF) {
231     auto Pos = MBB.getFirstTerminator();
232     if (Pos == MBB.end())
233       continue;
234     MachineInstr *TI = &*Pos;
235 
236     switch (TI->getOpcode()) {
237     case WebAssembly::CATCHRET: {
238       // Replace a catchret with a branch
239       MachineBasicBlock *TBB = TI->getOperand(0).getMBB();
240       if (!MBB.isLayoutSuccessor(TBB))
241         BuildMI(MBB, TI, TI->getDebugLoc(), TII.get(WebAssembly::BR))
242             .addMBB(TBB);
243       TI->eraseFromParent();
244       Changed = true;
245       break;
246     }
247     case WebAssembly::CLEANUPRET: {
248       // Replace a cleanupret with a rethrow. For C++ support, currently
249       // rethrow's immediate argument is always 0 (= the latest exception).
250       BuildMI(MBB, TI, TI->getDebugLoc(), TII.get(WebAssembly::RETHROW))
251           .addImm(0);
252       TI->eraseFromParent();
253       Changed = true;
254       break;
255     }
256     }
257   }
258   return Changed;
259 }
260 
261 // Remove unnecessary unreachables after a throw or rethrow.
262 bool WebAssemblyLateEHPrepare::removeUnnecessaryUnreachables(
263     MachineFunction &MF) {
264   bool Changed = false;
265   for (auto &MBB : MF) {
266     for (auto &MI : MBB) {
267       if (MI.getOpcode() != WebAssembly::THROW &&
268           MI.getOpcode() != WebAssembly::RETHROW)
269         continue;
270       Changed = true;
271 
272       // The instruction after the throw should be an unreachable or a branch to
273       // another BB that should eventually lead to an unreachable. Delete it
274       // because throw itself is a terminator, and also delete successors if
275       // any.
276       MBB.erase(std::next(MI.getIterator()), MBB.end());
277       SmallVector<MachineBasicBlock *, 8> Succs(MBB.successors());
278       for (auto *Succ : Succs)
279         if (!Succ->isEHPad())
280           MBB.removeSuccessor(Succ);
281       eraseDeadBBsAndChildren(Succs);
282     }
283   }
284 
285   return Changed;
286 }
287 
288 // After the stack is unwound due to a thrown exception, the __stack_pointer
289 // global can point to an invalid address. This inserts instructions that
290 // restore __stack_pointer global.
291 bool WebAssemblyLateEHPrepare::restoreStackPointer(MachineFunction &MF) {
292   const auto *FrameLowering = static_cast<const WebAssemblyFrameLowering *>(
293       MF.getSubtarget().getFrameLowering());
294   if (!FrameLowering->needsPrologForEH(MF))
295     return false;
296   bool Changed = false;
297 
298   for (auto &MBB : MF) {
299     if (!MBB.isEHPad())
300       continue;
301     Changed = true;
302 
303     // Insert __stack_pointer restoring instructions at the beginning of each EH
304     // pad, after the catch instruction. Here it is safe to assume that SP32
305     // holds the latest value of __stack_pointer, because the only exception for
306     // this case is when a function uses the red zone, but that only happens
307     // with leaf functions, and we don't restore __stack_pointer in leaf
308     // functions anyway.
309     auto InsertPos = MBB.begin();
310     if (InsertPos->isEHLabel()) // EH pad starts with an EH label
311       ++InsertPos;
312     if (WebAssembly::isCatch(InsertPos->getOpcode()))
313       ++InsertPos;
314     FrameLowering->writeSPToGlobal(FrameLowering->getSPReg(MF), MF, MBB,
315                                    InsertPos, MBB.begin()->getDebugLoc());
316   }
317   return Changed;
318 }
319