1//===- TailDuplicator.cpp - Duplicate blocks into predecessors' tails -----===//
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// This utility class duplicates basic blocks ending in unconditional branches
10// into the tails of their predecessors.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/TailDuplicator.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/CodeGen/MachineBasicBlock.h"
23#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineInstr.h"
26#include "llvm/CodeGen/MachineInstrBuilder.h"
27#include "llvm/CodeGen/MachineOperand.h"
28#include "llvm/CodeGen/MachineRegisterInfo.h"
29#include "llvm/CodeGen/MachineSSAUpdater.h"
30#include "llvm/CodeGen/MachineSizeOpts.h"
31#include "llvm/CodeGen/TargetInstrInfo.h"
32#include "llvm/CodeGen/TargetRegisterInfo.h"
33#include "llvm/CodeGen/TargetSubtargetInfo.h"
34#include "llvm/IR/DebugLoc.h"
35#include "llvm/IR/Function.h"
36#include "llvm/IR/Module.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/raw_ostream.h"
41#include "llvm/Target/TargetMachine.h"
42#include <cassert>
43#include <iterator>
44#include <utility>
45
46using namespace llvm;
47
48#define DEBUG_TYPE "tailduplication"
49
50STATISTIC(NumTails, "Number of tails duplicated");
51STATISTIC(NumTailDups, "Number of tail duplicated blocks");
52STATISTIC(NumTailDupAdded,
53 "Number of instructions added due to tail duplication");
54STATISTIC(NumTailDupRemoved,
55 "Number of instructions removed due to tail duplication");
56STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
57STATISTIC(NumAddedPHIs, "Number of phis added");
58
59// Heuristic for tail duplication.
60static cl::opt<unsigned> TailDuplicateSize(
61 "tail-dup-size",
62 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(Val: 2),
63 cl::Hidden);
64
65static cl::opt<unsigned> TailDupIndirectBranchSize(
66 "tail-dup-indirect-size",
67 cl::desc("Maximum instructions to consider tail duplicating blocks that "
68 "end with indirect branches."), cl::init(Val: 20),
69 cl::Hidden);
70
71static cl::opt<unsigned>
72 TailDupPredSize("tail-dup-pred-size",
73 cl::desc("Maximum predecessors (maximum successors at the "
74 "same time) to consider tail duplicating blocks."),
75 cl::init(Val: 16), cl::Hidden);
76
77static cl::opt<unsigned>
78 TailDupSuccSize("tail-dup-succ-size",
79 cl::desc("Maximum successors (maximum predecessors at the "
80 "same time) to consider tail duplicating blocks."),
81 cl::init(Val: 16), cl::Hidden);
82
83static cl::opt<bool>
84 TailDupVerify("tail-dup-verify",
85 cl::desc("Verify sanity of PHI instructions during taildup"),
86 cl::init(Val: false), cl::Hidden);
87
88static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(Val: ~0U),
89 cl::Hidden);
90
91void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc,
92 const MachineBranchProbabilityInfo *MBPIin,
93 MBFIWrapper *MBFIin,
94 ProfileSummaryInfo *PSIin,
95 bool LayoutModeIn, unsigned TailDupSizeIn) {
96 MF = &MFin;
97 TII = MF->getSubtarget().getInstrInfo();
98 TRI = MF->getSubtarget().getRegisterInfo();
99 MRI = &MF->getRegInfo();
100 MBPI = MBPIin;
101 MBFI = MBFIin;
102 PSI = PSIin;
103 TailDupSize = TailDupSizeIn;
104
105 assert(MBPI != nullptr && "Machine Branch Probability Info required");
106
107 LayoutMode = LayoutModeIn;
108 this->PreRegAlloc = PreRegAlloc;
109}
110
111static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
112 for (MachineBasicBlock &MBB : llvm::drop_begin(RangeOrContainer&: MF)) {
113 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB.pred_begin(),
114 MBB.pred_end());
115 MachineBasicBlock::iterator MI = MBB.begin();
116 while (MI != MBB.end()) {
117 if (!MI->isPHI())
118 break;
119 for (MachineBasicBlock *PredBB : Preds) {
120 bool Found = false;
121 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
122 MachineBasicBlock *PHIBB = MI->getOperand(i: i + 1).getMBB();
123 if (PHIBB == PredBB) {
124 Found = true;
125 break;
126 }
127 }
128 if (!Found) {
129 dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": "
130 << *MI;
131 dbgs() << " missing input from predecessor "
132 << printMBBReference(MBB: *PredBB) << '\n';
133 llvm_unreachable(nullptr);
134 }
135 }
136
137 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
138 MachineBasicBlock *PHIBB = MI->getOperand(i: i + 1).getMBB();
139 if (CheckExtra && !Preds.count(key: PHIBB)) {
140 dbgs() << "Warning: malformed PHI in " << printMBBReference(MBB)
141 << ": " << *MI;
142 dbgs() << " extra input from predecessor "
143 << printMBBReference(MBB: *PHIBB) << '\n';
144 llvm_unreachable(nullptr);
145 }
146 if (PHIBB->getNumber() < 0) {
147 dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": "
148 << *MI;
149 dbgs() << " non-existing " << printMBBReference(MBB: *PHIBB) << '\n';
150 llvm_unreachable(nullptr);
151 }
152 }
153 ++MI;
154 }
155 }
156}
157
158/// Tail duplicate the block and cleanup.
159/// \p IsSimple - return value of isSimpleBB
160/// \p MBB - block to be duplicated
161/// \p ForcedLayoutPred - If non-null, treat this block as the layout
162/// predecessor, instead of using the ordering in MF
163/// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
164/// all Preds that received a copy of \p MBB.
165/// \p RemovalCallback - if non-null, called just before MBB is deleted.
166bool TailDuplicator::tailDuplicateAndUpdate(
167 bool IsSimple, MachineBasicBlock *MBB,
168 MachineBasicBlock *ForcedLayoutPred,
169 SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
170 function_ref<void(MachineBasicBlock *)> *RemovalCallback,
171 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
172 // Save the successors list.
173 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
174 MBB->succ_end());
175
176 SmallVector<MachineBasicBlock *, 8> TDBBs;
177 SmallVector<MachineInstr *, 16> Copies;
178 if (!tailDuplicate(IsSimple, TailBB: MBB, ForcedLayoutPred,
179 TDBBs, Copies, CandidatePtr))
180 return false;
181
182 ++NumTails;
183
184 SmallVector<MachineInstr *, 8> NewPHIs;
185 MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
186
187 // TailBB's immediate successors are now successors of those predecessors
188 // which duplicated TailBB. Add the predecessors as sources to the PHI
189 // instructions.
190 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
191 if (PreRegAlloc)
192 updateSuccessorsPHIs(FromBB: MBB, isDead, TDBBs, Succs);
193
194 // If it is dead, remove it.
195 if (isDead) {
196 NumTailDupRemoved += MBB->size();
197 removeDeadBlock(MBB, RemovalCallback);
198 ++NumDeadBlocks;
199 }
200
201 // Update SSA form.
202 if (!SSAUpdateVRs.empty()) {
203 for (Register VReg : SSAUpdateVRs) {
204 SSAUpdate.Initialize(V: VReg);
205
206 // If the original definition is still around, add it as an available
207 // value.
208 MachineBasicBlock *DefBB = MRI->getDefBlock(Reg: VReg);
209 if (DefBB)
210 SSAUpdate.AddAvailableValue(BB: DefBB, V: VReg);
211
212 // Add the new vregs as available values.
213 auto LI = SSAUpdateVals.find(Val: VReg);
214 for (std::pair<MachineBasicBlock *, Register> &J : LI->second) {
215 MachineBasicBlock *SrcBB = J.first;
216 Register SrcReg = J.second;
217 SSAUpdate.AddAvailableValue(BB: SrcBB, V: SrcReg);
218 }
219
220 SmallVector<MachineOperand *> DebugUses;
221 // Rewrite uses that are outside of the original def's block.
222 for (MachineOperand &UseMO :
223 llvm::make_early_inc_range(Range: MRI->use_operands(Reg: VReg))) {
224 MachineInstr *UseMI = UseMO.getParent();
225 // Rewrite debug uses last so that they can take advantage of any
226 // register mappings introduced by other users in its BB, since we
227 // cannot create new register definitions specifically for the debug
228 // instruction (as debug instructions should not affect CodeGen).
229 if (UseMI->isDebugValue()) {
230 DebugUses.push_back(Elt: &UseMO);
231 continue;
232 }
233 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
234 continue;
235 SSAUpdate.RewriteUse(U&: UseMO);
236 }
237 for (auto *UseMO : DebugUses) {
238 MachineInstr *UseMI = UseMO->getParent();
239 UseMO->setReg(
240 SSAUpdate.GetValueInMiddleOfBlock(BB: UseMI->getParent(), ExistingValueOnly: true));
241 }
242 }
243
244 SSAUpdateVRs.clear();
245 SSAUpdateVals.clear();
246 }
247
248 // Eliminate some of the copies inserted by tail duplication to maintain
249 // SSA form.
250 for (MachineInstr *Copy : Copies) {
251 if (!Copy->isCopy())
252 continue;
253 Register Dst = Copy->getOperand(i: 0).getReg();
254 Register Src = Copy->getOperand(i: 1).getReg();
255 if (MRI->hasOneNonDBGUse(RegNo: Src) &&
256 MRI->constrainRegClass(Reg: Src, RC: MRI->getRegClass(Reg: Dst))) {
257 // Copy is the only use. Do trivial copy propagation here.
258 MRI->replaceRegWith(FromReg: Dst, ToReg: Src);
259 Copy->eraseFromParent();
260 }
261 }
262
263 if (NewPHIs.size())
264 NumAddedPHIs += NewPHIs.size();
265
266 if (DuplicatedPreds)
267 *DuplicatedPreds = std::move(TDBBs);
268
269 return true;
270}
271
272/// Look for small blocks that are unconditionally branched to and do not fall
273/// through. Tail-duplicate their instructions into their predecessors to
274/// eliminate (dynamic) branches.
275bool TailDuplicator::tailDuplicateBlocks() {
276 bool MadeChange = false;
277
278 if (PreRegAlloc && TailDupVerify) {
279 LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
280 VerifyPHIs(MF&: *MF, CheckExtra: true);
281 }
282
283 for (MachineBasicBlock &MBB :
284 llvm::make_early_inc_range(Range: llvm::drop_begin(RangeOrContainer&: *MF))) {
285 if (NumTails == TailDupLimit)
286 break;
287
288 bool IsSimple = isSimpleBB(TailBB: &MBB);
289
290 if (!shouldTailDuplicate(IsSimple, TailBB&: MBB))
291 continue;
292
293 MadeChange |= tailDuplicateAndUpdate(IsSimple, MBB: &MBB, ForcedLayoutPred: nullptr);
294 }
295
296 if (PreRegAlloc && TailDupVerify)
297 VerifyPHIs(MF&: *MF, CheckExtra: false);
298
299 return MadeChange;
300}
301
302static bool isDefLiveOut(Register Reg, MachineBasicBlock *BB,
303 const MachineRegisterInfo *MRI) {
304 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
305 if (UseMI.isDebugValue())
306 continue;
307 if (UseMI.getParent() != BB)
308 return true;
309 }
310 return false;
311}
312
313static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
314 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
315 if (MI->getOperand(i: i + 1).getMBB() == SrcBB)
316 return i;
317 return 0;
318}
319
320// Remember which registers are used by phis in this block. This is
321// used to determine which registers are liveout while modifying the
322// block (which is why we need to copy the information).
323static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
324 DenseSet<Register> *UsedByPhi) {
325 for (const auto &MI : BB) {
326 if (!MI.isPHI())
327 break;
328 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
329 Register SrcReg = MI.getOperand(i).getReg();
330 UsedByPhi->insert(V: SrcReg);
331 }
332 }
333}
334
335/// Add a definition and source virtual registers pair for SSA update.
336void TailDuplicator::addSSAUpdateEntry(Register OrigReg, Register NewReg,
337 MachineBasicBlock *BB) {
338 auto LI = SSAUpdateVals.find(Val: OrigReg);
339 if (LI != SSAUpdateVals.end())
340 LI->second.push_back(x: std::make_pair(x&: BB, y&: NewReg));
341 else {
342 AvailableValsTy Vals;
343 Vals.push_back(x: std::make_pair(x&: BB, y&: NewReg));
344 SSAUpdateVals.insert(KV: std::make_pair(x&: OrigReg, y&: Vals));
345 SSAUpdateVRs.push_back(Elt: OrigReg);
346 }
347}
348
349/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
350/// source register that's contributed by PredBB and update SSA update map.
351void TailDuplicator::processPHI(
352 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
353 DenseMap<Register, RegSubRegPair> &LocalVRMap,
354 SmallVectorImpl<std::pair<Register, RegSubRegPair>> &Copies,
355 const DenseSet<Register> &RegsUsedByPhi, bool Remove) {
356 Register DefReg = MI->getOperand(i: 0).getReg();
357 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, SrcBB: PredBB);
358 assert(SrcOpIdx && "Unable to find matching PHI source?");
359 Register SrcReg = MI->getOperand(i: SrcOpIdx).getReg();
360 unsigned SrcSubReg = MI->getOperand(i: SrcOpIdx).getSubReg();
361 const TargetRegisterClass *RC = MRI->getRegClass(Reg: DefReg);
362 LocalVRMap.try_emplace(Key: DefReg, Args&: SrcReg, Args&: SrcSubReg);
363
364 // Insert a copy from source to the end of the block. The def register is the
365 // available value liveout of the block.
366 Register NewDef = MRI->createVirtualRegister(RegClass: RC);
367 Copies.push_back(Elt: std::make_pair(x&: NewDef, y: RegSubRegPair(SrcReg, SrcSubReg)));
368 if (!Remove) {
369 // Informing MachineSSAUpdater that DefReg -> NewDef in PredBB is not
370 // correct, because it could be used to update on other PHI. But the DefReg
371 // in the COPY will be properly updated by MachineSSAUpdater.
372 MI->getOperand(i: SrcOpIdx).setReg(NewDef);
373 MI->getOperand(i: SrcOpIdx).setSubReg(0);
374 return;
375 }
376 if (isDefLiveOut(Reg: DefReg, BB: TailBB, MRI) || RegsUsedByPhi.count(V: DefReg))
377 addSSAUpdateEntry(OrigReg: DefReg, NewReg: NewDef, BB: PredBB);
378
379 MI->removePHIIncomingValueFor(MBB: *PredBB);
380
381 if (MI->getNumOperands() == 1 && !TailBB->hasAddressTaken())
382 MI->eraseFromParent();
383 else if (MI->getNumOperands() == 1)
384 MI->setDesc(TII->get(Opcode: TargetOpcode::IMPLICIT_DEF));
385}
386
387/// Duplicate a TailBB instruction to PredBB and update
388/// the source operands due to earlier PHI translation.
389void TailDuplicator::duplicateInstruction(
390 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
391 DenseMap<Register, RegSubRegPair> &LocalVRMap,
392 const DenseSet<Register> &UsedByPhi) {
393 // Allow duplication of CFI instructions.
394 if (MI->isCFIInstruction()) {
395 BuildMI(BB&: *PredBB, I: PredBB->end(), MIMD: PredBB->findDebugLoc(MBBI: PredBB->begin()),
396 MCID: TII->get(Opcode: TargetOpcode::CFI_INSTRUCTION))
397 .addCFIIndex(CFIIndex: MI->getOperand(i: 0).getCFIIndex())
398 .setMIFlags(MI->getFlags());
399 return;
400 }
401 MachineInstr &NewMI = TII->duplicate(MBB&: *PredBB, InsertBefore: PredBB->end(), Orig: *MI);
402 if (!PreRegAlloc)
403 return;
404 for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) {
405 MachineOperand &MO = NewMI.getOperand(i);
406 if (!MO.isReg())
407 continue;
408 Register Reg = MO.getReg();
409 if (!Reg.isVirtual())
410 continue;
411 if (MO.isDef()) {
412 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
413 Register NewReg = MRI->createVirtualRegister(RegClass: RC);
414 MO.setReg(NewReg);
415 LocalVRMap.try_emplace(Key: Reg, Args&: NewReg, Args: 0);
416 if (isDefLiveOut(Reg, BB: TailBB, MRI) || UsedByPhi.count(V: Reg))
417 addSSAUpdateEntry(OrigReg: Reg, NewReg, BB: PredBB);
418 continue;
419 }
420 auto VI = LocalVRMap.find(Val: Reg);
421 if (VI == LocalVRMap.end())
422 continue;
423 // Need to make sure that the register class of the mapped register
424 // will satisfy the constraints of the class of the register being
425 // replaced.
426 auto *OrigRC = MRI->getRegClass(Reg);
427 auto *MappedRC = MRI->getRegClass(Reg: VI->second.Reg);
428 const TargetRegisterClass *ConstrRC;
429 if (VI->second.SubReg != 0) {
430 ConstrRC =
431 TRI->getMatchingSuperRegClass(A: MappedRC, B: OrigRC, Idx: VI->second.SubReg);
432 if (ConstrRC) {
433 // The actual constraining (as in "find appropriate new class")
434 // is done by getMatchingSuperRegClass, so now we only need to
435 // change the class of the mapped register.
436 MRI->setRegClass(Reg: VI->second.Reg, RC: ConstrRC);
437 }
438 } else {
439 // For mapped registers that do not have sub-registers, simply
440 // restrict their class to match the original one.
441
442 // We don't want debug instructions affecting the resulting code so
443 // if we're cloning a debug instruction then just use MappedRC
444 // rather than constraining the register class further.
445 ConstrRC = NewMI.isDebugInstr()
446 ? MappedRC
447 : MRI->constrainRegClass(Reg: VI->second.Reg, RC: OrigRC);
448 }
449
450 if (ConstrRC) {
451 // If the class constraining succeeded, we can simply replace
452 // the old register with the mapped one.
453 MO.setReg(VI->second.Reg);
454 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
455 // sub-register, we need to compose the sub-register indices.
456 MO.setSubReg(
457 TRI->composeSubRegIndices(a: VI->second.SubReg, b: MO.getSubReg()));
458 } else {
459 // The direct replacement is not possible, due to failing register
460 // class constraints. An explicit COPY is necessary. Create one
461 // that can be reused.
462 Register NewReg = MRI->createVirtualRegister(RegClass: OrigRC);
463 BuildMI(BB&: *PredBB, I&: NewMI, MIMD: NewMI.getDebugLoc(), MCID: TII->get(Opcode: TargetOpcode::COPY),
464 DestReg: NewReg)
465 .addReg(RegNo: VI->second.Reg, Flags: {}, SubReg: VI->second.SubReg);
466 LocalVRMap.erase(I: VI);
467 LocalVRMap.try_emplace(Key: Reg, Args&: NewReg, Args: 0);
468 MO.setReg(NewReg);
469 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
470 // is equivalent to the whole register Reg. Hence, Reg:subreg
471 // is same as NewReg:subreg, so keep the sub-register index
472 // unchanged.
473 }
474 // Clear any kill flags from this operand. The new register could
475 // have uses after this one, so kills are not valid here.
476 MO.setIsKill(false);
477 }
478}
479
480/// After FromBB is tail duplicated into its predecessor blocks, the successors
481/// have gained new predecessors. Update the PHI instructions in them
482/// accordingly.
483void TailDuplicator::updateSuccessorsPHIs(
484 MachineBasicBlock *FromBB, bool isDead,
485 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
486 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
487 for (MachineBasicBlock *SuccBB : Succs) {
488 for (MachineInstr &MI : *SuccBB) {
489 if (!MI.isPHI())
490 break;
491 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
492 unsigned Idx = 0;
493 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
494 MachineOperand &MO = MI.getOperand(i: i + 1);
495 if (MO.getMBB() == FromBB) {
496 Idx = i;
497 break;
498 }
499 }
500
501 assert(Idx != 0);
502 MachineOperand &MO0 = MI.getOperand(i: Idx);
503 Register Reg = MO0.getReg();
504 if (isDead) {
505 // Folded into the previous BB.
506 // There could be duplicate phi source entries. FIXME: Should sdisel
507 // or earlier pass fixed this?
508 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
509 MachineOperand &MO = MI.getOperand(i: i + 1);
510 if (MO.getMBB() == FromBB) {
511 MI.removeOperand(OpNo: i + 1);
512 MI.removeOperand(OpNo: i);
513 }
514 }
515 } else
516 Idx = 0;
517
518 // If Idx is set, the operands at Idx and Idx+1 must be removed.
519 // We reuse the location to avoid expensive removeOperand calls.
520
521 auto LI = SSAUpdateVals.find(Val: Reg);
522 if (LI != SSAUpdateVals.end()) {
523 // This register is defined in the tail block.
524 for (const std::pair<MachineBasicBlock *, Register> &J : LI->second) {
525 MachineBasicBlock *SrcBB = J.first;
526 // If we didn't duplicate a bb into a particular predecessor, we
527 // might still have added an entry to SSAUpdateVals to correcly
528 // recompute SSA. If that case, avoid adding a dummy extra argument
529 // this PHI.
530 if (!SrcBB->isSuccessor(MBB: SuccBB))
531 continue;
532
533 Register SrcReg = J.second;
534 if (Idx != 0) {
535 MI.getOperand(i: Idx).setReg(SrcReg);
536 MI.getOperand(i: Idx + 1).setMBB(SrcBB);
537 Idx = 0;
538 } else {
539 MIB.addReg(RegNo: SrcReg).addMBB(MBB: SrcBB);
540 }
541 }
542 } else {
543 // Live in tail block, must also be live in predecessors.
544 for (MachineBasicBlock *SrcBB : TDBBs) {
545 if (Idx != 0) {
546 MI.getOperand(i: Idx).setReg(Reg);
547 MI.getOperand(i: Idx + 1).setMBB(SrcBB);
548 Idx = 0;
549 } else {
550 MIB.addReg(RegNo: Reg).addMBB(MBB: SrcBB);
551 }
552 }
553 }
554 if (Idx != 0) {
555 MI.removeOperand(OpNo: Idx + 1);
556 MI.removeOperand(OpNo: Idx);
557 }
558 }
559 }
560}
561
562/// Determine if it is profitable to duplicate this block.
563bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
564 MachineBasicBlock &TailBB) {
565 // When doing tail-duplication during layout, the block ordering is in flux,
566 // so canFallThrough returns a result based on incorrect information and
567 // should just be ignored.
568 if (!LayoutMode && TailBB.canFallThrough())
569 return false;
570
571 // Don't try to tail-duplicate single-block loops.
572 if (TailBB.isSuccessor(MBB: &TailBB))
573 return false;
574
575 // Set the limit on the cost to duplicate. When optimizing for size,
576 // duplicate only one, because one branch instruction can be eliminated to
577 // compensate for the duplication.
578 unsigned MaxDuplicateCount;
579 if (TailDupSize == 0)
580 MaxDuplicateCount = TailDuplicateSize;
581 else
582 MaxDuplicateCount = TailDupSize;
583 if (llvm::shouldOptimizeForSize(MBB: &TailBB, PSI, MBFIWrapper: MBFI))
584 MaxDuplicateCount = 1;
585
586 // If the block to be duplicated ends in an unanalyzable fallthrough, don't
587 // duplicate it.
588 // A similar check is necessary in MachineBlockPlacement to make sure pairs of
589 // blocks with unanalyzable fallthrough get layed out contiguously.
590 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
591 SmallVector<MachineOperand, 4> PredCond;
592 if (TII->analyzeBranch(MBB&: TailBB, TBB&: PredTBB, FBB&: PredFBB, Cond&: PredCond) &&
593 TailBB.canFallThrough())
594 return false;
595
596 // If the target has hardware branch prediction that can handle indirect
597 // branches, duplicating them can often make them predictable when there
598 // are common paths through the code. The limit needs to be high enough
599 // to allow undoing the effects of tail merging and other optimizations
600 // that rearrange the predecessors of the indirect branch.
601
602 bool HasIndirectbr = false;
603 bool HasComputedGoto = false;
604 if (!TailBB.empty()) {
605 HasIndirectbr = TailBB.back().isIndirectBranch();
606 HasComputedGoto = TailBB.terminatorIsComputedGotoWithSuccessors();
607 }
608
609 if (HasIndirectbr && PreRegAlloc)
610 MaxDuplicateCount = TailDupIndirectBranchSize;
611
612 // Allow higher limits when the block has computed-gotos and running after
613 // register allocation. NB. This basically unfactors computed gotos that were
614 // factored early on in the compilation process to speed up edge based data
615 // flow. If we do not unfactor them again, it can seriously pessimize code
616 // with many computed jumps in the source code, such as interpreters.
617 // Therefore we do not restrict the computed gotos.
618 if (HasComputedGoto && !PreRegAlloc)
619 MaxDuplicateCount = std::max(a: MaxDuplicateCount, b: 10u);
620
621 // Check the instructions in the block to determine whether tail-duplication
622 // is invalid or unlikely to be profitable.
623 unsigned InstrCount = 0;
624 unsigned NumPhis = 0;
625 for (MachineInstr &MI : TailBB) {
626 // Non-duplicable things shouldn't be tail-duplicated.
627 // CFI instructions are marked as non-duplicable, because Darwin compact
628 // unwind info emission can't handle multiple prologue setups. In case of
629 // DWARF, allow them be duplicated, so that their existence doesn't prevent
630 // tail duplication of some basic blocks, that would be duplicated otherwise.
631 if (MI.isNotDuplicable() && (TailBB.getParent()
632 ->getFunction()
633 .getParent()
634 ->getTargetTriple()
635 .isOSDarwin() ||
636 !MI.isCFIInstruction()))
637 return false;
638
639 // Convergent instructions can be duplicated only if doing so doesn't add
640 // new control dependencies, which is what we're going to do here.
641 if (MI.isConvergent())
642 return false;
643
644 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
645 // A return may expand into a lot more instructions (e.g. reload of callee
646 // saved registers) after PEI.
647 if (PreRegAlloc && MI.isReturn())
648 return false;
649
650 // Avoid duplicating calls before register allocation. Calls presents a
651 // barrier to register allocation so duplicating them may end up increasing
652 // spills.
653 if (PreRegAlloc && MI.isCall())
654 return false;
655
656 // TailDuplicator::appendCopies will erroneously place COPYs after
657 // INLINEASM_BR instructions after 4b0aa5724fea, which demonstrates the same
658 // bug that was fixed in f7a53d82c090.
659 // FIXME: Use findPHICopyInsertPoint() to find the correct insertion point
660 // for the COPY when replacing PHIs.
661 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
662 return false;
663
664 if (MI.isBundle())
665 InstrCount += MI.getBundleSize();
666 else if (!MI.isPHI() && !MI.isMetaInstruction())
667 InstrCount += 1;
668
669 if (InstrCount > MaxDuplicateCount)
670 return false;
671 NumPhis += MI.isPHI();
672 }
673
674 // Duplicating a BB which has both multiple predecessors and successors will
675 // may cause huge amount of PHI nodes. If we want to remove this limitation,
676 // we have to address https://github.com/llvm/llvm-project/issues/78578.
677 if (PreRegAlloc && TailBB.pred_size() > TailDupPredSize &&
678 TailBB.succ_size() > TailDupSuccSize) {
679 // If TailBB or any of its successors contains a phi, we may have to add a
680 // large number of additional phis with additional incoming values.
681 if (NumPhis != 0 || any_of(Range: TailBB.successors(), P: [](MachineBasicBlock *MBB) {
682 return any_of(Range&: *MBB, P: [](MachineInstr &MI) { return MI.isPHI(); });
683 }))
684 return false;
685 }
686
687 // Check if any of the successors of TailBB has a PHI node in which the
688 // value corresponding to TailBB uses a subregister.
689 // If a phi node uses a register paired with a subregister, the actual
690 // "value type" of the phi may differ from the type of the register without
691 // any subregisters. Due to a bug, tail duplication may add a new operand
692 // without a necessary subregister, producing an invalid code. This is
693 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
694 // Disable tail duplication for this case for now, until the problem is
695 // fixed.
696 for (auto *SB : TailBB.successors()) {
697 for (auto &I : *SB) {
698 if (!I.isPHI())
699 break;
700 unsigned Idx = getPHISrcRegOpIdx(MI: &I, SrcBB: &TailBB);
701 assert(Idx != 0);
702 MachineOperand &PU = I.getOperand(i: Idx);
703 if (PU.getSubReg() != 0)
704 return false;
705 }
706 }
707
708 if (HasIndirectbr && PreRegAlloc)
709 return true;
710
711 if (IsSimple)
712 return true;
713
714 if (!PreRegAlloc)
715 return true;
716
717 return canCompletelyDuplicateBB(BB&: TailBB);
718}
719
720/// True if this BB has only one unconditional jump.
721bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
722 if (TailBB->succ_size() != 1)
723 return false;
724 if (TailBB->pred_empty())
725 return false;
726 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr(SkipPseudoOp: true);
727 if (I == TailBB->end())
728 return true;
729 return I->isUnconditionalBranch();
730}
731
732static bool bothUsedInPHI(const MachineBasicBlock &A,
733 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
734 for (MachineBasicBlock *BB : A.successors())
735 if (SuccsB.count(Ptr: BB) && !BB->empty() && BB->begin()->isPHI())
736 return true;
737
738 return false;
739}
740
741bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
742 for (MachineBasicBlock *PredBB : BB.predecessors()) {
743 if (PredBB->succ_size() > 1)
744 return false;
745
746 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
747 SmallVector<MachineOperand, 4> PredCond;
748 if (TII->analyzeBranch(MBB&: *PredBB, TBB&: PredTBB, FBB&: PredFBB, Cond&: PredCond))
749 return false;
750
751 if (!PredCond.empty())
752 return false;
753 }
754 return true;
755}
756
757bool TailDuplicator::duplicateSimpleBB(
758 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
759 const DenseSet<Register> &UsedByPhi) {
760 SmallPtrSet<MachineBasicBlock *, 8> Succs(llvm::from_range,
761 TailBB->successors());
762 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->predecessors());
763 bool Changed = false;
764 for (MachineBasicBlock *PredBB : Preds) {
765 if (PredBB->hasEHPadSuccessor() || PredBB->mayHaveInlineAsmBr())
766 continue;
767
768 if (bothUsedInPHI(A: *PredBB, SuccsB: Succs))
769 continue;
770
771 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
772 SmallVector<MachineOperand, 4> PredCond;
773 if (TII->analyzeBranch(MBB&: *PredBB, TBB&: PredTBB, FBB&: PredFBB, Cond&: PredCond))
774 continue;
775
776 Changed = true;
777 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
778 << "From simple Succ: " << *TailBB);
779
780 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
781 MachineBasicBlock *NextBB = PredBB->getNextNode();
782
783 // Make PredFBB explicit.
784 if (PredCond.empty())
785 PredFBB = PredTBB;
786
787 // Make fall through explicit.
788 if (!PredTBB)
789 PredTBB = NextBB;
790 if (!PredFBB)
791 PredFBB = NextBB;
792
793 // Redirect
794 if (PredFBB == TailBB)
795 PredFBB = NewTarget;
796 if (PredTBB == TailBB)
797 PredTBB = NewTarget;
798
799 // Make the branch unconditional if possible
800 if (PredTBB == PredFBB) {
801 PredCond.clear();
802 PredFBB = nullptr;
803 }
804
805 // Avoid adding fall through branches.
806 if (PredFBB == NextBB)
807 PredFBB = nullptr;
808 if (PredTBB == NextBB && PredFBB == nullptr)
809 PredTBB = nullptr;
810
811 auto DL = PredBB->findBranchDebugLoc();
812 TII->removeBranch(MBB&: *PredBB);
813
814 if (!PredBB->isSuccessor(MBB: NewTarget))
815 PredBB->replaceSuccessor(Old: TailBB, New: NewTarget);
816 else {
817 PredBB->removeSuccessor(Succ: TailBB, NormalizeSuccProbs: true);
818 assert(PredBB->succ_size() <= 1);
819 }
820
821 if (PredTBB)
822 TII->insertBranch(MBB&: *PredBB, TBB: PredTBB, FBB: PredFBB, Cond: PredCond, DL);
823
824 TDBBs.push_back(Elt: PredBB);
825 }
826 return Changed;
827}
828
829bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
830 MachineBasicBlock *PredBB) {
831 // EH edges are ignored by analyzeBranch.
832 if (PredBB->succ_size() > 1)
833 return false;
834
835 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
836 SmallVector<MachineOperand, 4> PredCond;
837 if (TII->analyzeBranch(MBB&: *PredBB, TBB&: PredTBB, FBB&: PredFBB, Cond&: PredCond))
838 return false;
839 if (!PredCond.empty())
840 return false;
841 // FIXME: This is overly conservative; it may be ok to relax this in the
842 // future under more specific conditions. If TailBB is an INLINEASM_BR
843 // indirect target, we need to see if the edge from PredBB to TailBB is from
844 // an INLINEASM_BR in PredBB, and then also if that edge was from the
845 // indirect target list, fallthrough/default target, or potentially both. If
846 // it's both, TailDuplicator::tailDuplicate will remove the edge, corrupting
847 // the successor list in PredBB and predecessor list in TailBB.
848 if (TailBB->isInlineAsmBrIndirectTarget())
849 return false;
850 return true;
851}
852
853/// If it is profitable, duplicate TailBB's contents in each
854/// of its predecessors.
855/// \p IsSimple result of isSimpleBB
856/// \p TailBB Block to be duplicated.
857/// \p ForcedLayoutPred When non-null, use this block as the layout predecessor
858/// instead of the previous block in MF's order.
859/// \p TDBBs A vector to keep track of all blocks tail-duplicated
860/// into.
861/// \p Copies A vector of copy instructions inserted. Used later to
862/// walk all the inserted copies and remove redundant ones.
863bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
864 MachineBasicBlock *ForcedLayoutPred,
865 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
866 SmallVectorImpl<MachineInstr *> &Copies,
867 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
868 LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
869 << '\n');
870
871 bool ShouldUpdateTerminators = TailBB->canFallThrough();
872
873 DenseSet<Register> UsedByPhi;
874 getRegsUsedByPHIs(BB: *TailBB, UsedByPhi: &UsedByPhi);
875
876 if (IsSimple)
877 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi);
878
879 // Iterate through all the unique predecessors and tail-duplicate this
880 // block into them, if possible. Copying the list ahead of time also
881 // avoids trouble with the predecessor list reallocating.
882 bool Changed = false;
883 SmallSetVector<MachineBasicBlock *, 8> Preds;
884 if (CandidatePtr)
885 Preds.insert_range(R&: *CandidatePtr);
886 else
887 Preds.insert_range(R: TailBB->predecessors());
888
889 for (MachineBasicBlock *PredBB : Preds) {
890 assert(TailBB != PredBB &&
891 "Single-block loop should have been rejected earlier!");
892
893 if (!canTailDuplicate(TailBB, PredBB))
894 continue;
895
896 // Don't duplicate into a fall-through predecessor (at least for now).
897 // If profile is available, findDuplicateCandidates can choose better
898 // fall-through predecessor.
899 if (!(MF->getFunction().hasProfileData() && LayoutMode)) {
900 bool IsLayoutSuccessor = false;
901 if (ForcedLayoutPred)
902 IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
903 else if (PredBB->isLayoutSuccessor(MBB: TailBB) && PredBB->canFallThrough())
904 IsLayoutSuccessor = true;
905 if (IsLayoutSuccessor)
906 continue;
907 }
908
909 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
910 << "From Succ: " << *TailBB);
911
912 TDBBs.push_back(Elt: PredBB);
913
914 // Remove PredBB's unconditional branch.
915 TII->removeBranch(MBB&: *PredBB);
916
917 // Clone the contents of TailBB into PredBB.
918 DenseMap<Register, RegSubRegPair> LocalVRMap;
919 SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
920 for (MachineInstr &MI : llvm::make_early_inc_range(Range&: *TailBB)) {
921 if (MI.isPHI()) {
922 // Replace the uses of the def of the PHI with the register coming
923 // from PredBB.
924 processPHI(MI: &MI, TailBB, PredBB, LocalVRMap, Copies&: CopyInfos, RegsUsedByPhi: UsedByPhi, Remove: true);
925 } else {
926 // Replace def of virtual registers with new registers, and update
927 // uses with PHI source register or the new registers.
928 duplicateInstruction(MI: &MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
929 }
930 }
931 appendCopies(MBB: PredBB, CopyInfos, Copies);
932
933 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
934
935 // Update the CFG.
936 PredBB->removeSuccessor(I: PredBB->succ_begin());
937 assert(PredBB->succ_empty() &&
938 "TailDuplicate called on block with multiple successors!");
939 for (MachineBasicBlock *Succ : TailBB->successors())
940 PredBB->addSuccessor(Succ, Prob: MBPI->getEdgeProbability(Src: TailBB, Dst: Succ));
941
942 // Update branches in pred to jump to tail's layout successor if needed.
943 if (ShouldUpdateTerminators)
944 PredBB->updateTerminator(PreviousLayoutSuccessor: TailBB->getNextNode());
945
946 Changed = true;
947 ++NumTailDups;
948 }
949
950 // If TailBB was duplicated into all its predecessors except for the prior
951 // block, which falls through unconditionally, move the contents of this
952 // block into the prior block.
953 MachineBasicBlock *PrevBB = ForcedLayoutPred;
954 if (!PrevBB)
955 PrevBB = &*std::prev(x: TailBB->getIterator());
956 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
957 SmallVector<MachineOperand, 4> PriorCond;
958 // This has to check PrevBB->succ_size() because EH edges are ignored by
959 // analyzeBranch.
960 if (PrevBB->succ_size() == 1 &&
961 // Layout preds are not always CFG preds. Check.
962 *PrevBB->succ_begin() == TailBB &&
963 !TII->analyzeBranch(MBB&: *PrevBB, TBB&: PriorTBB, FBB&: PriorFBB, Cond&: PriorCond) &&
964 PriorCond.empty() &&
965 (!PriorTBB || PriorTBB == TailBB) &&
966 TailBB->pred_size() == 1 &&
967 !TailBB->hasAddressTaken()) {
968 LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
969 << "From MBB: " << *TailBB);
970 // There may be a branch to the layout successor. This is unlikely but it
971 // happens. The correct thing to do is to remove the branch before
972 // duplicating the instructions in all cases.
973 bool RemovedBranches = TII->removeBranch(MBB&: *PrevBB) != 0;
974
975 // If there are still tail instructions, abort the merge
976 if (PrevBB->getFirstTerminator() == PrevBB->end()) {
977 if (PreRegAlloc) {
978 DenseMap<Register, RegSubRegPair> LocalVRMap;
979 SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
980 MachineBasicBlock::iterator I = TailBB->begin();
981 // Process PHI instructions first.
982 while (I != TailBB->end() && I->isPHI()) {
983 // Replace the uses of the def of the PHI with the register coming
984 // from PredBB.
985 MachineInstr *MI = &*I++;
986 processPHI(MI, TailBB, PredBB: PrevBB, LocalVRMap, Copies&: CopyInfos, RegsUsedByPhi: UsedByPhi,
987 Remove: true);
988 }
989
990 // Now copy the non-PHI instructions.
991 while (I != TailBB->end()) {
992 // Replace def of virtual registers with new registers, and update
993 // uses with PHI source register or the new registers.
994 MachineInstr *MI = &*I++;
995 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
996 duplicateInstruction(MI, TailBB, PredBB: PrevBB, LocalVRMap, UsedByPhi);
997 MI->eraseFromParent();
998 }
999 appendCopies(MBB: PrevBB, CopyInfos, Copies);
1000 } else {
1001 TII->removeBranch(MBB&: *PrevBB);
1002 // No PHIs to worry about, just splice the instructions over.
1003 PrevBB->splice(Where: PrevBB->end(), Other: TailBB, From: TailBB->begin(), To: TailBB->end());
1004 }
1005 PrevBB->removeSuccessor(I: PrevBB->succ_begin());
1006 assert(PrevBB->succ_empty());
1007 PrevBB->transferSuccessors(FromMBB: TailBB);
1008
1009 // Update branches in PrevBB based on Tail's layout successor.
1010 if (ShouldUpdateTerminators)
1011 PrevBB->updateTerminator(PreviousLayoutSuccessor: TailBB->getNextNode());
1012
1013 TDBBs.push_back(Elt: PrevBB);
1014 Changed = true;
1015 } else {
1016 LLVM_DEBUG(dbgs() << "Abort merging blocks, the predecessor still "
1017 "contains terminator instructions");
1018 // Return early if no changes were made
1019 if (!Changed)
1020 return RemovedBranches;
1021 }
1022 Changed |= RemovedBranches;
1023 }
1024
1025 // If this is after register allocation, there are no phis to fix.
1026 if (!PreRegAlloc)
1027 return Changed;
1028
1029 // If we made no changes so far, we are safe.
1030 if (!Changed)
1031 return Changed;
1032
1033 // Handle the nasty case in that we duplicated a block that is part of a loop
1034 // into some but not all of its predecessors. For example:
1035 // 1 -> 2 <-> 3 |
1036 // \ |
1037 // \---> rest |
1038 // if we duplicate 2 into 1 but not into 3, we end up with
1039 // 12 -> 3 <-> 2 -> rest |
1040 // \ / |
1041 // \----->-----/ |
1042 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
1043 // with a phi in 3 (which now dominates 2).
1044 // What we do here is introduce a copy in 3 of the register defined by the
1045 // phi, just like when we are duplicating 2 into 3, but we don't copy any
1046 // real instructions or remove the 3 -> 2 edge from the phi in 2.
1047 for (MachineBasicBlock *PredBB : Preds) {
1048 if (is_contained(Range&: TDBBs, Element: PredBB))
1049 continue;
1050
1051 // EH edges
1052 if (PredBB->succ_size() != 1)
1053 continue;
1054
1055 DenseMap<Register, RegSubRegPair> LocalVRMap;
1056 SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
1057 // Process PHI instructions first.
1058 for (MachineInstr &MI : make_early_inc_range(Range: TailBB->phis())) {
1059 // Replace the uses of the def of the PHI with the register coming
1060 // from PredBB.
1061 processPHI(MI: &MI, TailBB, PredBB, LocalVRMap, Copies&: CopyInfos, RegsUsedByPhi: UsedByPhi, Remove: false);
1062 }
1063 appendCopies(MBB: PredBB, CopyInfos, Copies);
1064 }
1065
1066 return Changed;
1067}
1068
1069/// At the end of the block \p MBB generate COPY instructions between registers
1070/// described by \p CopyInfos. Append resulting instructions to \p Copies.
1071void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
1072 SmallVectorImpl<std::pair<Register, RegSubRegPair>> &CopyInfos,
1073 SmallVectorImpl<MachineInstr*> &Copies) {
1074 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1075 const MCInstrDesc &CopyD = TII->get(Opcode: TargetOpcode::COPY);
1076 for (auto &CI : CopyInfos) {
1077 auto C = BuildMI(BB&: *MBB, I: Loc, MIMD: DebugLoc(), MCID: CopyD, DestReg: CI.first)
1078 .addReg(RegNo: CI.second.Reg, Flags: {}, SubReg: CI.second.SubReg);
1079 Copies.push_back(Elt: C);
1080 }
1081}
1082
1083/// Remove the specified dead machine basic block from the function, updating
1084/// the CFG.
1085void TailDuplicator::removeDeadBlock(
1086 MachineBasicBlock *MBB,
1087 function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
1088 assert(MBB->pred_empty() && "MBB must be dead!");
1089 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
1090
1091 MachineFunction *MF = MBB->getParent();
1092 // Update the call info.
1093 for (const MachineInstr &MI : *MBB)
1094 if (MI.shouldUpdateAdditionalCallInfo())
1095 MF->eraseAdditionalCallInfo(MI: &MI);
1096
1097 if (RemovalCallback)
1098 (*RemovalCallback)(MBB);
1099
1100 // Remove all successors.
1101 while (!MBB->succ_empty())
1102 MBB->removeSuccessor(I: MBB->succ_end() - 1);
1103
1104 // Remove the block.
1105 MBB->eraseFromParent();
1106}
1107