LLVM 24.0.0git
WebAssemblyCFGStackify.cpp
Go to the documentation of this file.
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, TRY, and TRY_TABLE markers to mark the start
13/// of scopes, since scope boundaries serve as the labels for WebAssembly's
14/// control 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
25#include "WebAssembly.h"
31#include "llvm/ADT/MapVector.h"
32#include "llvm/ADT/Statistic.h"
40#include "llvm/IR/Analysis.h"
41#include "llvm/IR/Module.h"
42using namespace llvm;
44
45#define DEBUG_TYPE "wasm-cfg-stackify"
46
47STATISTIC(NumCallUnwindMismatches, "Number of call unwind mismatches found");
48STATISTIC(NumCatchUnwindMismatches, "Number of catch unwind mismatches found");
49
50namespace {
51class WebAssemblyCFGStackifyImpl {
52 const WebAssemblyOptions &CLOpts;
54 MachineLoopInfo &MLI;
56
57 bool UsesWasmEH = false;
58
59 // For each block whose label represents the end of a scope, record the block
60 // which holds the beginning of the scope. This will allow us to quickly skip
61 // over scoped regions when walking blocks.
63 void updateScopeTops(MachineBasicBlock *Begin, MachineBasicBlock *End) {
64 int BeginNo = Begin->getNumber();
65 int EndNo = End->getNumber();
66 if (!ScopeTops[EndNo] || ScopeTops[EndNo]->getNumber() > BeginNo)
67 ScopeTops[EndNo] = Begin;
68 }
69
70 // Placing markers.
71 void placeMarkers(MachineFunction &MF);
72 void placeBlockMarker(MachineBasicBlock &MBB);
73 void placeLoopMarker(MachineBasicBlock &MBB);
74 void placeTryMarker(MachineBasicBlock &MBB);
75 void placeTryTableMarker(MachineBasicBlock &MBB);
76
77 // Unwind mismatch fixing for exception handling
78 // - Common functions
79 bool fixCallUnwindMismatches(MachineFunction &MF);
80 bool fixCatchUnwindMismatches(MachineFunction &MF);
81 void recalculateScopeTops(MachineFunction &MF);
82 // - Legacy EH
83 void addNestedTryDelegate(MachineInstr *RangeBegin, MachineInstr *RangeEnd,
84 MachineBasicBlock *UnwindDest);
85 void removeUnnecessaryInstrs(MachineFunction &MF);
86 // - Standard EH (exnref)
87 void addNestedTryTable(MachineInstr *RangeBegin, MachineInstr *RangeEnd,
88 MachineBasicBlock *UnwindDest);
89 MachineBasicBlock *getTrampolineBlock(MachineBasicBlock *UnwindDest);
90
91 // Wrap-up
92 using EndMarkerInfo =
93 std::pair<const MachineBasicBlock *, const MachineInstr *>;
94 unsigned getBranchDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
95 const MachineBasicBlock *MBB);
96 unsigned getDelegateDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
97 const MachineBasicBlock *MBB);
98 unsigned getRethrowDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
99 const MachineBasicBlock *EHPadToRethrow);
100 void rewriteDepthImmediates(MachineFunction &MF);
101 void fixEndsAtEndOfFunction(MachineFunction &MF);
102 void cleanupFunctionData(MachineFunction &MF);
103
104 // For each BLOCK|LOOP|TRY|TRY_TABLE, the corresponding
105 // END_(BLOCK|LOOP|TRY|TRY_TABLE) or DELEGATE (in case of TRY).
106 DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
107 // For each END_(BLOCK|LOOP|TRY|TRY_TABLE) or DELEGATE, the corresponding
108 // BLOCK|LOOP|TRY|TRY_TABLE.
109 DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
110 // <TRY marker, EH pad> map
111 DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
112 // <EH pad, TRY marker> map
113 DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
114
115 DenseMap<const MachineBasicBlock *, MachineBasicBlock *>
116 UnwindDestToTrampoline;
117
118 // We need an appendix block to place 'end_loop' or 'end_try' marker when the
119 // loop / exception bottom block is the last block in a function
120 MachineBasicBlock *AppendixBB = nullptr;
121 MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
122 if (!AppendixBB) {
123 AppendixBB = MF.CreateMachineBasicBlock();
124 // Give it a fake predecessor so that AsmPrinter prints its label.
125 AppendixBB->addSuccessor(AppendixBB);
126 // If the caller trampoline BB exists, insert the appendix BB before it.
127 // Otherwise insert it at the end of the function.
128 if (CallerTrampolineBB)
129 MF.insert(CallerTrampolineBB->getIterator(), AppendixBB);
130 else
131 MF.push_back(AppendixBB);
132 }
133 return AppendixBB;
134 }
135
136 // Create a caller-dedicated trampoline BB to be used for fixing unwind
137 // mismatches where the unwind destination is the caller.
138 MachineBasicBlock *CallerTrampolineBB = nullptr;
139 MachineBasicBlock *getCallerTrampolineBlock(MachineFunction &MF) {
140 if (!CallerTrampolineBB) {
141 CallerTrampolineBB = MF.CreateMachineBasicBlock();
142 MF.push_back(CallerTrampolineBB);
143 }
144 return CallerTrampolineBB;
145 }
146
147 // Before running rewriteDepthImmediates function, 'delegate' has a BB as its
148 // destination operand. getFakeCallerBlock() returns a fake BB that will be
149 // used for the operand when 'delegate' needs to rethrow to the caller. This
150 // will be rewritten as an immediate value that is the number of block depths
151 // + 1 in rewriteDepthImmediates, and this fake BB will be removed at the end
152 // of the pass.
153 MachineBasicBlock *FakeCallerBB = nullptr;
154 MachineBasicBlock *getFakeCallerBlock(MachineFunction &MF) {
155 if (!FakeCallerBB)
156 FakeCallerBB = MF.CreateMachineBasicBlock();
157 return FakeCallerBB;
158 }
159
160 // Helper functions to register / unregister scope information created by
161 // marker instructions.
162 void registerScope(MachineInstr *Begin, MachineInstr *End);
163 void registerTryScope(MachineInstr *Begin, MachineInstr *End,
164 MachineBasicBlock *EHPad);
165 void unregisterScope(MachineInstr *Begin);
166
167public:
168 WebAssemblyCFGStackifyImpl(const WebAssemblyOptions &CLOpts,
169 MachineDominatorTree &MDT, MachineLoopInfo &MLI,
170 WebAssemblyExceptionInfo &WEI)
171 : CLOpts(CLOpts), MDT(MDT), MLI(MLI), WEI(WEI) {}
172
173 bool runOnMachineFunction(MachineFunction &MF);
174};
175
176class WebAssemblyCFGStackifyLegacy : public MachineFunctionPass {
177 StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
178
179 void getAnalysisUsage(AnalysisUsage &AU) const override {
180 AU.addRequired<MachineDominatorTreeWrapperPass>();
181 AU.addRequired<MachineLoopInfoWrapperPass>();
182 AU.addRequired<WebAssemblyExceptionInfoWrapperPass>();
184 }
185
186public:
187 bool runOnMachineFunction(MachineFunction &MF) override;
188 static char ID; // Pass identification, replacement for typeid
189 WebAssemblyCFGStackifyLegacy() : MachineFunctionPass(ID) {}
190};
191} // end anonymous namespace
192
193char WebAssemblyCFGStackifyLegacy::ID = 0;
195 WebAssemblyCFGStackifyLegacy, DEBUG_TYPE,
196 "Insert BLOCK/LOOP/TRY/TRY_TABLE markers for WebAssembly scopes", false,
197 false)
198
200 return new WebAssemblyCFGStackifyLegacy();
201}
202
203/// Test whether Pred has any terminators explicitly branching to MBB, as
204/// opposed to falling through. Note that it's possible (eg. in unoptimized
205/// code) for a branch instruction to both branch to a block and fallthrough
206/// to it, so we check the actual branch operands to see if there are any
207/// explicit mentions.
210 for (MachineInstr &MI : Pred->terminators())
211 for (MachineOperand &MO : MI.explicit_operands())
212 if (MO.isMBB() && MO.getMBB() == MBB)
213 return true;
214 return false;
215}
216
217// Returns an iterator to the earliest position possible within the MBB,
218// satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
219// contains instructions that should go before the marker, and AfterSet contains
220// ones that should go after the marker. In this function, AfterSet is only
221// used for validation checking.
222template <typename Container>
224getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
225 const Container &AfterSet) {
226 auto InsertPos = MBB->end();
227 while (InsertPos != MBB->begin()) {
228 if (BeforeSet.count(&*std::prev(InsertPos))) {
229#ifndef NDEBUG
230 // Validation check
231 for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
232 assert(!AfterSet.count(&*std::prev(Pos)));
233#endif
234 break;
235 }
236 --InsertPos;
237 }
238 return InsertPos;
239}
240
241// Returns an iterator to the latest position possible within the MBB,
242// satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
243// contains instructions that should go before the marker, and AfterSet contains
244// ones that should go after the marker. In this function, BeforeSet is only
245// used for validation checking.
246template <typename Container>
248getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
249 const Container &AfterSet) {
250 auto InsertPos = MBB->begin();
251 while (InsertPos != MBB->end()) {
252 if (AfterSet.count(&*InsertPos)) {
253#ifndef NDEBUG
254 // Validation check
255 for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
256 assert(!BeforeSet.count(&*Pos));
257#endif
258 break;
259 }
260 ++InsertPos;
261 }
262 return InsertPos;
263}
264
265void WebAssemblyCFGStackifyImpl::registerScope(MachineInstr *Begin,
266 MachineInstr *End) {
267 BeginToEnd[Begin] = End;
268 EndToBegin[End] = Begin;
269}
270
271// When 'End' is not an 'end_try' but a 'delegate', EHPad is nullptr.
272void WebAssemblyCFGStackifyImpl::registerTryScope(MachineInstr *Begin,
273 MachineInstr *End,
274 MachineBasicBlock *EHPad) {
275 registerScope(Begin, End);
276 TryToEHPad[Begin] = EHPad;
277 EHPadToTry[EHPad] = Begin;
278}
279
280void WebAssemblyCFGStackifyImpl::unregisterScope(MachineInstr *Begin) {
281 assert(BeginToEnd.count(Begin));
282 MachineInstr *End = BeginToEnd[Begin];
283 assert(EndToBegin.count(End));
284 BeginToEnd.erase(Begin);
285 EndToBegin.erase(End);
286 MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
287 if (EHPad) {
288 assert(EHPadToTry.count(EHPad));
289 TryToEHPad.erase(Begin);
290 EHPadToTry.erase(EHPad);
291 }
292}
293
294/// Insert a BLOCK marker for branches to MBB (if needed).
295// TODO Consider a more generalized way of handling block (and also loop and
296// try) signatures when we implement the multi-value proposal later.
297void WebAssemblyCFGStackifyImpl::placeBlockMarker(MachineBasicBlock &MBB) {
298 assert(!MBB.isEHPad());
300 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
301 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
302
303 // First compute the nearest common dominator of all forward non-fallthrough
304 // predecessors so that we minimize the time that the BLOCK is on the stack,
305 // which reduces overall stack height.
306 MachineBasicBlock *Header = nullptr;
307 bool IsBranchedTo = false;
308 int MBBNumber = MBB.getNumber();
309 for (MachineBasicBlock *Pred : MBB.predecessors()) {
310 if (Pred->getNumber() < MBBNumber) {
311 Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
313 IsBranchedTo = true;
314 }
315 }
316 if (!Header)
317 return;
318 if (!IsBranchedTo)
319 return;
320
321 assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
322 MachineBasicBlock *LayoutPred = MBB.getPrevNode();
323
324 // If the nearest common dominator is inside a more deeply nested context,
325 // walk out to the nearest scope which isn't more deeply nested.
326 for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
327 if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
328 if (ScopeTop->getNumber() > Header->getNumber()) {
329 // Skip over an intervening scope.
330 I = std::next(ScopeTop->getIterator());
331 } else {
332 // We found a scope level at an appropriate depth.
333 Header = ScopeTop;
334 break;
335 }
336 }
337 }
338
339 // Decide where in MBB to put the BLOCK.
340
341 // Instructions that should go before the BLOCK.
342 SmallPtrSet<const MachineInstr *, 4> BeforeSet;
343 // Instructions that should go after the BLOCK.
344 SmallPtrSet<const MachineInstr *, 4> AfterSet;
345 for (const auto &MI : *Header) {
346 // If there is a previously placed LOOP marker and the bottom block of the
347 // loop is above MBB, it should be after the BLOCK, because the loop is
348 // nested in this BLOCK. Otherwise it should be before the BLOCK.
349 if (MI.getOpcode() == WebAssembly::LOOP) {
350 auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
351 if (MBB.getNumber() > LoopBottom->getNumber())
352 AfterSet.insert(&MI);
353#ifndef NDEBUG
354 else
355 BeforeSet.insert(&MI);
356#endif
357 }
358
359 // If there is a previously placed BLOCK/TRY/TRY_TABLE marker and its
360 // corresponding END marker is before the current BLOCK's END marker, that
361 // should be placed after this BLOCK. Otherwise it should be placed before
362 // this BLOCK marker.
363 if (MI.getOpcode() == WebAssembly::BLOCK ||
364 MI.getOpcode() == WebAssembly::TRY ||
365 MI.getOpcode() == WebAssembly::TRY_TABLE) {
366 if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
367 AfterSet.insert(&MI);
368#ifndef NDEBUG
369 else
370 BeforeSet.insert(&MI);
371#endif
372 }
373
374#ifndef NDEBUG
375 // All END_(BLOCK|LOOP|TRY|TRY_TABLE) markers should be before the BLOCK.
376 if (MI.getOpcode() == WebAssembly::END_BLOCK ||
377 MI.getOpcode() == WebAssembly::END_LOOP ||
378 MI.getOpcode() == WebAssembly::END_TRY ||
379 MI.getOpcode() == WebAssembly::END_TRY_TABLE)
380 BeforeSet.insert(&MI);
381#endif
382
383 // Terminators should go after the BLOCK.
384 if (MI.isTerminator())
385 AfterSet.insert(&MI);
386 }
387
388 // Local expression tree should go after the BLOCK.
389 for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
390 --I) {
391 if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
392 continue;
393 if (WebAssembly::isChild(*std::prev(I), MFI))
394 AfterSet.insert(&*std::prev(I));
395 else
396 break;
397 }
398
399 // Add the BLOCK.
400 WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
401 auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
402 MachineInstr *Begin =
403 BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
404 TII.get(WebAssembly::BLOCK))
405 .addImm(int64_t(ReturnType));
406
407 // Decide where in MBB to put the END_BLOCK.
408 BeforeSet.clear();
409 AfterSet.clear();
410 for (auto &MI : MBB) {
411#ifndef NDEBUG
412 // END_BLOCK should precede existing LOOP markers.
413 if (MI.getOpcode() == WebAssembly::LOOP)
414 AfterSet.insert(&MI);
415#endif
416
417 // If there is a previously placed END_LOOP marker and the header of the
418 // loop is above this block's header, the END_LOOP should be placed after
419 // the END_BLOCK, because the loop contains this block. Otherwise the
420 // END_LOOP should be placed before the END_BLOCK. The same for END_TRY.
421 //
422 // Note that while there can be existing END_TRYs, there can't be
423 // END_TRY_TABLEs; END_TRYs are placed when its corresponding EH pad is
424 // processed, so they are placed below MBB (EH pad) in placeTryMarker. But
425 // END_TRY_TABLE is placed like a END_BLOCK, so they can't be here already.
426 if (MI.getOpcode() == WebAssembly::END_LOOP ||
427 MI.getOpcode() == WebAssembly::END_TRY) {
428 if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
429 BeforeSet.insert(&MI);
430#ifndef NDEBUG
431 else
432 AfterSet.insert(&MI);
433#endif
434 }
435 }
436
437 // Mark the end of the block.
438 InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
439 MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
440 TII.get(WebAssembly::END_BLOCK));
441 registerScope(Begin, End);
442
443 // Track the farthest-spanning scope that ends at this point.
444 updateScopeTops(Header, &MBB);
445}
446
447/// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
448void WebAssemblyCFGStackifyImpl::placeLoopMarker(MachineBasicBlock &MBB) {
450 SortRegionInfo SRI(MLI, WEI);
451 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
452
453 MachineLoop *Loop = MLI.getLoopFor(&MBB);
454 if (!Loop || Loop->getHeader() != &MBB)
455 return;
456
457 // The operand of a LOOP is the first block after the loop. If the loop is the
458 // bottom of the function, insert a dummy block at the end.
459 MachineBasicBlock *Bottom = SRI.getBottom(Loop);
460 auto Iter = std::next(Bottom->getIterator());
461 if (Iter == MF.end()) {
462 getAppendixBlock(MF);
463 Iter = std::next(Bottom->getIterator());
464 }
465 MachineBasicBlock *AfterLoop = &*Iter;
466
467 // Decide where in Header to put the LOOP.
468 SmallPtrSet<const MachineInstr *, 4> BeforeSet;
469 SmallPtrSet<const MachineInstr *, 4> AfterSet;
470 for (const auto &MI : MBB) {
471 // LOOP marker should be after any existing loop that ends here. Otherwise
472 // we assume the instruction belongs to the loop.
473 if (MI.getOpcode() == WebAssembly::END_LOOP)
474 BeforeSet.insert(&MI);
475#ifndef NDEBUG
476 else
477 AfterSet.insert(&MI);
478#endif
479 }
480
481 // Mark the beginning of the loop.
482 auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
483 MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
484 TII.get(WebAssembly::LOOP))
485 .addImm(int64_t(WebAssembly::BlockType::Void));
486
487 // Decide where in MBB to put the END_LOOP.
488 BeforeSet.clear();
489 AfterSet.clear();
490#ifndef NDEBUG
491 for (const auto &MI : MBB)
492 // Existing END_LOOP markers belong to parent loops of this loop
493 if (MI.getOpcode() == WebAssembly::END_LOOP)
494 AfterSet.insert(&MI);
495#endif
496
497 // Mark the end of the loop (using arbitrary debug location that branched to
498 // the loop end as its location).
499 InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
500 DebugLoc EndDL = AfterLoop->pred_empty()
501 ? DebugLoc()
502 : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
503 MachineInstr *End =
504 BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
505 registerScope(Begin, End);
506
507 assert((!ScopeTops[AfterLoop->getNumber()] ||
508 ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
509 "With block sorting the outermost loop for a block should be first.");
510 updateScopeTops(&MBB, AfterLoop);
511}
512
513void WebAssemblyCFGStackifyImpl::placeTryMarker(MachineBasicBlock &MBB) {
514 assert(MBB.isEHPad());
516 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
517 SortRegionInfo SRI(MLI, WEI);
518 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
519
520 // Compute the nearest common dominator of all unwind predecessors
521 MachineBasicBlock *Header = nullptr;
522 int MBBNumber = MBB.getNumber();
523 for (auto *Pred : MBB.predecessors()) {
524 if (Pred->getNumber() < MBBNumber) {
525 Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
527 "Explicit branch to an EH pad!");
528 }
529 }
530 if (!Header)
531 return;
532
533 // If this try is at the bottom of the function, insert a dummy block at the
534 // end.
535 WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
536 assert(WE);
537 MachineBasicBlock *Bottom = SRI.getBottom(WE);
538 auto Iter = std::next(Bottom->getIterator());
539 if (Iter == MF.end()) {
540 getAppendixBlock(MF);
541 Iter = std::next(Bottom->getIterator());
542 }
543 MachineBasicBlock *Cont = &*Iter;
544
545 // If the nearest common dominator is inside a more deeply nested context,
546 // walk out to the nearest scope which isn't more deeply nested.
547 for (MachineFunction::iterator I(Bottom), E(Header); I != E; --I) {
548 if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
549 if (ScopeTop->getNumber() > Header->getNumber()) {
550 // Skip over an intervening scope.
551 I = std::next(ScopeTop->getIterator());
552 } else {
553 // We found a scope level at an appropriate depth.
554 Header = ScopeTop;
555 break;
556 }
557 }
558 }
559
560 // Decide where in Header to put the TRY.
561
562 // Instructions that should go before the TRY.
563 SmallPtrSet<const MachineInstr *, 4> BeforeSet;
564 // Instructions that should go after the TRY.
565 SmallPtrSet<const MachineInstr *, 4> AfterSet;
566 for (const auto &MI : *Header) {
567 // If there is a previously placed LOOP marker and the bottom block of the
568 // loop is above MBB, it should be after the TRY, because the loop is nested
569 // in this TRY. Otherwise it should be before the TRY.
570 if (MI.getOpcode() == WebAssembly::LOOP) {
571 auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
572 if (MBB.getNumber() > LoopBottom->getNumber())
573 AfterSet.insert(&MI);
574#ifndef NDEBUG
575 else
576 BeforeSet.insert(&MI);
577#endif
578 }
579
580 // All previously inserted BLOCK/TRY markers should be after the TRY because
581 // they are all nested blocks/trys.
582 if (MI.getOpcode() == WebAssembly::BLOCK ||
583 MI.getOpcode() == WebAssembly::TRY)
584 AfterSet.insert(&MI);
585
586#ifndef NDEBUG
587 // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
588 if (MI.getOpcode() == WebAssembly::END_BLOCK ||
589 MI.getOpcode() == WebAssembly::END_LOOP ||
590 MI.getOpcode() == WebAssembly::END_TRY)
591 BeforeSet.insert(&MI);
592#endif
593
594 // Terminators should go after the TRY.
595 if (MI.isTerminator())
596 AfterSet.insert(&MI);
597 }
598
599 // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
600 // contain the call within it. So the call should go after the TRY. The
601 // exception is when the header's terminator is a rethrow instruction, in
602 // which case that instruction, not a call instruction before it, is gonna
603 // throw.
604 MachineInstr *ThrowingCall = nullptr;
605 if (MBB.isPredecessor(Header)) {
606 auto TermPos = Header->getFirstTerminator();
607 if (TermPos == Header->end() ||
608 TermPos->getOpcode() != WebAssembly::RETHROW) {
609 for (auto &MI : reverse(*Header)) {
610 if (MI.isCall()) {
611 AfterSet.insert(&MI);
612 ThrowingCall = &MI;
613 break;
614 }
615 }
616 }
617 }
618
619 // Local expression tree should go after the TRY.
620 // For BLOCK placement, we start the search from the previous instruction of a
621 // BB's terminator, but in TRY's case, we should start from the previous
622 // instruction of a call that can throw, because the return values of the
623 // call's previous instructions can be stackified and consumed by the throwing
624 // call.
625 auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
626 : Header->getFirstTerminator();
627 for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
628 if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
629 continue;
630 if (WebAssembly::isChild(*std::prev(I), MFI))
631 AfterSet.insert(&*std::prev(I));
632 else
633 break;
634 }
635
636 // Add the TRY.
637 auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
638 MachineInstr *Begin =
639 BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
640 TII.get(WebAssembly::TRY))
641 .addImm(int64_t(WebAssembly::BlockType::Void));
642
643 // Decide where in Cont to put the END_TRY.
644 BeforeSet.clear();
645 AfterSet.clear();
646 for (const auto &MI : *Cont) {
647#ifndef NDEBUG
648 // END_TRY should precede existing LOOP markers.
649 if (MI.getOpcode() == WebAssembly::LOOP)
650 AfterSet.insert(&MI);
651
652 // All END_TRY markers placed earlier belong to exceptions that contains
653 // this one.
654 if (MI.getOpcode() == WebAssembly::END_TRY)
655 AfterSet.insert(&MI);
656#endif
657
658 // If there is a previously placed END_LOOP marker and its header is after
659 // where TRY marker is, this loop is contained within the 'catch' part, so
660 // the END_TRY marker should go after that. Otherwise, the whole try-catch
661 // is contained within this loop, so the END_TRY should go before that.
662 if (MI.getOpcode() == WebAssembly::END_LOOP) {
663 // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
664 // are in the same BB, LOOP is always before TRY.
665 if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
666 BeforeSet.insert(&MI);
667#ifndef NDEBUG
668 else
669 AfterSet.insert(&MI);
670#endif
671 }
672
673 // It is not possible for an END_BLOCK to be already in this block.
674 }
675
676 // Mark the end of the TRY.
677 InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
678 MachineInstr *End = BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
679 TII.get(WebAssembly::END_TRY));
680 registerTryScope(Begin, End, &MBB);
681
682 // Track the farthest-spanning scope that ends at this point. We create two
683 // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
684 // with 'try'). We need to create 'catch' -> 'try' mapping here too because
685 // markers should not span across 'catch'. For example, this should not
686 // happen:
687 //
688 // try
689 // block --| (X)
690 // catch |
691 // end_block --|
692 // end_try
693 for (auto *End : {&MBB, Cont})
694 updateScopeTops(Header, End);
695}
696
697void WebAssemblyCFGStackifyImpl::placeTryTableMarker(MachineBasicBlock &MBB) {
698 assert(MBB.isEHPad());
700 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
701 SortRegionInfo SRI(MLI, WEI);
702 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
703
704 // Compute the nearest common dominator of all unwind predecessors
705 MachineBasicBlock *Header = nullptr;
706 int MBBNumber = MBB.getNumber();
707 for (auto *Pred : MBB.predecessors()) {
708 if (Pred->getNumber() < MBBNumber) {
709 Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
711 "Explicit branch to an EH pad!");
712 }
713 }
714 if (!Header)
715 return;
716
717 // Unlike the end_try marker, we don't place an end marker at the end of
718 // exception bottom, i.e., at the end of the old 'catch' block. But we still
719 // consider the try-catch part as a scope when computing ScopeTops.
720 WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
721 assert(WE);
722 MachineBasicBlock *Bottom = SRI.getBottom(WE);
723 auto Iter = std::next(Bottom->getIterator());
724 if (Iter == MF.end())
725 Iter--;
726 MachineBasicBlock *Cont = &*Iter;
727
728 // If the nearest common dominator is inside a more deeply nested context,
729 // walk out to the nearest scope which isn't more deeply nested.
730 for (MachineFunction::iterator I(Bottom), E(Header); I != E; --I) {
731 if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
732 if (ScopeTop->getNumber() > Header->getNumber()) {
733 // Skip over an intervening scope.
734 I = std::next(ScopeTop->getIterator());
735 } else {
736 // We found a scope level at an appropriate depth.
737 Header = ScopeTop;
738 break;
739 }
740 }
741 }
742
743 // Decide where in Header to put the TRY_TABLE.
744
745 // Instructions that should go before the TRY_TABLE.
746 SmallPtrSet<const MachineInstr *, 4> BeforeSet;
747 // Instructions that should go after the TRY_TABLE.
748 SmallPtrSet<const MachineInstr *, 4> AfterSet;
749 for (const auto &MI : *Header) {
750 // If there is a previously placed LOOP marker and the bottom block of the
751 // loop is above MBB, it should be after the TRY_TABLE, because the loop is
752 // nested in this TRY_TABLE. Otherwise it should be before the TRY_TABLE.
753 if (MI.getOpcode() == WebAssembly::LOOP) {
754 auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
755 if (MBB.getNumber() > LoopBottom->getNumber())
756 AfterSet.insert(&MI);
757#ifndef NDEBUG
758 else
759 BeforeSet.insert(&MI);
760#endif
761 }
762
763 // All previously inserted BLOCK/TRY_TABLE markers should be after the
764 // TRY_TABLE because they are all nested blocks/try_tables.
765 if (MI.getOpcode() == WebAssembly::BLOCK ||
766 MI.getOpcode() == WebAssembly::TRY_TABLE)
767 AfterSet.insert(&MI);
768
769#ifndef NDEBUG
770 // All END_(BLOCK/LOOP/TRY_TABLE) markers should be before the TRY_TABLE.
771 if (MI.getOpcode() == WebAssembly::END_BLOCK ||
772 MI.getOpcode() == WebAssembly::END_LOOP ||
773 MI.getOpcode() == WebAssembly::END_TRY_TABLE)
774 BeforeSet.insert(&MI);
775#endif
776
777 // Terminators should go after the TRY_TABLE.
778 if (MI.isTerminator())
779 AfterSet.insert(&MI);
780 }
781
782 // If Header unwinds to MBB (= Header contains 'invoke'), the try_table block
783 // should contain the call within it. So the call should go after the
784 // TRY_TABLE. The exception is when the header's terminator is a rethrow
785 // instruction, in which case that instruction, not a call instruction before
786 // it, is gonna throw.
787 MachineInstr *ThrowingCall = nullptr;
788 if (MBB.isPredecessor(Header)) {
789 auto TermPos = Header->getFirstTerminator();
790 if (TermPos == Header->end() ||
791 TermPos->getOpcode() != WebAssembly::RETHROW) {
792 for (auto &MI : reverse(*Header)) {
793 if (MI.isCall()) {
794 AfterSet.insert(&MI);
795 ThrowingCall = &MI;
796 break;
797 }
798 }
799 }
800 }
801
802 // Local expression tree should go after the TRY_TABLE.
803 // For BLOCK placement, we start the search from the previous instruction of a
804 // BB's terminator, but in TRY_TABLE's case, we should start from the previous
805 // instruction of a call that can throw, because the return values of the
806 // call's previous instructions can be stackified and consumed by the throwing
807 // call.
808 auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
809 : Header->getFirstTerminator();
810 for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
811 if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
812 continue;
813 if (WebAssembly::isChild(*std::prev(I), MFI))
814 AfterSet.insert(&*std::prev(I));
815 else
816 break;
817 }
818
819 // Add the TRY_TABLE and a BLOCK for the catch destination. We currently
820 // generate only one CATCH clause for a TRY_TABLE, so we need one BLOCK for
821 // its destination.
822 //
823 // Header:
824 // block
825 // try_table (catch ... $MBB)
826 // ...
827 //
828 // MBB:
829 // end_try_table
830 // end_block ;; destination of (catch ...)
831 // ... catch handler body ...
832 auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
833 MachineInstrBuilder BlockMIB =
834 BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
835 TII.get(WebAssembly::BLOCK));
836 auto *Block = BlockMIB.getInstr();
837 MachineInstrBuilder TryTableMIB =
838 BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
839 TII.get(WebAssembly::TRY_TABLE))
840 .addImm(int64_t(WebAssembly::BlockType::Void))
841 .addImm(1); // # of catch clauses
842 auto *TryTable = TryTableMIB.getInstr();
843
844 // Add a CATCH_*** clause to the TRY_TABLE. These are pseudo instructions
845 // following the destination END_BLOCK to simulate block return values,
846 // because we currently don't support them.
847 const auto &TLI =
848 *MF.getSubtarget<WebAssemblySubtarget>().getTargetLowering();
850 TLI.getPointerTy(MF.getDataLayout()) == MVT::i32
851 ? WebAssembly::BlockType::I32
852 : WebAssembly::BlockType::I64;
854 switch (Catch->getOpcode()) {
855 case WebAssembly::CATCH:
856 // CATCH's destination block's return type is the extracted value type,
857 // which is currently the thrown value's pointer type for all supported
858 // tags.
859 BlockMIB.addImm(int64_t(PtrTy));
860 TryTableMIB.addImm(wasm::WASM_OPCODE_CATCH);
861 for (const auto &Use : Catch->uses()) {
862 // The only use operand a CATCH can have is the tag symbol.
863 TryTableMIB.addExternalSymbol(Use.getSymbolName());
864 break;
865 }
866 TryTableMIB.addMBB(&MBB);
867 break;
868 case WebAssembly::CATCH_REF:
869 // CATCH_REF's destination block's return type is the extracted value type
870 // followed by an exnref, which is (i32, exnref) in our case. We assign the
871 // actual multiavlue signature in MCInstLower. MO_CATCH_BLOCK_SIG signals
872 // that this operand is used for catch_ref's multivalue destination.
873 BlockMIB.addImm(int64_t(WebAssembly::BlockType::Multivalue));
876 for (const auto &Use : Catch->uses()) {
877 TryTableMIB.addExternalSymbol(Use.getSymbolName());
878 break;
879 }
880 TryTableMIB.addMBB(&MBB);
881 break;
882 case WebAssembly::CATCH_ALL:
883 // CATCH_ALL's destination block's return type is void.
884 BlockMIB.addImm(int64_t(WebAssembly::BlockType::Void));
886 TryTableMIB.addMBB(&MBB);
887 break;
888 case WebAssembly::CATCH_ALL_REF:
889 // CATCH_ALL_REF's destination block's return type is exnref.
890 BlockMIB.addImm(int64_t(WebAssembly::BlockType::Exnref));
892 TryTableMIB.addMBB(&MBB);
893 break;
894 }
895
896 // Decide where in MBB to put the END_TRY_TABLE, and the END_BLOCK for the
897 // CATCH destination.
898 BeforeSet.clear();
899 AfterSet.clear();
900 for (const auto &MI : MBB) {
901#ifndef NDEBUG
902 // END_TRY_TABLE should precede existing LOOP markers.
903 if (MI.getOpcode() == WebAssembly::LOOP)
904 AfterSet.insert(&MI);
905#endif
906
907 // If there is a previously placed END_LOOP marker and the header of the
908 // loop is above this try_table's header, the END_LOOP should be placed
909 // after the END_TRY_TABLE, because the loop contains this block. Otherwise
910 // the END_LOOP should be placed before the END_TRY_TABLE.
911 if (MI.getOpcode() == WebAssembly::END_LOOP) {
912 if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
913 BeforeSet.insert(&MI);
914#ifndef NDEBUG
915 else
916 AfterSet.insert(&MI);
917#endif
918 }
919
920#ifndef NDEBUG
921 // CATCH, CATCH_REF, CATCH_ALL, and CATCH_ALL_REF are pseudo-instructions
922 // that simulate the block return value, so they should be placed after the
923 // END_TRY_TABLE.
924 if (WebAssembly::isCatch(MI.getOpcode()))
925 AfterSet.insert(&MI);
926#endif
927 }
928
929 // Mark the end of the TRY_TABLE and the BLOCK.
930 InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
931 MachineInstr *EndTryTable =
932 BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
933 TII.get(WebAssembly::END_TRY_TABLE));
934 registerTryScope(TryTable, EndTryTable, &MBB);
935 MachineInstr *EndBlock =
936 BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
937 TII.get(WebAssembly::END_BLOCK));
938 registerScope(Block, EndBlock);
939
940 // Track the farthest-spanning scope that ends at this point.
941 // Unlike the end_try, even if we don't put a end marker at the end of catch
942 // block, we still have to create two mappings: (BB with 'end_try_table' -> BB
943 // with 'try_table') and (BB after the (conceptual) catch block -> BB with
944 // 'try_table').
945 //
946 // This is what can happen if we don't create the latter mapping:
947 //
948 // Suppoe in the legacy EH we have this code:
949 // try
950 // try
951 // code1
952 // catch (a)
953 // end_try
954 // code2
955 // catch (b)
956 // end_try
957 //
958 // If we don't create the latter mapping, try_table markers would be placed
959 // like this:
960 // try_table
961 // code1
962 // end_try_table (a)
963 // try_table
964 // code2
965 // end_try_table (b)
966 //
967 // This does not reflect the original structure, and more important problem
968 // is, in case 'code1' has an unwind mismatch and should unwind to
969 // 'end_try_table (b)' rather than 'end_try_table (a)', we don't have a way to
970 // make it jump after 'end_try_table (b)' without creating another block. So
971 // even if we don't place 'end_try' marker at the end of 'catch' block
972 // anymore, we create ScopeTops mapping the same way as the legacy exception,
973 // so the resulting code will look like:
974 // try_table
975 // try_table
976 // code1
977 // end_try_table (a)
978 // code2
979 // end_try_table (b)
980 for (auto *End : {&MBB, Cont})
981 updateScopeTops(Header, End);
982}
983
984void WebAssemblyCFGStackifyImpl::removeUnnecessaryInstrs(MachineFunction &MF) {
985 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
986
987 // When there is an unconditional branch right before a catch instruction and
988 // it branches to the end of end_try marker, we don't need the branch, because
989 // if there is no exception, the control flow transfers to that point anyway.
990 // bb0:
991 // try
992 // ...
993 // br bb2 <- Not necessary
994 // bb1 (ehpad):
995 // catch
996 // ...
997 // bb2: <- Continuation BB
998 // end
999 //
1000 // A more involved case: When the BB where 'end' is located is an another EH
1001 // pad, the Cont (= continuation) BB is that EH pad's 'end' BB. For example,
1002 // bb0:
1003 // try
1004 // try
1005 // ...
1006 // br bb3 <- Not necessary
1007 // bb1 (ehpad):
1008 // catch
1009 // bb2 (ehpad):
1010 // end
1011 // catch
1012 // ...
1013 // bb3: <- Continuation BB
1014 // end
1015 //
1016 // When the EH pad at hand is bb1, its matching end_try is in bb2. But it is
1017 // another EH pad, so bb0's continuation BB becomes bb3. So 'br bb3' in the
1018 // code can be deleted. This is why we run 'while' until 'Cont' is not an EH
1019 // pad.
1020 for (auto &MBB : MF) {
1021 if (!MBB.isEHPad())
1022 continue;
1023
1024 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1025 SmallVector<MachineOperand, 4> Cond;
1026 MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
1027
1028 MachineBasicBlock *Cont = &MBB;
1029 while (Cont->isEHPad()) {
1030 MachineInstr *Try = EHPadToTry[Cont];
1031 MachineInstr *EndTry = BeginToEnd[Try];
1032 // We started from an EH pad, so the end marker cannot be a delegate
1033 assert(EndTry->getOpcode() != WebAssembly::DELEGATE);
1034 Cont = EndTry->getParent();
1035 }
1036
1037 bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
1038 // This condition means either
1039 // 1. This BB ends with a single unconditional branch whose destination is
1040 // Cont.
1041 // 2. This BB ends with a conditional branch followed by an unconditional
1042 // branch, and the unconditional branch's destination is Cont.
1043 // In both cases, we want to remove the last (= unconditional) branch.
1044 if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
1045 (!Cond.empty() && FBB && FBB == Cont))) {
1046 bool ErasedUncondBr = false;
1047 (void)ErasedUncondBr;
1048 for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
1049 I != E; --I) {
1050 auto PrevI = std::prev(I);
1051 if (PrevI->isTerminator()) {
1052 assert(PrevI->getOpcode() == WebAssembly::BR);
1053 PrevI->eraseFromParent();
1054 ErasedUncondBr = true;
1055 break;
1056 }
1057 }
1058 assert(ErasedUncondBr && "Unconditional branch not erased!");
1059 }
1060 }
1061
1062 // When there are block / end_block markers that overlap with try / end_try
1063 // markers, and the block and try markers' return types are the same, the
1064 // block /end_block markers are not necessary, because try / end_try markers
1065 // also can serve as boundaries for branches.
1066 // block <- Not necessary
1067 // try
1068 // ...
1069 // catch
1070 // ...
1071 // end
1072 // end <- Not necessary
1074 for (auto &MBB : MF) {
1075 for (auto &MI : MBB) {
1076 if (MI.getOpcode() != WebAssembly::TRY)
1077 continue;
1078 MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
1079 if (EndTry->getOpcode() == WebAssembly::DELEGATE)
1080 continue;
1081
1082 MachineBasicBlock *TryBB = Try->getParent();
1083 MachineBasicBlock *Cont = EndTry->getParent();
1084 int64_t RetType = Try->getOperand(0).getImm();
1085 for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
1086 B != TryBB->begin() && E != Cont->end() &&
1087 std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
1088 E->getOpcode() == WebAssembly::END_BLOCK &&
1089 std::prev(B)->getOperand(0).getImm() == RetType;
1090 --B, ++E) {
1091 ToDelete.push_back(&*std::prev(B));
1092 ToDelete.push_back(&*E);
1093 }
1094 }
1095 }
1096 for (auto *MI : ToDelete) {
1097 if (MI->getOpcode() == WebAssembly::BLOCK)
1098 unregisterScope(MI);
1099 MI->eraseFromParent();
1100 }
1101}
1102
1103// When MBB is split into MBB and Split, we should unstackify defs in MBB that
1104// have their uses in Split.
1106 MachineBasicBlock &Split) {
1107 MachineFunction &MF = *MBB.getParent();
1108 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1109 auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
1110 auto &MRI = MF.getRegInfo();
1111
1112 for (auto &MI : Split) {
1113 for (auto &MO : MI.explicit_uses()) {
1114 if (!MO.isReg() || MO.getReg().isPhysical())
1115 continue;
1116 if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
1117 if (Def->getParent() == &MBB)
1118 MFI.unstackifyVReg(MO.getReg());
1119 }
1120 }
1121
1122 // In RegStackify, when a register definition is used multiple times,
1123 // Reg = INST ...
1124 // INST ..., Reg, ...
1125 // INST ..., Reg, ...
1126 // INST ..., Reg, ...
1127 //
1128 // we introduce a TEE, which has the following form:
1129 // DefReg = INST ...
1130 // TeeReg, Reg = TEE_... DefReg
1131 // INST ..., TeeReg, ...
1132 // INST ..., Reg, ...
1133 // INST ..., Reg, ...
1134 // with DefReg and TeeReg stackified but Reg not stackified.
1135 //
1136 // But the invariant that TeeReg should be stackified can be violated while we
1137 // unstackify registers in the split BB above. In this case, we convert TEEs
1138 // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
1139 // DefReg = INST ...
1140 // TeeReg = COPY DefReg
1141 // Reg = COPY DefReg
1142 // INST ..., TeeReg, ...
1143 // INST ..., Reg, ...
1144 // INST ..., Reg, ...
1146 if (!WebAssembly::isTee(MI.getOpcode()))
1147 continue;
1148 Register TeeReg = MI.getOperand(0).getReg();
1149 Register Reg = MI.getOperand(1).getReg();
1150 Register DefReg = MI.getOperand(2).getReg();
1151 if (!MFI.isVRegStackified(TeeReg)) {
1152 // Now we are not using TEE anymore, so unstackify DefReg too
1153 MFI.unstackifyVReg(DefReg);
1154 unsigned CopyOpc =
1155 WebAssembly::getCopyOpcodeForRegClass(MRI.getRegClass(DefReg));
1156 BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
1157 .addReg(DefReg);
1158 BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
1159 MI.eraseFromParent();
1160 }
1161 }
1162}
1163
1164// Wrap the given range of instructions with a try-delegate that targets
1165// 'UnwindDest'. RangeBegin and RangeEnd are inclusive.
1166void WebAssemblyCFGStackifyImpl::addNestedTryDelegate(
1167 MachineInstr *RangeBegin, MachineInstr *RangeEnd,
1168 MachineBasicBlock *UnwindDest) {
1169 auto *BeginBB = RangeBegin->getParent();
1170 auto *EndBB = RangeEnd->getParent();
1171 MachineFunction &MF = *BeginBB->getParent();
1172 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
1173 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1174
1175 // Local expression tree before the first call of this range should go
1176 // after the nested TRY.
1177 SmallPtrSet<const MachineInstr *, 4> AfterSet;
1178 AfterSet.insert(RangeBegin);
1179 for (auto I = MachineBasicBlock::iterator(RangeBegin), E = BeginBB->begin();
1180 I != E; --I) {
1181 if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
1182 continue;
1183 if (WebAssembly::isChild(*std::prev(I), MFI))
1184 AfterSet.insert(&*std::prev(I));
1185 else
1186 break;
1187 }
1188
1189 // Create the nested try instruction.
1190 auto TryPos = getLatestInsertPos(
1191 BeginBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet);
1192 MachineInstr *Try = BuildMI(*BeginBB, TryPos, RangeBegin->getDebugLoc(),
1193 TII.get(WebAssembly::TRY))
1194 .addImm(int64_t(WebAssembly::BlockType::Void));
1195
1196 // Create a BB to insert the 'delegate' instruction.
1197 MachineBasicBlock *DelegateBB = MF.CreateMachineBasicBlock();
1198 // If the destination of 'delegate' is not the caller, adds the destination to
1199 // the BB's successors.
1200 if (UnwindDest != FakeCallerBB)
1201 DelegateBB->addSuccessor(UnwindDest);
1202
1203 auto SplitPos = std::next(RangeEnd->getIterator());
1204 if (SplitPos == EndBB->end()) {
1205 // If the range's end instruction is at the end of the BB, insert the new
1206 // delegate BB after the current BB.
1207 MF.insert(std::next(EndBB->getIterator()), DelegateBB);
1208 EndBB->addSuccessor(DelegateBB);
1209
1210 } else {
1211 // When the split pos is in the middle of a BB, we split the BB into two and
1212 // put the 'delegate' BB in between. We normally create a split BB and make
1213 // it a successor of the original BB (CatchAfterSplit == false), but in case
1214 // the BB is an EH pad and there is a 'catch' after the split pos
1215 // (CatchAfterSplit == true), we should preserve the BB's property,
1216 // including that it is an EH pad, in the later part of the BB, where the
1217 // 'catch' is.
1218 bool CatchAfterSplit = false;
1219 if (EndBB->isEHPad()) {
1220 for (auto I = MachineBasicBlock::iterator(SplitPos), E = EndBB->end();
1221 I != E; ++I) {
1222 if (WebAssembly::isCatch(I->getOpcode())) {
1223 CatchAfterSplit = true;
1224 break;
1225 }
1226 }
1227 }
1228
1229 MachineBasicBlock *PreBB = nullptr, *PostBB = nullptr;
1230 if (!CatchAfterSplit) {
1231 // If the range's end instruction is in the middle of the BB, we split the
1232 // BB into two and insert the delegate BB in between.
1233 // - Before:
1234 // bb:
1235 // range_end
1236 // other_insts
1237 //
1238 // - After:
1239 // pre_bb: (previous 'bb')
1240 // range_end
1241 // delegate_bb: (new)
1242 // delegate
1243 // post_bb: (new)
1244 // other_insts
1245 PreBB = EndBB;
1246 PostBB = MF.CreateMachineBasicBlock();
1247 MF.insert(std::next(PreBB->getIterator()), PostBB);
1248 MF.insert(std::next(PreBB->getIterator()), DelegateBB);
1249 PostBB->splice(PostBB->end(), PreBB, SplitPos, PreBB->end());
1250 PostBB->transferSuccessors(PreBB);
1251 } else {
1252 // - Before:
1253 // ehpad:
1254 // range_end
1255 // catch
1256 // ...
1257 //
1258 // - After:
1259 // pre_bb: (new)
1260 // range_end
1261 // delegate_bb: (new)
1262 // delegate
1263 // post_bb: (previous 'ehpad')
1264 // catch
1265 // ...
1266 assert(EndBB->isEHPad());
1267 PreBB = MF.CreateMachineBasicBlock();
1268 PostBB = EndBB;
1269 MF.insert(PostBB->getIterator(), PreBB);
1270 MF.insert(PostBB->getIterator(), DelegateBB);
1271 PreBB->splice(PreBB->end(), PostBB, PostBB->begin(), SplitPos);
1272 // We don't need to transfer predecessors of the EH pad to 'PreBB',
1273 // because an EH pad's predecessors are all through unwind edges and they
1274 // should still unwind to the EH pad, not PreBB.
1275 }
1276 unstackifyVRegsUsedInSplitBB(*PreBB, *PostBB);
1277 PreBB->addSuccessor(DelegateBB);
1278 PreBB->addSuccessor(PostBB);
1279 }
1280
1281 // Add a 'delegate' instruction in the delegate BB created above.
1282 MachineInstr *Delegate = BuildMI(DelegateBB, RangeEnd->getDebugLoc(),
1283 TII.get(WebAssembly::DELEGATE))
1284 .addMBB(UnwindDest);
1285 registerTryScope(Try, Delegate, nullptr);
1286}
1287
1288// Given an unwind destination, return a trampoline BB. A trampoline BB is a
1289// destination of a nested try_table inserted to fix an unwind mismatch. It
1290// contains an end_block, which is the target of the try_table, and a throw_ref,
1291// to rethrow the exception to the right try_table.
1292// try_table (catch ... )
1293// block exnref
1294// ...
1295// try_table (catch_all_ref N)
1296// some code
1297// end_try_table
1298// ...
1299// unreachable
1300// end_block ;; Trampoline BB
1301// throw_ref
1302// end_try_table
1303MachineBasicBlock *
1304WebAssemblyCFGStackifyImpl::getTrampolineBlock(MachineBasicBlock *UnwindDest) {
1305 // We need one trampoline BB per unwind destination, even though there are
1306 // multiple try_tables target the same unwind destination. If we have already
1307 // created one for the given UnwindDest, return it.
1308 auto It = UnwindDestToTrampoline.find(UnwindDest);
1309 if (It != UnwindDestToTrampoline.end())
1310 return It->second;
1311
1312 auto &MF = *UnwindDest->getParent();
1313 auto &MRI = MF.getRegInfo();
1314 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1315
1316 MachineInstr *Block = nullptr;
1317 MachineBasicBlock *TrampolineBB = nullptr;
1318 DebugLoc EndDebugLoc;
1319
1320 if (UnwindDest == getFakeCallerBlock(MF)) {
1321 // If the unwind destination is the caller, create a caller-dedicated
1322 // trampoline BB at the end of the function and wrap the whole function with
1323 // a block.
1324 auto BeginPos = MF.begin()->begin();
1325 while (WebAssembly::isArgument(BeginPos->getOpcode()))
1326 BeginPos++;
1327 Block = BuildMI(*MF.begin(), BeginPos, MF.begin()->begin()->getDebugLoc(),
1328 TII.get(WebAssembly::BLOCK))
1329 .addImm(int64_t(WebAssembly::BlockType::Exnref));
1330 TrampolineBB = getCallerTrampolineBlock(MF);
1331 MachineBasicBlock *PrevBB = &*std::prev(CallerTrampolineBB->getIterator());
1332 EndDebugLoc = PrevBB->findPrevDebugLoc(PrevBB->end());
1333 } else {
1334 // If the unwind destination is another EH pad, create a trampoline BB for
1335 // the unwind dest and insert a block instruction right after the target
1336 // try_table.
1337 auto *TargetBeginTry = EHPadToTry[UnwindDest];
1338 auto *TargetEndTry = BeginToEnd[TargetBeginTry];
1339 auto *TargetBeginBB = TargetBeginTry->getParent();
1340 auto *TargetEndBB = TargetEndTry->getParent();
1341
1342 Block = BuildMI(*TargetBeginBB, std::next(TargetBeginTry->getIterator()),
1343 TargetBeginTry->getDebugLoc(), TII.get(WebAssembly::BLOCK))
1344 .addImm(int64_t(WebAssembly::BlockType::Exnref));
1345 TrampolineBB = MF.CreateMachineBasicBlock();
1346 EndDebugLoc = TargetEndTry->getDebugLoc();
1347 MF.insert(TargetEndBB->getIterator(), TrampolineBB);
1348 TrampolineBB->addSuccessor(UnwindDest);
1349 }
1350
1351 // Insert an end_block, catch_all_ref (pseudo instruction), and throw_ref
1352 // instructions in the trampoline BB.
1353 MachineInstr *EndBlock =
1354 BuildMI(TrampolineBB, EndDebugLoc, TII.get(WebAssembly::END_BLOCK));
1355 auto ExnReg = MRI.createVirtualRegister(&WebAssembly::EXNREFRegClass);
1356 BuildMI(TrampolineBB, EndDebugLoc, TII.get(WebAssembly::CATCH_ALL_REF))
1357 .addDef(ExnReg);
1358 BuildMI(TrampolineBB, EndDebugLoc, TII.get(WebAssembly::THROW_REF))
1359 .addReg(ExnReg);
1360
1361 // The trampoline BB's return type is exnref because it is a target of
1362 // catch_all_ref. But the body type of the block we just created is not. We
1363 // add an 'unreachable' right before the 'end_block' to make the code valid.
1364 MachineBasicBlock *TrampolineLayoutPred = TrampolineBB->getPrevNode();
1365 BuildMI(TrampolineLayoutPred, TrampolineLayoutPred->findBranchDebugLoc(),
1366 TII.get(WebAssembly::UNREACHABLE));
1367
1368 registerScope(Block, EndBlock);
1369 UnwindDestToTrampoline[UnwindDest] = TrampolineBB;
1370 return TrampolineBB;
1371}
1372
1373// Wrap the given range of instructions with a try_table-end_try_table that
1374// targets 'UnwindDest'. RangeBegin and RangeEnd are inclusive.
1375void WebAssemblyCFGStackifyImpl::addNestedTryTable(
1376 MachineInstr *RangeBegin, MachineInstr *RangeEnd,
1377 MachineBasicBlock *UnwindDest) {
1378 auto *BeginBB = RangeBegin->getParent();
1379 auto *EndBB = RangeEnd->getParent();
1380
1381 MachineFunction &MF = *BeginBB->getParent();
1382 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
1383 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1384
1385 // Get the trampoline BB that the new try_table will unwind to.
1386 auto *TrampolineBB = getTrampolineBlock(UnwindDest);
1387
1388 // Local expression tree before the first call of this range should go
1389 // after the nested TRY_TABLE.
1390 SmallPtrSet<const MachineInstr *, 4> AfterSet;
1391 AfterSet.insert(RangeBegin);
1392 for (auto I = MachineBasicBlock::iterator(RangeBegin), E = BeginBB->begin();
1393 I != E; --I) {
1394 if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
1395 continue;
1396 if (WebAssembly::isChild(*std::prev(I), MFI))
1397 AfterSet.insert(&*std::prev(I));
1398 else
1399 break;
1400 }
1401
1402 // Create the nested try_table instruction.
1403 auto TryTablePos = getLatestInsertPos(
1404 BeginBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet);
1405 MachineInstr *TryTable =
1406 BuildMI(*BeginBB, TryTablePos, RangeBegin->getDebugLoc(),
1407 TII.get(WebAssembly::TRY_TABLE))
1408 .addImm(int64_t(WebAssembly::BlockType::Void))
1409 .addImm(1) // # of catch clauses
1411 .addMBB(TrampolineBB);
1412
1413 // Create a BB to insert the 'end_try_table' instruction.
1414 MachineBasicBlock *EndTryTableBB = MF.CreateMachineBasicBlock();
1415 EndTryTableBB->addSuccessor(TrampolineBB);
1416
1417 auto SplitPos = std::next(RangeEnd->getIterator());
1418 if (SplitPos == EndBB->end()) {
1419 // If the range's end instruction is at the end of the BB, insert the new
1420 // end_try_table BB after the current BB.
1421 MF.insert(std::next(EndBB->getIterator()), EndTryTableBB);
1422 EndBB->addSuccessor(EndTryTableBB);
1423
1424 } else {
1425 // When the split pos is in the middle of a BB, we split the BB into two and
1426 // put the 'end_try_table' BB in between. We normally create a split BB and
1427 // make it a successor of the original BB (CatchAfterSplit == false), but in
1428 // case the BB is an EH pad and there is a 'catch' after split pos
1429 // (CatchAfterSplit == true), we should preserve the BB's property,
1430 // including that it is an EH pad, in the later part of the BB, where the
1431 // 'catch' is.
1432 bool CatchAfterSplit = false;
1433 if (EndBB->isEHPad()) {
1434 for (auto I = MachineBasicBlock::iterator(SplitPos), E = EndBB->end();
1435 I != E; ++I) {
1436 if (WebAssembly::isCatch(I->getOpcode())) {
1437 CatchAfterSplit = true;
1438 break;
1439 }
1440 }
1441 }
1442
1443 MachineBasicBlock *PreBB = nullptr, *PostBB = nullptr;
1444 if (!CatchAfterSplit) {
1445 // If the range's end instruction is in the middle of the BB, we split the
1446 // BB into two and insert the end_try_table BB in between.
1447 // - Before:
1448 // bb:
1449 // range_end
1450 // other_insts
1451 //
1452 // - After:
1453 // pre_bb: (previous 'bb')
1454 // range_end
1455 // end_try_table_bb: (new)
1456 // end_try_table
1457 // post_bb: (new)
1458 // other_insts
1459 PreBB = EndBB;
1460 PostBB = MF.CreateMachineBasicBlock();
1461 MF.insert(std::next(PreBB->getIterator()), PostBB);
1462 MF.insert(std::next(PreBB->getIterator()), EndTryTableBB);
1463 PostBB->splice(PostBB->end(), PreBB, SplitPos, PreBB->end());
1464 PostBB->transferSuccessors(PreBB);
1465 } else {
1466 // - Before:
1467 // ehpad:
1468 // range_end
1469 // catch
1470 // ...
1471 //
1472 // - After:
1473 // pre_bb: (new)
1474 // range_end
1475 // end_try_table_bb: (new)
1476 // end_try_table
1477 // post_bb: (previous 'ehpad')
1478 // catch
1479 // ...
1480 assert(EndBB->isEHPad());
1481 PreBB = MF.CreateMachineBasicBlock();
1482 PostBB = EndBB;
1483 MF.insert(PostBB->getIterator(), PreBB);
1484 MF.insert(PostBB->getIterator(), EndTryTableBB);
1485 PreBB->splice(PreBB->end(), PostBB, PostBB->begin(), SplitPos);
1486 // We don't need to transfer predecessors of the EH pad to 'PreBB',
1487 // because an EH pad's predecessors are all through unwind edges and they
1488 // should still unwind to the EH pad, not PreBB.
1489 }
1490 unstackifyVRegsUsedInSplitBB(*PreBB, *PostBB);
1491 PreBB->addSuccessor(EndTryTableBB);
1492 PreBB->addSuccessor(PostBB);
1493 }
1494
1495 // Add a 'end_try_table' instruction in the EndTryTable BB created above.
1496 MachineInstr *EndTryTable = BuildMI(EndTryTableBB, RangeEnd->getDebugLoc(),
1497 TII.get(WebAssembly::END_TRY_TABLE));
1498 registerTryScope(TryTable, EndTryTable, TrampolineBB);
1499}
1500
1501// In the standard (exnref) EH, we fix unwind mismatches by adding a new
1502// block~end_block inside of the unwind destination try_table~end_try_table:
1503// try_table ...
1504// block exnref ;; (new)
1505// ...
1506// try_table (catch_all_ref N) ;; (new) to trampoline BB
1507// code
1508// end_try_table ;; (new)
1509// ...
1510// end_block ;; (new) trampoline BB
1511// throw_ref ;; (new)
1512// end_try_table
1513//
1514// To do this, we will create a new BB that will contain the new 'end_block' and
1515// 'throw_ref' and insert it before the 'end_try_table' BB.
1516//
1517// But there are cases when there are 'end_loop'(s) before the 'end_try_table'
1518// in the same BB. (There can't be 'end_block' before 'end_try_table' in the
1519// same BB because EH pads can't be directly branched to.) Then after fixing
1520// unwind mismatches this will create the mismatching markers like below:
1521// bb0:
1522// try_table
1523// block exnref
1524// ...
1525// loop
1526// ...
1527// new_bb:
1528// end_block
1529// end_try_table_bb:
1530// end_loop
1531// end_try_table
1532//
1533// So if an end_try_table BB has an end_loop before the end_try_table, we split
1534// the BB with the end_loop as a separate BB before the end_try_table BB, so
1535// that after we fix the unwind mismatch, the code will be like:
1536// bb0:
1537// try_table
1538// block exnref
1539// ...
1540// loop
1541// ...
1542// end_loop_bb:
1543// end_loop
1544// new_bb:
1545// end_block
1546// end_try_table_bb:
1547// end_try_table
1548static void splitEndLoopBB(MachineBasicBlock *EndTryTableBB) {
1549 auto &MF = *EndTryTableBB->getParent();
1550 MachineInstr *EndTryTable = nullptr, *EndLoop = nullptr;
1551 for (auto &MI : reverse(*EndTryTableBB)) {
1552 if (MI.getOpcode() == WebAssembly::END_TRY_TABLE) {
1553 EndTryTable = &MI;
1554 continue;
1555 }
1556 if (EndTryTable && MI.getOpcode() == WebAssembly::END_LOOP) {
1557 EndLoop = &MI;
1558 break;
1559 }
1560 }
1561 if (!EndLoop)
1562 return;
1563
1564 auto *EndLoopBB = MF.CreateMachineBasicBlock();
1565 MF.insert(EndTryTableBB->getIterator(), EndLoopBB);
1566 auto SplitPos = std::next(EndLoop->getIterator());
1567 EndLoopBB->splice(EndLoopBB->end(), EndTryTableBB, EndTryTableBB->begin(),
1568 SplitPos);
1569 EndLoopBB->addSuccessor(EndTryTableBB);
1570}
1571
1572// Print the BB name in the form of bb.NUMBER.ORIGINAL_NAME.
1573// e.g., bb.3.catch.start
1574[[maybe_unused]] static std::string getBBName(const MachineBasicBlock *MBB) {
1575 std::string Name = "bb.";
1576 Name += Twine(MBB->getNumber()).str();
1577 if (MBB->getBasicBlock()) {
1578 Name += ".";
1579 Name += MBB->getBasicBlock()->getName();
1580 }
1581 return Name;
1582}
1583
1584bool WebAssemblyCFGStackifyImpl::fixCallUnwindMismatches(MachineFunction &MF) {
1585 // This function is used for both the legacy EH and the standard (exnref) EH,
1586 // and the reason we have unwind mismatches is the same for the both of them,
1587 // but the code examples in the comments are going to be different. To make
1588 // the description less confusing, we write the basically same comments twice,
1589 // once for the legacy EH and the standard EH.
1590 //
1591 // -- Legacy EH --------------------------------------------------------------
1592 //
1593 // Linearizing the control flow by placing TRY / END_TRY markers can create
1594 // mismatches in unwind destinations for throwing instructions, such as calls.
1595 //
1596 // We use the 'delegate' instruction to fix the unwind mismatches. 'delegate'
1597 // instruction delegates an exception to an outer 'catch'. It can target not
1598 // only 'catch' but all block-like structures including another 'delegate',
1599 // but with slightly different semantics than branches. When it targets a
1600 // 'catch', it will delegate the exception to that catch. It is being
1601 // discussed how to define the semantics when 'delegate''s target is a non-try
1602 // block: it will either be a validation failure or it will target the next
1603 // outer try-catch. But anyway our LLVM backend currently does not generate
1604 // such code. The example below illustrates where the 'delegate' instruction
1605 // in the middle will delegate the exception to, depending on the value of N.
1606 // try
1607 // try
1608 // block
1609 // try
1610 // try
1611 // call @foo
1612 // delegate N ;; Where will this delegate to?
1613 // catch ;; N == 0
1614 // end
1615 // end ;; N == 1 (invalid; will not be generated)
1616 // delegate ;; N == 2
1617 // catch ;; N == 3
1618 // end
1619 // ;; N == 4 (to caller)
1620 //
1621 // 1. When an instruction may throw, but the EH pad it will unwind to can be
1622 // different from the original CFG.
1623 //
1624 // Example: we have the following CFG:
1625 // bb0:
1626 // call @foo ; if it throws, unwind to bb2
1627 // bb1:
1628 // call @bar ; if it throws, unwind to bb3
1629 // bb2 (ehpad):
1630 // catch
1631 // ...
1632 // bb3 (ehpad)
1633 // catch
1634 // ...
1635 //
1636 // And the CFG is sorted in this order. Then after placing TRY markers, it
1637 // will look like: (BB markers are omitted)
1638 // try
1639 // try
1640 // call @foo
1641 // call @bar ;; if it throws, unwind to bb3
1642 // catch ;; ehpad (bb2)
1643 // ...
1644 // end_try
1645 // catch ;; ehpad (bb3)
1646 // ...
1647 // end_try
1648 //
1649 // Now if bar() throws, it is going to end up in bb2, not bb3, where it is
1650 // supposed to end up. We solve this problem by wrapping the mismatching call
1651 // with an inner try-delegate that rethrows the exception to the right
1652 // 'catch'.
1653 //
1654 // try
1655 // try
1656 // call @foo
1657 // try ;; (new)
1658 // call @bar
1659 // delegate 1 (bb3) ;; (new)
1660 // catch ;; ehpad (bb2)
1661 // ...
1662 // end_try
1663 // catch ;; ehpad (bb3)
1664 // ...
1665 // end_try
1666 //
1667 // ---
1668 // 2. The same as 1, but in this case an instruction unwinds to a caller
1669 // function and not another EH pad.
1670 //
1671 // Example: we have the following CFG:
1672 // bb0:
1673 // call @foo ; if it throws, unwind to bb2
1674 // bb1:
1675 // call @bar ; if it throws, unwind to caller
1676 // bb2 (ehpad):
1677 // catch
1678 // ...
1679 //
1680 // And the CFG is sorted in this order. Then after placing TRY markers, it
1681 // will look like:
1682 // try
1683 // call @foo
1684 // call @bar ;; if it throws, unwind to caller
1685 // catch ;; ehpad (bb2)
1686 // ...
1687 // end_try
1688 //
1689 // Now if bar() throws, it is going to end up in bb2, when it is supposed
1690 // throw up to the caller. We solve this problem in the same way, but in this
1691 // case 'delegate's immediate argument is the number of block depths + 1,
1692 // which means it rethrows to the caller.
1693 // try
1694 // call @foo
1695 // try ;; (new)
1696 // call @bar
1697 // delegate 1 (caller) ;; (new)
1698 // catch ;; ehpad (bb2)
1699 // ...
1700 // end_try
1701 //
1702 // Before rewriteDepthImmediates, delegate's argument is a BB. In case of the
1703 // caller, it will take a fake BB generated by getFakeCallerBlock(), which
1704 // will be converted to a correct immediate argument later.
1705 //
1706 // In case there are multiple calls in a BB that may throw to the caller, they
1707 // can be wrapped together in one nested try-delegate scope. (In 1, this
1708 // couldn't happen, because may-throwing instruction there had an unwind
1709 // destination, i.e., it was an invoke before, and there could be only one
1710 // invoke within a BB.)
1711 //
1712 // -- Standard EH ------------------------------------------------------------
1713 //
1714 // Linearizing the control flow by placing TRY / END_TRY_TABLE markers can
1715 // create mismatches in unwind destinations for throwing instructions, such as
1716 // calls.
1717 //
1718 // We use the a nested 'try_table'~'end_try_table' instruction to fix the
1719 // unwind mismatches. try_table's catch clauses take an immediate argument
1720 // that specifics which block we should branch to.
1721 //
1722 // 1. When an instruction may throw, but the EH pad it will unwind to can be
1723 // different from the original CFG.
1724 //
1725 // Example: we have the following CFG:
1726 // bb0:
1727 // call @foo ; if it throws, unwind to bb2
1728 // bb1:
1729 // call @bar ; if it throws, unwind to bb3
1730 // bb2 (ehpad):
1731 // catch
1732 // ...
1733 // bb3 (ehpad)
1734 // catch
1735 // ...
1736 //
1737 // And the CFG is sorted in this order. Then after placing TRY_TABLE markers
1738 // (and BLOCK markers for the TRY_TABLE's destinations), it will look like:
1739 // (BB markers are omitted)
1740 // block
1741 // try_table (catch ... 0)
1742 // block
1743 // try_table (catch ... 0)
1744 // call @foo
1745 // call @bar ;; if it throws, unwind to bb3
1746 // end_try_table
1747 // end_block ;; ehpad (bb2)
1748 // ...
1749 // end_try_table
1750 // end_block ;; ehpad (bb3)
1751 // ...
1752 //
1753 // Now if bar() throws, it is going to end up in bb2, not bb3, where it is
1754 // supposed to end up. We solve this problem by wrapping the mismatching call
1755 // with an inner try_table~end_try_table that sends the exception to the the
1756 // 'trampoline' block, which rethrows, or 'bounces' it to the right
1757 // end_try_table:
1758 // block
1759 // try_table (catch ... 0)
1760 // block exnref ;; (new)
1761 // block
1762 // try_table (catch ... 0)
1763 // call @foo
1764 // try_table (catch_all_ref 2) ;; (new) to trampoline BB
1765 // call @bar
1766 // end_try_table ;; (new)
1767 // end_try_table
1768 // end_block ;; ehpad (bb2)
1769 // ...
1770 // end_block ;; (new) trampoline BB
1771 // throw_ref ;; (new)
1772 // end_try_table
1773 // end_block ;; ehpad (bb3)
1774 //
1775 // ---
1776 // 2. The same as 1, but in this case an instruction unwinds to a caller
1777 // function and not another EH pad.
1778 //
1779 // Example: we have the following CFG:
1780 // bb0:
1781 // call @foo ; if it throws, unwind to bb2
1782 // bb1:
1783 // call @bar ; if it throws, unwind to caller
1784 // bb2 (ehpad):
1785 // catch
1786 // ...
1787 //
1788 // And the CFG is sorted in this order. Then after placing TRY_TABLE markers
1789 // (and BLOCK markers for the TRY_TABLE's destinations), it will look like:
1790 // block
1791 // try_table (catch ... 0)
1792 // call @foo
1793 // call @bar ;; if it throws, unwind to caller
1794 // end_try_table
1795 // end_block ;; ehpad (bb2)
1796 // ...
1797 //
1798 // Now if bar() throws, it is going to end up in bb2, when it is supposed
1799 // throw up to the caller. We solve this problem in the same way, but in this
1800 // case 'catch_all_ref's immediate argument is the number of block depths + 1,
1801 // which means it rethrows to the caller.
1802 // block exnref ;; (new)
1803 // block
1804 // try_table (catch ... 0)
1805 // call @foo
1806 // try_table (catch_all_ref 2) ;; (new) to trampoline BB
1807 // call @bar
1808 // end_try_table ;; (new)
1809 // end_try_table
1810 // end_block ;; ehpad (bb2)
1811 // ...
1812 // end_block ;; (new) caller trampoline BB
1813 // throw_ref ;; (new) throw to the caller
1814 //
1815 // Before rewriteDepthImmediates, try_table's catch clauses' argument is a
1816 // trampoline BB from which we throw_ref the exception to the right
1817 // end_try_table. In case of the caller, it will take a new caller-dedicated
1818 // trampoline BB generated by getCallerTrampolineBlock(), which throws the
1819 // exception to the caller.
1820 //
1821 // In case there are multiple calls in a BB that may throw to the caller, they
1822 // can be wrapped together in one nested try_table-end_try_table scope. (In 1,
1823 // this couldn't happen, because may-throwing instruction there had an unwind
1824 // destination, i.e., it was an invoke before, and there could be only one
1825 // invoke within a BB.)
1826
1828 // Range of instructions to be wrapped in a new nested try~delegate or
1829 // try_table~end_try_table. A range exists in a single BB and does not span
1830 // multiple BBs.
1831 using TryRange = std::pair<MachineInstr *, MachineInstr *>;
1832 // In original CFG, <unwind destination BB, a vector of try/try_table ranges>
1833 MapVector<MachineBasicBlock *, SmallVector<TryRange, 4>>
1834 UnwindDestToTryRanges;
1835
1836 // Gather possibly throwing calls (i.e., previously invokes) whose current
1837 // unwind destination is not the same as the original CFG. (Case 1)
1838
1839 for (auto &MBB : reverse(MF)) {
1840 bool SeenThrowableInstInBB = false;
1841 for (auto &MI : reverse(MBB)) {
1842 if (WebAssembly::isTry(MI.getOpcode()))
1843 EHPadStack.pop_back();
1844 else if (MI.getOpcode() == WebAssembly::DELEGATE)
1845 EHPadStack.push_back(MI.getOperand(0).getMBB());
1846 else if (CLOpts.use_legacy_eh && WebAssembly::isCatch(MI.getOpcode()))
1847 EHPadStack.push_back(MI.getParent());
1848 else if (MI.getOpcode() == WebAssembly::END_TRY_TABLE)
1849 // In case of the legacy EH, 'catch' instruction is always an EH pad for
1850 // the 'try' body that precedes it. But in the standard EH, because
1851 // fixCatchUnwindMismatches runs before this, a new try_table's
1852 // trampoline BB will be separated from try_table ~ end_try_table body:
1853 //
1854 // bb0:
1855 // try_table (catch_all_ref %far_away_trampoline)
1856 // ...
1857 // end_try_table
1858 // ...
1859 // far_away_trampoline:
1860 // catch_all_ref
1861 // throw_ref
1862 //
1863 // And there can be multiple try_tables that target a single trampoline:
1864 //
1865 // bb0:
1866 // try_table (catch_all_ref %far_away_trampolinle_bb)
1867 // ...
1868 // end_try_table
1869 // ...
1870 // bb1:
1871 // try_table (catch_all_ref %far_away_trampolinle_bb)
1872 // ...
1873 // end_try_table
1874 // ...
1875 // far_away_trampoline:
1876 // catch_all_ref
1877 // throw_ref
1878 //
1879 // So we can't call WebAssembly::isCatch to add its parent EH pad to
1880 // EHPadStack. Now we add to EHPadStack at end_try_table marker, by
1881 // getting its matching try_table's destination. This works when the
1882 // destination EH pad is either a normal EH pad or a trampoline created
1883 // in fixCatchUnwindMismatches.
1884 //
1885 // Note that we don't need to distinguish this case in
1886 // fixCatchUnwindMismatches because it runs before
1887 // fixCallUnwindMismatches and there is no new try_tables and
1888 // trampolines when it runs.
1889 EHPadStack.push_back(TryToEHPad[EndToBegin[&MI]]);
1890
1891 // In this loop we only gather calls that have an EH pad to unwind. So
1892 // there will be at most 1 such call (= invoke) in a BB, so after we've
1893 // seen one, we can skip the rest of BB. Also if MBB has no EH pad
1894 // successor or MI does not throw, this is not an invoke.
1895 if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() ||
1897 continue;
1898 SeenThrowableInstInBB = true;
1899
1900 // If the EH pad on the stack top is where this instruction should unwind
1901 // next, we're good.
1902 MachineBasicBlock *UnwindDest = nullptr;
1903 for (auto *Succ : MBB.successors()) {
1904 // Even though semantically a BB can have multiple successors in case an
1905 // exception is not caught by a catchpad, the first unwind destination
1906 // should appear first in the successor list, based on the calculation
1907 // in findUnwindDestinations() in SelectionDAGBuilder.cpp.
1908 if (Succ->isEHPad()) {
1909 UnwindDest = Succ;
1910 break;
1911 }
1912 }
1913 if (EHPadStack.back() == UnwindDest)
1914 continue;
1915
1916 // If not, record the range.
1917 UnwindDestToTryRanges[UnwindDest].push_back(TryRange(&MI, &MI));
1918 LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = " << getBBName(&MBB)
1919 << "\nCall = " << MI
1920 << "\nOriginal dest = " << getBBName(UnwindDest)
1921 << " Current dest = " << getBBName(EHPadStack.back())
1922 << "\n\n");
1923 }
1924 }
1925
1926 assert(EHPadStack.empty());
1927
1928 // Gather possibly throwing calls that are supposed to unwind up to the caller
1929 // if they throw, but currently unwind to an incorrect destination. Unlike the
1930 // loop above, there can be multiple calls within a BB that unwind to the
1931 // caller, which we should group together in a range. (Case 2)
1932
1933 MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive
1934
1935 // Record the range.
1936 auto RecordCallerMismatchRange = [&](const MachineBasicBlock *CurrentDest) {
1937 UnwindDestToTryRanges[getFakeCallerBlock(MF)].push_back(
1938 TryRange(RangeBegin, RangeEnd));
1939 LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = "
1940 << getBBName(RangeBegin->getParent())
1941 << "\nRange begin = " << *RangeBegin
1942 << "Range end = " << *RangeEnd
1943 << "\nOriginal dest = caller Current dest = "
1944 << getBBName(CurrentDest) << "\n\n");
1945 RangeBegin = RangeEnd = nullptr; // Reset range pointers
1946 };
1947
1948 for (auto &MBB : reverse(MF)) {
1949 bool SeenThrowableInstInBB = false;
1950 for (auto &MI : reverse(MBB)) {
1951 bool MayThrow = WebAssembly::mayThrow(MI);
1952
1953 // If MBB has an EH pad successor and this is the last instruction that
1954 // may throw, this instruction unwinds to the EH pad and not to the
1955 // caller.
1956 if (MBB.hasEHPadSuccessor() && MayThrow && !SeenThrowableInstInBB)
1957 SeenThrowableInstInBB = true;
1958
1959 // We wrap up the current range when we see a marker even if we haven't
1960 // finished a BB.
1961 else if (RangeEnd && WebAssembly::isMarker(MI.getOpcode()))
1962 RecordCallerMismatchRange(EHPadStack.back());
1963
1964 // If EHPadStack is empty, that means it correctly unwinds to the caller
1965 // if it throws, so we're good. A delegate targeting FakeCallerBB also
1966 // correctly unwinds to the caller. If MI does not throw, we're good too.
1967 else if (EHPadStack.empty() || EHPadStack.back() == FakeCallerBB ||
1968 !MayThrow) {
1969 }
1970
1971 // We found an instruction that unwinds to the caller but currently has an
1972 // incorrect unwind destination. Create a new range or increment the
1973 // currently existing range.
1974 else {
1975 if (!RangeEnd)
1976 RangeBegin = RangeEnd = &MI;
1977 else
1978 RangeBegin = &MI;
1979 }
1980
1981 // Update EHPadStack.
1982 if (WebAssembly::isTry(MI.getOpcode()))
1983 EHPadStack.pop_back();
1984 else if (MI.getOpcode() == WebAssembly::DELEGATE)
1985 EHPadStack.push_back(MI.getOperand(0).getMBB());
1986 else if (CLOpts.use_legacy_eh && WebAssembly::isCatch(MI.getOpcode()))
1987 EHPadStack.push_back(MI.getParent());
1988 else if (!CLOpts.use_legacy_eh &&
1989 MI.getOpcode() == WebAssembly::END_TRY_TABLE)
1990 EHPadStack.push_back(TryToEHPad[EndToBegin[&MI]]);
1991 }
1992
1993 if (RangeEnd)
1994 RecordCallerMismatchRange(EHPadStack.back());
1995 }
1996
1997 assert(EHPadStack.empty());
1998
1999 // We don't have any unwind destination mismatches to resolve.
2000 if (UnwindDestToTryRanges.empty())
2001 return false;
2002
2003 // When end_loop is before end_try_table within the same BB in unwind
2004 // destinations, we should split the end_loop into another BB.
2005 if (!CLOpts.use_legacy_eh)
2006 for (auto &[UnwindDest, _] : UnwindDestToTryRanges) {
2007 auto It = EHPadToTry.find(UnwindDest);
2008 // If UnwindDest is the fake caller block, it will not be in EHPadToTry
2009 // map
2010 if (It != EHPadToTry.end()) {
2011 auto *TryTable = It->second;
2012 auto *EndTryTable = BeginToEnd[TryTable];
2013 splitEndLoopBB(EndTryTable->getParent());
2014 }
2015 }
2016
2017 // Now we fix the mismatches by wrapping calls with inner try-delegates.
2018 for (auto &P : UnwindDestToTryRanges) {
2019 NumCallUnwindMismatches += P.second.size();
2020 MachineBasicBlock *UnwindDest = P.first;
2021 auto &TryRanges = P.second;
2022
2023 for (auto Range : TryRanges) {
2024 MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr;
2025 std::tie(RangeBegin, RangeEnd) = Range;
2026 auto *MBB = RangeBegin->getParent();
2027
2028 // If this BB has an EH pad successor, i.e., ends with an 'invoke', and if
2029 // the current range contains the invoke, now we are going to wrap the
2030 // invoke with try-delegate or try_table-end_try_table, making the
2031 // 'delegate' or 'end_try_table' BB the new successor instead, so remove
2032 // the EH pad successor here. The BB may not have an EH pad successor if
2033 // calls in this BB throw to the caller.
2034 if (UnwindDest != getFakeCallerBlock(MF)) {
2035 MachineBasicBlock *EHPad = nullptr;
2036 for (auto *Succ : MBB->successors()) {
2037 if (Succ->isEHPad()) {
2038 EHPad = Succ;
2039 break;
2040 }
2041 }
2042 if (EHPad)
2043 MBB->removeSuccessor(EHPad);
2044 }
2045
2046 if (CLOpts.use_legacy_eh)
2047 addNestedTryDelegate(RangeBegin, RangeEnd, UnwindDest);
2048 else
2049 addNestedTryTable(RangeBegin, RangeEnd, UnwindDest);
2050 }
2051 }
2052
2053 return true;
2054}
2055
2056bool WebAssemblyCFGStackifyImpl::fixCatchUnwindMismatches(MachineFunction &MF) {
2057 // This function is used for both the legacy EH and the standard (exnref) EH,
2058 // and the reason we have unwind mismatches is the same for the both of them,
2059 // but the code examples in the comments are going to be different. To make
2060 // the description less confusing, we write the basically same comments twice,
2061 // once for the legacy EH and the standard EH.
2062 //
2063 // -- Legacy EH --------------------------------------------------------------
2064 //
2065 // There is another kind of unwind destination mismatches besides call unwind
2066 // mismatches, which we will call "catch unwind mismatches". See this example
2067 // after the marker placement:
2068 // try
2069 // try
2070 // call @foo
2071 // catch __cpp_exception ;; ehpad A (next unwind dest: caller)
2072 // ...
2073 // end_try
2074 // catch_all ;; ehpad B
2075 // ...
2076 // end_try
2077 //
2078 // 'call @foo's unwind destination is the ehpad A. But suppose 'call @foo'
2079 // throws a foreign exception that is not caught by ehpad A, and its next
2080 // destination should be the caller. But after control flow linearization,
2081 // another EH pad can be placed in between (e.g. ehpad B here), making the
2082 // next unwind destination incorrect. In this case, the foreign exception will
2083 // instead go to ehpad B and will be caught there instead. In this example the
2084 // correct next unwind destination is the caller, but it can be another outer
2085 // catch in other cases.
2086 //
2087 // There is no specific 'call' or 'throw' instruction to wrap with a
2088 // try-delegate, so we wrap the whole try-catch-end with a try-delegate and
2089 // make it rethrow to the right destination, which is the caller in the
2090 // example below:
2091 // try
2092 // try ;; (new)
2093 // try
2094 // call @foo
2095 // catch __cpp_exception ;; ehpad A (next unwind dest: caller)
2096 // ...
2097 // end_try
2098 // delegate 1 (caller) ;; (new)
2099 // catch_all ;; ehpad B
2100 // ...
2101 // end_try
2102 //
2103 // The right destination may be another EH pad or the caller. (The example
2104 // here shows the case it is the caller.)
2105 //
2106 // -- Standard EH ------------------------------------------------------------
2107 //
2108 // There is another kind of unwind destination mismatches besides call unwind
2109 // mismatches, which we will call "catch unwind mismatches". See this example
2110 // after the marker placement:
2111 // block
2112 // try_table (catch_all_ref 0)
2113 // block
2114 // try_table (catch ... 0)
2115 // call @foo
2116 // end_try_table
2117 // end_block ;; ehpad A (next unwind dest: caller)
2118 // ...
2119 // end_try_table
2120 // end_block ;; ehpad B
2121 // ...
2122 //
2123 // 'call @foo's unwind destination is the ehpad A. But suppose 'call @foo'
2124 // throws a foreign exception that is not caught by ehpad A, and its next
2125 // destination should be the caller. But after control flow linearization,
2126 // another EH pad can be placed in between (e.g. ehpad B here), making the
2127 // next unwind destination incorrect. In this case, the foreign exception will
2128 // instead go to ehpad B and will be caught there instead. In this example the
2129 // correct next unwind destination is the caller, but it can be another outer
2130 // catch in other cases.
2131 //
2132 // There is no specific 'call' or 'throw' instruction to wrap with an inner
2133 // try_table-end_try_table, so we wrap the whole try_table-end_try_table with
2134 // an inner try_table-end_try_table that sends the exception to a trampoline
2135 // BB. We rethrow the sent exception using a throw_ref to the right
2136 // destination, which is the caller in the example below:
2137 // block exnref
2138 // block
2139 // try_table (catch_all_ref 0)
2140 // try_table (catch_all_ref 2) ;; (new) to trampoline
2141 // block
2142 // try_table (catch ... 0)
2143 // call @foo
2144 // end_try_table
2145 // end_block ;; ehpad A (next unwind dest: caller)
2146 // end_try_table ;; (new)
2147 // ...
2148 // end_try_table
2149 // end_block ;; ehpad B
2150 // ...
2151 // end_block ;; (new) caller trampoline BB
2152 // throw_ref ;; (new) throw to the caller
2153 //
2154 // The right destination may be another EH pad or the caller. (The example
2155 // here shows the case it is the caller.)
2156
2157 // Returns whether the next unwind destination exists when an exception is not
2158 // caught by the given EHPad. It is guaranteed that the next successor of the
2159 // given EHPad's predecessor is the next unwind destination, due to the order
2160 // we add successors in findUnwindDestinations in SelectionDAGBuilder.
2161 auto HasUnwindDest = [&](const MachineBasicBlock *EHPad) {
2162 assert(!EHPad->pred_empty() && "EHPad has no predecessors");
2163 auto *InvokeBB = *EHPad->pred_begin();
2164 for (auto I = InvokeBB->succ_begin(), E = InvokeBB->succ_end(); I != E; ++I)
2165 if (*I == EHPad)
2166 return std::next(I) != E;
2167 llvm_unreachable("EHPad not found in its predecessor's successors");
2168 };
2169
2170 // Returns the next unwind destination when an exception is not caught by the
2171 // given EHPad. Returns nullptr when it doesn't exist.
2172 auto GetUnwindDest = [&](const MachineBasicBlock *EHPad) {
2173 assert(!EHPad->pred_empty() && "EHPad has no predecessors");
2174 auto *InvokeBB = *EHPad->pred_begin();
2175 for (auto I = InvokeBB->succ_begin(), E = InvokeBB->succ_end(); I != E;
2176 ++I) {
2177 if (*I == EHPad) {
2178 auto *Next = std::next(I);
2179 return Next == E ? nullptr : *Next;
2180 }
2181 }
2182 llvm_unreachable("EHPad not found in its predecessor's successors");
2183 };
2184
2186 // For EH pads that have catch unwind mismatches, a map of <EH pad, its
2187 // correct unwind destination>.
2188 MapVector<MachineBasicBlock *, MachineBasicBlock *> EHPadToUnwindDest;
2189
2190 for (auto &MBB : reverse(MF)) {
2191 for (auto &MI : reverse(MBB)) {
2192 if (WebAssembly::isTry(MI.getOpcode())) {
2193 EHPadStack.pop_back();
2194 } else if (MI.getOpcode() == WebAssembly::DELEGATE) {
2195 EHPadStack.push_back(&MBB);
2196 } else if (WebAssembly::isCatch(MI.getOpcode())) {
2197 auto *EHPad = &MBB;
2198
2199 // catch_all always catches an exception, so we don't need to do
2200 // anything
2201 if (WebAssembly::isCatchAll(MI.getOpcode())) {
2202 }
2203
2204 // This can happen when the unwind dest was removed during the
2205 // optimization, e.g. because it was unreachable.
2206 else if (EHPadStack.empty() && HasUnwindDest(EHPad)) {
2207 LLVM_DEBUG(dbgs() << "EHPad (" << getBBName(EHPad)
2208 << "'s unwind destination does not exist anymore"
2209 << "\n\n");
2210 }
2211
2212 // The EHPad's next unwind destination is the caller, but we incorrectly
2213 // unwind to another EH pad.
2214 else if (!EHPadStack.empty() && EHPadStack.back() != FakeCallerBB &&
2215 !HasUnwindDest(EHPad)) {
2216 EHPadToUnwindDest[EHPad] = getFakeCallerBlock(MF);
2218 << "- Catch unwind mismatch:\nEHPad = " << getBBName(EHPad)
2219 << " Original dest = caller Current dest = "
2220 << getBBName(EHPadStack.back()) << "\n\n");
2221 }
2222
2223 // The EHPad's next unwind destination is an EH pad, whereas we
2224 // incorrectly unwind to another EH pad.
2225 else if (!EHPadStack.empty() && HasUnwindDest(EHPad)) {
2226 auto *UnwindDest = GetUnwindDest(EHPad);
2227 if (EHPadStack.back() != UnwindDest) {
2228 EHPadToUnwindDest[EHPad] = UnwindDest;
2229 LLVM_DEBUG(dbgs() << "- Catch unwind mismatch:\nEHPad = "
2230 << getBBName(EHPad) << " Original dest = "
2231 << getBBName(UnwindDest) << " Current dest = "
2232 << getBBName(EHPadStack.back()) << "\n\n");
2233 }
2234 }
2235
2236 EHPadStack.push_back(EHPad);
2237 }
2238 }
2239 }
2240
2241 assert(EHPadStack.empty());
2242 if (EHPadToUnwindDest.empty())
2243 return false;
2244
2245 // When end_loop is before end_try_table within the same BB in unwind
2246 // destinations, we should split the end_loop into another BB.
2247 for (auto &[_, UnwindDest] : EHPadToUnwindDest) {
2248 auto It = EHPadToTry.find(UnwindDest);
2249 // If UnwindDest is the fake caller block, it will not be in EHPadToTry map
2250 if (It != EHPadToTry.end()) {
2251 auto *TryTable = It->second;
2252 auto *EndTryTable = BeginToEnd[TryTable];
2253 splitEndLoopBB(EndTryTable->getParent());
2254 }
2255 }
2256
2257 NumCatchUnwindMismatches += EHPadToUnwindDest.size();
2258 SmallPtrSet<MachineBasicBlock *, 4> NewEndTryBBs;
2259
2260 for (auto &[EHPad, UnwindDest] : EHPadToUnwindDest) {
2261 MachineInstr *Try = EHPadToTry[EHPad];
2262 MachineInstr *EndTry = BeginToEnd[Try];
2263 if (CLOpts.use_legacy_eh) {
2264 addNestedTryDelegate(Try, EndTry, UnwindDest);
2265 NewEndTryBBs.insert(EndTry->getParent());
2266 } else {
2267 addNestedTryTable(Try, EndTry, UnwindDest);
2268 }
2269 }
2270
2271 if (!CLOpts.use_legacy_eh)
2272 return true;
2273
2274 // Adding a try-delegate wrapping an existing try-catch-end can make existing
2275 // branch destination BBs invalid. For example,
2276 //
2277 // - Before:
2278 // bb0:
2279 // block
2280 // br bb3
2281 // bb1:
2282 // try
2283 // ...
2284 // bb2: (ehpad)
2285 // catch
2286 // bb3:
2287 // end_try
2288 // end_block ;; 'br bb3' targets here
2289 //
2290 // Suppose this try-catch-end has a catch unwind mismatch, so we need to wrap
2291 // this with a try-delegate. Then this becomes:
2292 //
2293 // - After:
2294 // bb0:
2295 // block
2296 // br bb3 ;; invalid destination!
2297 // bb1:
2298 // try ;; (new instruction)
2299 // try
2300 // ...
2301 // bb2: (ehpad)
2302 // catch
2303 // bb3:
2304 // end_try ;; 'br bb3' still incorrectly targets here!
2305 // delegate_bb: ;; (new BB)
2306 // delegate ;; (new instruction)
2307 // split_bb: ;; (new BB)
2308 // end_block
2309 //
2310 // Now 'br bb3' incorrectly branches to an inner scope.
2311 //
2312 // As we can see in this case, when branches target a BB that has both
2313 // 'end_try' and 'end_block' and the BB is split to insert a 'delegate', we
2314 // have to remap existing branch destinations so that they target not the
2315 // 'end_try' BB but the new 'end_block' BB. There can be multiple 'delegate's
2316 // in between, so we try to find the next BB with 'end_block' instruction. In
2317 // this example, the 'br bb3' instruction should be remapped to 'br split_bb'.
2318 for (auto &MBB : MF) {
2319 for (auto &MI : MBB) {
2320 if (MI.isTerminator()) {
2321 for (auto &MO : MI.operands()) {
2322 if (MO.isMBB() && NewEndTryBBs.count(MO.getMBB())) {
2323 auto *BrDest = MO.getMBB();
2324 bool FoundEndBlock = false;
2325 for (; std::next(BrDest->getIterator()) != MF.end();
2326 BrDest = BrDest->getNextNode()) {
2327 for (const auto &MI : *BrDest) {
2328 if (MI.getOpcode() == WebAssembly::END_BLOCK) {
2329 FoundEndBlock = true;
2330 break;
2331 }
2332 }
2333 if (FoundEndBlock)
2334 break;
2335 }
2336 assert(FoundEndBlock);
2337 MO.setMBB(BrDest);
2338 }
2339 }
2340 }
2341 }
2342 }
2343
2344 return true;
2345}
2346
2347void WebAssemblyCFGStackifyImpl::recalculateScopeTops(MachineFunction &MF) {
2348 // Renumber BBs and recalculate ScopeTop info because new BBs might have been
2349 // created and inserted during fixing unwind mismatches.
2350 MF.RenumberBlocks();
2351 ScopeTops.clear();
2352 ScopeTops.resize(MF.getNumBlockIDs());
2353 for (auto &MBB : reverse(MF)) {
2354 for (auto &MI : reverse(MBB)) {
2355 if (ScopeTops[MBB.getNumber()])
2356 break;
2357 switch (MI.getOpcode()) {
2358 case WebAssembly::END_BLOCK:
2359 case WebAssembly::END_LOOP:
2360 case WebAssembly::END_TRY:
2361 case WebAssembly::END_TRY_TABLE:
2362 case WebAssembly::DELEGATE:
2363 updateScopeTops(EndToBegin[&MI]->getParent(), &MBB);
2364 break;
2365 case WebAssembly::CATCH_LEGACY:
2366 case WebAssembly::CATCH_ALL_LEGACY:
2367 updateScopeTops(EHPadToTry[&MBB]->getParent(), &MBB);
2368 break;
2369 }
2370 }
2371 }
2372}
2373
2374/// In normal assembly languages, when the end of a function is unreachable,
2375/// because the function ends in an infinite loop or a noreturn call or similar,
2376/// it isn't necessary to worry about the function return type at the end of
2377/// the function, because it's never reached. However, in WebAssembly, blocks
2378/// that end at the function end need to have a return type signature that
2379/// matches the function signature, even though it's unreachable. This function
2380/// checks for such cases and fixes up the signatures.
2381void WebAssemblyCFGStackifyImpl::fixEndsAtEndOfFunction(MachineFunction &MF) {
2382 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
2383
2384 if (MFI.getResults().empty())
2385 return;
2386
2387 // MCInstLower will add the proper types to multivalue signatures based on the
2388 // function return type
2389 WebAssembly::BlockType RetType =
2390 MFI.getResults().size() > 1
2391 ? WebAssembly::BlockType::Multivalue
2393 WebAssembly::toValType(MFI.getResults().front()));
2394
2396 Worklist.push_back(MF.rbegin()->rbegin());
2397
2398 auto Process = [&](MachineBasicBlock::reverse_iterator It) {
2399 auto *MBB = It->getParent();
2400 while (It != MBB->rend()) {
2401 MachineInstr &MI = *It++;
2402 if (MI.isPosition() || MI.isDebugInstr())
2403 continue;
2404 switch (MI.getOpcode()) {
2405 case WebAssembly::END_TRY: {
2406 // If a 'try''s return type is fixed, both its try body and catch body
2407 // should satisfy the return type, so we need to search 'end'
2408 // instructions before its corresponding 'catch' too.
2409 auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
2410 assert(EHPad);
2411 auto NextIt =
2412 std::next(WebAssembly::findCatch(EHPad)->getReverseIterator());
2413 if (NextIt != EHPad->rend())
2414 Worklist.push_back(NextIt);
2415 [[fallthrough]];
2416 }
2417 case WebAssembly::END_BLOCK:
2418 case WebAssembly::END_LOOP:
2419 case WebAssembly::END_TRY_TABLE:
2420 case WebAssembly::DELEGATE:
2421 EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
2422 continue;
2423 default:
2424 // Something other than an `end`. We're done for this BB.
2425 return;
2426 }
2427 }
2428 // We've reached the beginning of a BB. Continue the search in the previous
2429 // BB.
2430 Worklist.push_back(MBB->getPrevNode()->rbegin());
2431 };
2432
2433 while (!Worklist.empty())
2434 Process(Worklist.pop_back_val());
2435}
2436
2437// WebAssembly functions end with an end instruction, as if the function body
2438// were a block.
2440 const WebAssemblyInstrInfo &TII) {
2441 BuildMI(MF.back(), MF.back().end(),
2442 MF.back().findPrevDebugLoc(MF.back().end()),
2443 TII.get(WebAssembly::END_FUNCTION));
2444}
2445
2446// We added block~end_block and try_table~end_try_table markers in
2447// placeTryTableMarker. But When catch clause's destination has a return type,
2448// as in the case of catch with a concrete tag, catch_ref, and catch_all_ref.
2449// For example:
2450// block exnref
2451// try_table (catch_all_ref 0)
2452// ...
2453// end_try_table
2454// end_block
2455// ... use exnref ...
2456//
2457// This code is not valid because the block's body type is not exnref. So we add
2458// an unreachable after the 'end_try_table' to make the code valid here:
2459// block exnref
2460// try_table (catch_all_ref 0)
2461// ...
2462// end_try_table
2463// unreachable (new)
2464// end_block
2465//
2466// Because 'unreachable' is a terminator we also need to split the BB.
2468 const WebAssemblyInstrInfo &TII) {
2469 std::vector<MachineInstr *> EndTryTables;
2470 for (auto &MBB : MF)
2471 for (auto &MI : MBB)
2472 if (MI.getOpcode() == WebAssembly::END_TRY_TABLE)
2473 EndTryTables.push_back(&MI);
2474
2475 for (auto *EndTryTable : EndTryTables) {
2476 auto *MBB = EndTryTable->getParent();
2477 auto *NewEndTryTableBB = MF.CreateMachineBasicBlock();
2478 MF.insert(MBB->getIterator(), NewEndTryTableBB);
2479 auto SplitPos = std::next(EndTryTable->getIterator());
2480 NewEndTryTableBB->splice(NewEndTryTableBB->end(), MBB, MBB->begin(),
2481 SplitPos);
2482 NewEndTryTableBB->addSuccessor(MBB);
2483 BuildMI(NewEndTryTableBB, EndTryTable->getDebugLoc(),
2484 TII.get(WebAssembly::UNREACHABLE));
2485 }
2486}
2487
2488/// Insert BLOCK/LOOP/TRY/TRY_TABLE markers at appropriate places.
2489void WebAssemblyCFGStackifyImpl::placeMarkers(MachineFunction &MF) {
2490 // We allocate one more than the number of blocks in the function to
2491 // accommodate for the possible fake block we may insert at the end.
2492 ScopeTops.resize(MF.getNumBlockIDs() + 1);
2493 // Place the LOOP for MBB if MBB is the header of a loop.
2494 for (auto &MBB : MF)
2495 placeLoopMarker(MBB);
2496
2497 for (auto &MBB : MF) {
2498 if (MBB.isEHPad()) {
2499 // Place the TRY/TRY_TABLE for MBB if MBB is the EH pad of an exception.
2500 if (UsesWasmEH) {
2501 if (CLOpts.use_legacy_eh)
2502 placeTryMarker(MBB);
2503 else
2504 placeTryTableMarker(MBB);
2505 }
2506 } else {
2507 // Place the BLOCK for MBB if MBB is branched to from above.
2508 placeBlockMarker(MBB);
2509 }
2510 }
2511
2512 if (UsesWasmEH) {
2513 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
2514 // Add an 'unreachable' after 'end_try_table's.
2516 // Fix mismatches in unwind destinations induced by linearizing the code.
2517 // Run fixCatchUnwindMismatches() first so that fixCallUnwindMismatches()
2518 // will see and correct any new call/rethrow unwind mismatches introduced by
2519 // fixCatchUnwindMismatches().
2520 fixCatchUnwindMismatches(MF);
2521 fixCallUnwindMismatches(MF);
2522 // addUnreachableAfterTryTables and fixUnwindMismatches create new BBs, so
2523 // we need to recalculate ScopeTops.
2524 recalculateScopeTops(MF);
2525 }
2526}
2527
2528unsigned WebAssemblyCFGStackifyImpl::getBranchDepth(
2529 const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
2530 unsigned Depth = 0;
2531 for (auto X : reverse(Stack)) {
2532 if (X.first == MBB)
2533 break;
2534 ++Depth;
2535 }
2536 assert(Depth < Stack.size() && "Branch destination should be in scope");
2537 return Depth;
2538}
2539
2540unsigned WebAssemblyCFGStackifyImpl::getDelegateDepth(
2541 const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
2542 if (MBB == FakeCallerBB)
2543 return Stack.size();
2544 // Delegate's destination is either a catch or a another delegate BB. When the
2545 // destination is another delegate, we can compute the argument in the same
2546 // way as branches, because the target delegate BB only contains the single
2547 // delegate instruction.
2548 if (!MBB->isEHPad()) // Target is a delegate BB
2549 return getBranchDepth(Stack, MBB);
2550
2551 // When the delegate's destination is a catch BB, we need to use its
2552 // corresponding try's end_try BB because Stack contains each marker's end BB.
2553 // Also we need to check if the end marker instruction matches, because a
2554 // single BB can contain multiple end markers, like this:
2555 // bb:
2556 // END_BLOCK
2557 // END_TRY
2558 // END_BLOCK
2559 // END_TRY
2560 // ...
2561 //
2562 // In case of branches getting the immediate that targets any of these is
2563 // fine, but delegate has to exactly target the correct try.
2564 unsigned Depth = 0;
2565 const MachineInstr *EndTry = BeginToEnd[EHPadToTry[MBB]];
2566 for (auto X : reverse(Stack)) {
2567 if (X.first == EndTry->getParent() && X.second == EndTry)
2568 break;
2569 ++Depth;
2570 }
2571 assert(Depth < Stack.size() && "Delegate destination should be in scope");
2572 return Depth;
2573}
2574
2575unsigned WebAssemblyCFGStackifyImpl::getRethrowDepth(
2576 const SmallVectorImpl<EndMarkerInfo> &Stack,
2577 const MachineBasicBlock *EHPadToRethrow) {
2578 unsigned Depth = 0;
2579 for (auto X : reverse(Stack)) {
2580 const MachineInstr *End = X.second;
2581 if (End->getOpcode() == WebAssembly::END_TRY) {
2582 auto *EHPad = TryToEHPad[EndToBegin[End]];
2583 if (EHPadToRethrow == EHPad)
2584 break;
2585 }
2586 ++Depth;
2587 }
2588 assert(Depth < Stack.size() && "Rethrow destination should be in scope");
2589 return Depth;
2590}
2591
2592void WebAssemblyCFGStackifyImpl::rewriteDepthImmediates(MachineFunction &MF) {
2593 // Now rewrite references to basic blocks to be depth immediates.
2595
2596 auto RewriteOperands = [&](MachineInstr &MI) {
2597 // Rewrite MBB operands to be depth immediates.
2598 SmallVector<MachineOperand, 4> Ops(MI.operands());
2599 while (MI.getNumOperands() > 0)
2600 MI.removeOperand(MI.getNumOperands() - 1);
2601 for (auto MO : Ops) {
2602 if (MO.isMBB()) {
2603 if (MI.getOpcode() == WebAssembly::DELEGATE)
2604 MO = MachineOperand::CreateImm(getDelegateDepth(Stack, MO.getMBB()));
2605 else if (MI.getOpcode() == WebAssembly::RETHROW)
2606 MO = MachineOperand::CreateImm(getRethrowDepth(Stack, MO.getMBB()));
2607 else
2608 MO = MachineOperand::CreateImm(getBranchDepth(Stack, MO.getMBB()));
2609 }
2610 MI.addOperand(MF, MO);
2611 }
2612 };
2613
2614 for (auto &MBB : reverse(MF)) {
2615 for (MachineInstr &MI : llvm::reverse(MBB)) {
2616 switch (MI.getOpcode()) {
2617 case WebAssembly::BLOCK:
2618 case WebAssembly::TRY:
2619 assert(ScopeTops[Stack.back().first->getNumber()]->getNumber() <=
2620 MBB.getNumber() &&
2621 "Block/try/try_table marker should be balanced");
2622 Stack.pop_back();
2623 break;
2624
2625 case WebAssembly::TRY_TABLE:
2626 assert(ScopeTops[Stack.back().first->getNumber()]->getNumber() <=
2627 MBB.getNumber() &&
2628 "Block/try/try_table marker should be balanced");
2629 Stack.pop_back();
2630 RewriteOperands(MI);
2631 break;
2632
2633 case WebAssembly::LOOP:
2634 assert(Stack.back().first == &MBB && "Loop top should be balanced");
2635 Stack.pop_back();
2636 break;
2637
2638 case WebAssembly::END_BLOCK:
2639 case WebAssembly::END_TRY:
2640 case WebAssembly::END_TRY_TABLE:
2641 Stack.push_back(std::make_pair(&MBB, &MI));
2642 break;
2643
2644 case WebAssembly::END_LOOP:
2645 Stack.push_back(std::make_pair(EndToBegin[&MI]->getParent(), &MI));
2646 break;
2647
2648 case WebAssembly::DELEGATE:
2649 RewriteOperands(MI);
2650 Stack.push_back(std::make_pair(&MBB, &MI));
2651 break;
2652
2653 default:
2654 if (MI.isTerminator())
2655 RewriteOperands(MI);
2656 break;
2657 }
2658 }
2659 }
2660 assert(Stack.empty() && "Control flow should be balanced");
2661}
2662
2663void WebAssemblyCFGStackifyImpl::cleanupFunctionData(MachineFunction &MF) {
2664 if (FakeCallerBB)
2665 MF.deleteMachineBasicBlock(FakeCallerBB);
2666 AppendixBB = FakeCallerBB = CallerTrampolineBB = nullptr;
2667}
2668
2669bool WebAssemblyCFGStackifyImpl::runOnMachineFunction(MachineFunction &MF) {
2670 LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
2671 "********** Function: "
2672 << MF.getName() << '\n');
2673
2674 UsesWasmEH = MF.getFunction().hasPersonalityFn() &&
2676 ExceptionHandling::Wasm;
2677
2678 // Liveness is not tracked for VALUE_STACK physreg.
2680
2681 // Place the BLOCK/LOOP/TRY/TRY_TABLE markers to indicate the beginnings of
2682 // scopes.
2683 placeMarkers(MF);
2684
2685 // Remove unnecessary instructions possibly introduced by try/end_trys.
2686 if (UsesWasmEH && CLOpts.use_legacy_eh)
2687 removeUnnecessaryInstrs(MF);
2688
2689 // Convert MBB operands in terminators to relative depth immediates.
2690 rewriteDepthImmediates(MF);
2691
2692 // Fix up block/loop/try/try_table signatures at the end of the function to
2693 // conform to WebAssembly's rules.
2694 fixEndsAtEndOfFunction(MF);
2695
2696 // Add an end instruction at the end of the function body.
2697 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
2699
2700 cleanupFunctionData(MF);
2701
2702 MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
2703 return true;
2704}
2705
2706bool WebAssemblyCFGStackifyLegacy::runOnMachineFunction(MachineFunction &MF) {
2707 MachineDominatorTree &MDT =
2708 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
2709 MachineLoopInfo &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2710 WebAssemblyExceptionInfo &WEI =
2711 getAnalysis<WebAssemblyExceptionInfoWrapperPass>().getWEI();
2712 WebAssemblyCFGStackifyImpl Impl(
2713 MF.getSubtarget<WebAssemblySubtarget>().getCLOpts(), MDT, MLI, WEI);
2714 return Impl.runOnMachineFunction(MF);
2715}
2716
2717PreservedAnalyses
2724 WebAssemblyCFGStackifyImpl Impl(
2725 MF.getSubtarget<WebAssemblySubtarget>().getCLOpts(), MDT, MLI, WEI);
2726 return Impl.runOnMachineFunction(MF)
2729}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
#define _
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
SmallVector< MachineOperand, 4 > Cond
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
This file implements a map that provides insertion order iteration.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static std::string getBBName(const MachineBasicBlock *MBB)
static bool explicitlyBranchesTo(MachineBasicBlock *Pred, MachineBasicBlock *MBB)
Test whether Pred has any terminators explicitly branching to MBB, as opposed to falling through.
static void addUnreachableAfterTryTables(MachineFunction &MF, const WebAssemblyInstrInfo &TII)
static MachineBasicBlock::iterator getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet, const Container &AfterSet)
static void splitEndLoopBB(MachineBasicBlock *EndTryTableBB)
static void appendEndToFunction(MachineFunction &MF, const WebAssemblyInstrInfo &TII)
static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, MachineBasicBlock &Split)
static MachineBasicBlock::iterator getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet, const Container &AfterSet)
This file implements WebAssemblyException information analysis.
This file declares WebAssembly-specific per-machine-function information.
This file implements regions used in CFGSort and CFGStackify.
This file declares the WebAssembly-specific subclass of TargetSubtarget.
This file contains the declaration of the WebAssembly-specific type parsing utility functions.
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.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
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...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI bool hasEHPadSuccessor() const
bool isEHPad() const
Returns true if the block is a landing pad.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI bool isPredecessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a predecessor of this block.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
LLVM_ABI DebugLoc findPrevDebugLoc(instr_iterator MBBI)
Find the previous valid DebugLoc preceding MBBI, skipping any debug instructions.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
iterator_range< pred_iterator > predecessors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
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.
void push_back(MachineBasicBlock *MBB)
reverse_iterator rbegin()
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
void deleteMachineBasicBlock(MachineBasicBlock *MBB)
DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
Function & getFunction()
Return the LLVM function that this machine code represents.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
const MachineBasicBlock & back() const
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
const MachineBasicBlock & front() const
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
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 & addImm(int64_t Val) const
Add a new immediate 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.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
static MachineOperand CreateImm(int64_t Val)
void setTargetFlags(unsigned F)
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
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
Wrapper class representing virtual and physical registers.
Definition Register.h:20
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
WebAssemblyException * getExceptionFor(const MachineBasicBlock *MBB) const
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
const WebAssemblyOptions & getCLOpts() const
self_iterator getIterator()
Definition ilist_node.h:123
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isChild(const MachineInstr &MI, const WebAssemblyFunctionInfo &MFI)
Test whether MI is a child of some other node in an expression tree.
bool isArgument(unsigned Opc)
bool isCatchAll(unsigned Opc)
bool isMarker(unsigned Opc)
unsigned getCopyOpcodeForRegClass(const TargetRegisterClass *RC)
Returns the appropriate copy opcode for the given register class.
wasm::ValType toValType(MVT Type)
MachineInstr * findCatch(MachineBasicBlock *EHPad)
Find a catch instruction from an EH pad.
bool isCatch(unsigned Opc)
BlockType
Used as immediate MachineOperands for block signatures.
bool mayThrow(const MachineInstr &MI)
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
@ WASM_OPCODE_CATCH_ALL_REF
Definition Wasm.h:163
@ WASM_OPCODE_CATCH
Definition Wasm.h:160
@ WASM_OPCODE_CATCH_ALL
Definition Wasm.h:162
@ WASM_OPCODE_CATCH_REF
Definition Wasm.h:161
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.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
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 * createWebAssemblyCFGStackifyLegacyPass()
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320