LLVM 24.0.0git
WebAssemblyLateEHPrepare.cpp
Go to the documentation of this file.
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 "WebAssembly.h"
17#include "llvm/ADT/MapVector.h"
23#include "llvm/IR/Analysis.h"
24#include "llvm/IR/Module.h"
25#include "llvm/Support/Debug.h"
26using namespace llvm;
27
28#define DEBUG_TYPE "wasm-late-eh-prepare"
29
30namespace {
31class WebAssemblyLateEHPrepareImpl {
32 const WebAssemblyOptions &CLOpts;
33
34 bool removeUnreachableEHPads(MachineFunction &MF);
35 void recordCatchRetBBs(MachineFunction &MF);
36 bool hoistCatches(MachineFunction &MF);
37 bool addCatchAlls(MachineFunction &MF);
38 bool addCatchRefsAndThrowRefs(MachineFunction &MF);
39 bool replaceFuncletReturns(MachineFunction &MF);
40 bool removeUnnecessaryUnreachables(MachineFunction &MF);
41 bool restoreStackPointer(MachineFunction &MF);
42
43 MachineBasicBlock *getMatchingEHPad(MachineInstr *MI);
45
46public:
47 explicit WebAssemblyLateEHPrepareImpl(const WebAssemblyOptions &CLOpts)
48 : CLOpts(CLOpts) {}
49 bool runOnMachineFunction(MachineFunction &MF);
50};
51
52class WebAssemblyLateEHPrepareLegacy final : public MachineFunctionPass {
53 StringRef getPassName() const override {
54 return "WebAssembly Late Prepare Exception";
55 }
56
57 bool runOnMachineFunction(MachineFunction &MF) override;
58
59public:
60 static char ID; // Pass identification, replacement for typeid
61 WebAssemblyLateEHPrepareLegacy() : MachineFunctionPass(ID) {}
62};
63} // end anonymous namespace
64
65char WebAssemblyLateEHPrepareLegacy::ID = 0;
66INITIALIZE_PASS(WebAssemblyLateEHPrepareLegacy, DEBUG_TYPE,
67 "WebAssembly Late Exception Preparation", false, false)
68
70 return new WebAssemblyLateEHPrepareLegacy();
71}
72
73// Returns the nearest EH pad that dominates this instruction. This does not use
74// dominator analysis; it just does BFS on its predecessors until arriving at an
75// EH pad. This assumes valid EH scopes so the first EH pad it arrives in all
76// possible search paths should be the same.
77// Returns nullptr in case it does not find any EH pad in the search, or finds
78// multiple different EH pads.
80WebAssemblyLateEHPrepareImpl::getMatchingEHPad(MachineInstr *MI) {
81 MachineFunction *MF = MI->getParent()->getParent();
82 SmallVector<MachineBasicBlock *, 2> WL;
83 SmallPtrSet<MachineBasicBlock *, 2> Visited;
84 WL.push_back(MI->getParent());
85 MachineBasicBlock *EHPad = nullptr;
86 while (!WL.empty()) {
87 MachineBasicBlock *MBB = WL.pop_back_val();
88 if (!Visited.insert(MBB).second)
89 continue;
90 if (MBB->isEHPad()) {
91 if (EHPad && EHPad != MBB)
92 return nullptr;
93 EHPad = MBB;
94 continue;
95 }
96 if (MBB == &MF->front())
97 return nullptr;
98 for (auto *Pred : MBB->predecessors())
99 if (!CatchRetBBs.count(Pred)) // We don't go into child scopes
100 WL.push_back(Pred);
101 }
102 return EHPad;
103}
104
105// Erase the specified BBs if the BB does not have any remaining predecessors,
106// and also all its dead children.
107template <typename Container>
108static void eraseDeadBBsAndChildren(const Container &MBBs) {
109 SmallVector<MachineBasicBlock *, 8> WL(MBBs.begin(), MBBs.end());
111 while (!WL.empty()) {
113 if (Deleted.count(MBB) || !MBB->pred_empty())
114 continue;
115 SmallVector<MachineBasicBlock *, 4> Succs(MBB->successors());
116 WL.append(MBB->succ_begin(), MBB->succ_end());
117 for (auto *Succ : Succs)
118 MBB->removeSuccessor(Succ);
119 // To prevent deleting the same BB multiple times, which can happen when
120 // 'MBBs' contain both a parent and a child
121 Deleted.insert(MBB);
122 MBB->eraseFromParent();
123 }
124}
125
126bool WebAssemblyLateEHPrepareImpl::runOnMachineFunction(MachineFunction &MF) {
127 LLVM_DEBUG(dbgs() << "********** Late EH Prepare **********\n"
128 "********** Function: "
129 << MF.getName() << '\n');
130
132 ExceptionHandling::Wasm)
133 return false;
134
135 bool Changed = false;
136 if (MF.getFunction().hasPersonalityFn()) {
137 Changed |= removeUnreachableEHPads(MF);
138 recordCatchRetBBs(MF);
139 Changed |= hoistCatches(MF);
140 Changed |= addCatchAlls(MF);
141 Changed |= replaceFuncletReturns(MF);
142 if (!CLOpts.use_legacy_eh)
143 Changed |= addCatchRefsAndThrowRefs(MF);
144 }
145 Changed |= removeUnnecessaryUnreachables(MF);
146 if (MF.getFunction().hasPersonalityFn())
147 Changed |= restoreStackPointer(MF);
148 return Changed;
149}
150
151// Remove unreachable EH pads and its children. If they remain, CFG
152// stackification can be tricky.
153bool WebAssemblyLateEHPrepareImpl::removeUnreachableEHPads(
154 MachineFunction &MF) {
155 SmallVector<MachineBasicBlock *, 4> ToDelete;
156 for (auto &MBB : MF)
157 if (MBB.isEHPad() && MBB.pred_empty())
158 ToDelete.push_back(&MBB);
159 eraseDeadBBsAndChildren(ToDelete);
160 return !ToDelete.empty();
161}
162
163// Record which BB ends with catchret instruction, because this will be replaced
164// with 'br's later. This set of catchret BBs is necessary in 'getMatchingEHPad'
165// function.
166void WebAssemblyLateEHPrepareImpl::recordCatchRetBBs(MachineFunction &MF) {
167 CatchRetBBs.clear();
168 for (auto &MBB : MF) {
169 auto Pos = MBB.getFirstTerminator();
170 if (Pos == MBB.end())
171 continue;
172 MachineInstr *TI = &*Pos;
173 if (TI->getOpcode() == WebAssembly::CATCHRET)
174 CatchRetBBs.insert(&MBB);
175 }
176}
177
178// Hoist catch instructions to the beginning of their matching EH pad BBs in
179// case,
180// (1) catch instruction is not the first instruction in EH pad.
181// ehpad:
182// some_other_instruction
183// ...
184// %exn = catch 0
185// (2) catch instruction is in a non-EH pad BB. For example,
186// ehpad:
187// br bb0
188// bb0:
189// %exn = catch 0
190bool WebAssemblyLateEHPrepareImpl::hoistCatches(MachineFunction &MF) {
191 bool Changed = false;
193 for (auto &MBB : MF)
194 for (auto &MI : MBB)
195 if (WebAssembly::isCatch(MI.getOpcode()))
196 Catches.push_back(&MI);
197
198 for (auto *Catch : Catches) {
199 MachineBasicBlock *EHPad = getMatchingEHPad(Catch);
200 assert(EHPad && "No matching EH pad for catch");
201 auto InsertPos = EHPad->begin();
202 // Skip EH_LABELs in the beginning of an EH pad if present. We don't use
203 // these labels at the moment, but other targets also seem to have an
204 // EH_LABEL instruction in the beginning of an EH pad.
205 while (InsertPos != EHPad->end() && InsertPos->isEHLabel())
206 InsertPos++;
207 if (InsertPos == Catch)
208 continue;
209 Changed = true;
210 EHPad->insert(InsertPos, Catch->removeFromParent());
211 }
212 return Changed;
213}
214
215// Add catch_all to beginning of cleanup pads.
216bool WebAssemblyLateEHPrepareImpl::addCatchAlls(MachineFunction &MF) {
217 bool Changed = false;
218 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
219
220 for (auto &MBB : MF) {
221 if (!MBB.isEHPad())
222 continue;
223 auto InsertPos = MBB.begin();
224 // Skip EH_LABELs in the beginning of an EH pad if present.
225 while (InsertPos != MBB.end() && InsertPos->isEHLabel())
226 InsertPos++;
227 // This runs after hoistCatches(), so we assume that if there is a catch,
228 // that should be the first non-EH-label instruction in an EH pad.
229 if (InsertPos == MBB.end() ||
230 !WebAssembly::isCatch(InsertPos->getOpcode())) {
231 Changed = true;
232 unsigned CatchAllOpcode = CLOpts.use_legacy_eh
233 ? WebAssembly::CATCH_ALL_LEGACY
234 : WebAssembly::CATCH_ALL;
235 BuildMI(MBB, InsertPos,
236 InsertPos == MBB.end() ? DebugLoc() : InsertPos->getDebugLoc(),
237 TII.get(CatchAllOpcode));
238 }
239 }
240 return Changed;
241}
242
243// Replace pseudo-instructions catchret and cleanupret with br and rethrow
244// respectively.
245bool WebAssemblyLateEHPrepareImpl::replaceFuncletReturns(MachineFunction &MF) {
246 bool Changed = false;
247 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
248
249 for (auto &MBB : MF) {
250 auto Pos = MBB.getFirstTerminator();
251 if (Pos == MBB.end())
252 continue;
253 MachineInstr *TI = &*Pos;
254
255 switch (TI->getOpcode()) {
256 case WebAssembly::CATCHRET: {
257 // Replace a catchret with a branch
258 MachineBasicBlock *TBB = TI->getOperand(0).getMBB();
260 BuildMI(MBB, TI, TI->getDebugLoc(), TII.get(WebAssembly::BR))
261 .addMBB(TBB);
262 TI->eraseFromParent();
263 Changed = true;
264 break;
265 }
266 case WebAssembly::RETHROW:
267 // These RETHROWs here were lowered from llvm.wasm.rethrow() intrinsics,
268 // generated in Clang for when an exception is not caught by the given
269 // type (e.g. catch (int)).
270 //
271 // RETHROW's BB argument is the EH pad where the exception to rethrow has
272 // been caught. (Until this point, RETHROW has just a '0' as a placeholder
273 // argument.) For these llvm.wasm.rethrow()s, we can safely assume the
274 // exception comes from the nearest dominating EH pad, because catch.start
275 // EH pad is structured like this:
276 //
277 // catch.start:
278 // catchpad ...
279 // %matches = compare ehselector with typeid
280 // br i1 %matches, label %catch, label %rethrow
281 //
282 // rethrow:
283 // ;; rethrows the exception caught in 'catch.start'
284 // call @llvm.wasm.rethrow()
285 TI->removeOperand(0);
286 TI->addOperand(MachineOperand::CreateMBB(getMatchingEHPad(TI)));
287 Changed = true;
288 break;
289 case WebAssembly::CLEANUPRET: {
290 // CLEANUPRETs have the EH pad BB the exception to rethrow has been caught
291 // as an argument. Use it and change the instruction opcode to 'RETHROW'
292 // to make rethrowing instructions consistent.
293 //
294 // This is because we cannot safely assume that it is always the nearest
295 // dominating EH pad, in case there are code transformations such as
296 // inlining.
297 BuildMI(MBB, TI, TI->getDebugLoc(), TII.get(WebAssembly::RETHROW))
298 .addMBB(TI->getOperand(0).getMBB());
299 TI->eraseFromParent();
300 Changed = true;
301 break;
302 }
303 }
304 }
305 return Changed;
306}
307
308// Add CATCH_REF and CATCH_ALL_REF pseudo instructions to EH pads, and convert
309// RETHROWs to THROW_REFs.
310bool WebAssemblyLateEHPrepareImpl::addCatchRefsAndThrowRefs(
311 MachineFunction &MF) {
312 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
313 auto &MRI = MF.getRegInfo();
314 MapVector<MachineBasicBlock *, SmallVector<MachineInstr *, 2>>
315 EHPadToRethrows;
316
317 // Create a map of <EH pad, a vector of RETHROWs rethrowing its exception>
318 for (auto &MBB : MF)
319 for (auto &MI : MBB)
320 if (MI.getOpcode() == WebAssembly::RETHROW)
321 EHPadToRethrows[MI.getOperand(0).getMBB()].push_back(&MI);
322 if (EHPadToRethrows.empty())
323 return false;
324
325 // Convert CATCH into CATCH_REF and CATCH_ALL into CATCH_ALL_REF, when the
326 // caught exception is rethrown. And convert RETHROWs to THROW_REFs.
327 for (auto &[EHPad, Rethrows] : EHPadToRethrows) {
328 auto *Catch = WebAssembly::findCatch(EHPad);
329 assert(Catch && "CATCH not found in EHPad");
330 auto InsertPos = std::next(Catch->getIterator());
331 auto ExnReg = MRI.createVirtualRegister(&WebAssembly::EXNREFRegClass);
332 if (Catch->getOpcode() == WebAssembly::CATCH) {
333 MachineInstrBuilder MIB = BuildMI(*EHPad, InsertPos, Catch->getDebugLoc(),
334 TII.get(WebAssembly::CATCH_REF));
335 // Copy defs (= extracted values) from the old CATCH to the new CATCH_REF
336 for (const auto &Def : Catch->defs())
337 MIB.addDef(Def.getReg());
338 MIB.addDef(ExnReg); // Attach the exnref def after extracted values
339 // Copy the tag symbol (The only use operand a CATCH can have is the tag
340 // symbol)
341 for (const auto &Use : Catch->uses()) {
342 MIB.addExternalSymbol(Use.getSymbolName());
343 break;
344 }
345 } else if (Catch->getOpcode() == WebAssembly::CATCH_ALL) {
346 BuildMI(*EHPad, InsertPos, Catch->getDebugLoc(),
347 TII.get(WebAssembly::CATCH_ALL_REF))
348 .addDef(ExnReg);
349 } else {
350 assert(false);
351 }
352 Catch->eraseFromParent();
353
354 for (auto *Rethrow : Rethrows) {
355 auto InsertPos = std::next(Rethrow->getIterator());
356 BuildMI(*Rethrow->getParent(), InsertPos, Rethrow->getDebugLoc(),
357 TII.get(WebAssembly::THROW_REF))
358 .addReg(ExnReg);
359 Rethrow->eraseFromParent();
360 }
361 }
362
363 return true;
364}
365
366// Remove unnecessary unreachables after a throw/rethrow/throw_ref.
367bool WebAssemblyLateEHPrepareImpl::removeUnnecessaryUnreachables(
368 MachineFunction &MF) {
369 bool Changed = false;
370 for (auto &MBB : MF) {
371 for (auto &MI : MBB) {
372 if (MI.getOpcode() != WebAssembly::THROW &&
373 MI.getOpcode() != WebAssembly::RETHROW &&
374 MI.getOpcode() != WebAssembly::THROW_REF)
375 continue;
376 Changed = true;
377
378 // The instruction after the throw should be an unreachable or a branch to
379 // another BB that should eventually lead to an unreachable. Delete it
380 // because throw itself is a terminator, and also delete successors if
381 // any.
382 MBB.erase(std::next(MI.getIterator()), MBB.end());
384 for (auto *Succ : Succs)
385 if (!Succ->isEHPad())
386 MBB.removeSuccessor(Succ);
388 }
389 }
390
391 return Changed;
392}
393
394// After the stack is unwound due to a thrown exception, the __stack_pointer
395// global/__wasm_get_stack_pointer() can point to an invalid address. This
396// inserts instructions that restore the stack pointer state.
397bool WebAssemblyLateEHPrepareImpl::restoreStackPointer(MachineFunction &MF) {
398 const auto *FrameLowering = static_cast<const WebAssemblyFrameLowering *>(
399 MF.getSubtarget().getFrameLowering());
400 if (!FrameLowering->needsPrologForEH(MF))
401 return false;
402 bool Changed = false;
403
404 for (auto &MBB : MF) {
405 if (!MBB.isEHPad())
406 continue;
407 Changed = true;
408
409 // Insert stack pointer restoring instructions at the beginning of each EH
410 // pad, after the catch instruction. Here it is safe to assume that SP32
411 // holds the latest value of the stack pointer, because the only exception
412 // for this case is when a function uses the red zone, but that only happens
413 // with leaf functions, and we don't restore the stack pointer in leaf
414 // functions anyway.
415 auto InsertPos = MBB.begin();
416 // Skip EH_LABELs in the beginning of an EH pad if present.
417 while (InsertPos != MBB.end() && InsertPos->isEHLabel())
418 InsertPos++;
419 assert(InsertPos != MBB.end() &&
420 WebAssembly::isCatch(InsertPos->getOpcode()) &&
421 "catch/catch_all should be present in every EH pad at this point");
422 ++InsertPos; // Skip the catch instruction
423 FrameLowering->writeBackSP(FrameLowering->getSPReg(MF), MF, MBB, InsertPos,
424 MBB.begin()->getDebugLoc());
425 }
426 return Changed;
427}
428
429bool WebAssemblyLateEHPrepareLegacy::runOnMachineFunction(MachineFunction &MF) {
430 WebAssemblyLateEHPrepareImpl Impl(
431 MF.getSubtarget<WebAssemblySubtarget>().getCLOpts());
432 return Impl.runOnMachineFunction(MF);
433}
434
435PreservedAnalyses
438 WebAssemblyLateEHPrepareImpl Impl(
440 return Impl.runOnMachineFunction(MF)
443}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
#define DEBUG_TYPE
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This file implements a map that provides insertion order iteration.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file defines the SmallPtrSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static void eraseDeadBBsAndChildren(const Container &BBs)
This file declares the WebAssembly-specific subclass of TargetSubtarget.
This file contains the declaration of the WebAssembly-specific utility functions.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:899
Module * getParent()
Get the module that this global value is contained inside of...
bool isEHPad() const
Returns true if the block is a landing pad.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineBasicBlock * getMBB() const
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool empty() const
Definition MapVector.h:80
ExceptionHandling getExceptionModel() const
Returns the exception model recorded by the "exception-model" module flag, or the target's default ex...
Definition Module.cpp:744
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const WebAssemblyOptions & getCLOpts() const
Pass manager infrastructure for declaring and invalidating analyses.
MachineInstr * findCatch(MachineBasicBlock *EHPad)
Find a catch instruction from an EH pad.
bool isCatch(unsigned Opc)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
FunctionPass * createWebAssemblyLateEHPrepareLegacyPass()