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