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