1 //===- TailDuplicator.cpp - Duplicate blocks into predecessors' tails -----===//
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
7 //===----------------------------------------------------------------------===//
9 // This utility class duplicates basic blocks ending in unconditional branches
10 // into the tails of their predecessors.
12 //===----------------------------------------------------------------------===//
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/Analysis/ProfileSummaryInfo.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/MachineSizeOpts.h"
32 #include "llvm/CodeGen/MachineSSAUpdater.h"
33 #include "llvm/CodeGen/TargetInstrInfo.h"
34 #include "llvm/CodeGen/TargetRegisterInfo.h"
35 #include "llvm/CodeGen/TargetSubtargetInfo.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetMachine.h"
50 #define DEBUG_TYPE "tailduplication"
52 STATISTIC(NumTails, "Number of tails duplicated");
53 STATISTIC(NumTailDups, "Number of tail duplicated blocks");
54 STATISTIC(NumTailDupAdded,
55 "Number of instructions added due to tail duplication");
56 STATISTIC(NumTailDupRemoved,
57 "Number of instructions removed due to tail duplication");
58 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
59 STATISTIC(NumAddedPHIs, "Number of phis added");
61 // Heuristic for tail duplication.
62 static cl::opt<unsigned> TailDuplicateSize(
64 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
67 static cl::opt<unsigned> TailDupIndirectBranchSize(
68 "tail-dup-indirect-size",
69 cl::desc("Maximum instructions to consider tail duplicating blocks that "
70 "end with indirect branches."), cl::init(20),
74 TailDupVerify("tail-dup-verify",
75 cl::desc("Verify sanity of PHI instructions during taildup"),
76 cl::init(false), cl::Hidden);
78 static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
81 void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc,
82 const MachineBranchProbabilityInfo *MBPIin,
84 ProfileSummaryInfo *PSIin,
85 bool LayoutModeIn, unsigned TailDupSizeIn) {
87 TII = MF->getSubtarget().getInstrInfo();
88 TRI = MF->getSubtarget().getRegisterInfo();
89 MRI = &MF->getRegInfo();
94 TailDupSize = TailDupSizeIn;
96 assert(MBPI != nullptr && "Machine Branch Probability Info required");
98 LayoutMode = LayoutModeIn;
99 this->PreRegAlloc = PreRegAlloc;
102 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
103 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
104 MachineBasicBlock *MBB = &*I;
105 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
107 MachineBasicBlock::iterator MI = MBB->begin();
108 while (MI != MBB->end()) {
111 for (MachineBasicBlock *PredBB : Preds) {
113 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
114 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
115 if (PHIBB == PredBB) {
121 dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
123 dbgs() << " missing input from predecessor "
124 << printMBBReference(*PredBB) << '\n';
125 llvm_unreachable(nullptr);
129 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
130 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
131 if (CheckExtra && !Preds.count(PHIBB)) {
132 dbgs() << "Warning: malformed PHI in " << printMBBReference(*MBB)
134 dbgs() << " extra input from predecessor "
135 << printMBBReference(*PHIBB) << '\n';
136 llvm_unreachable(nullptr);
138 if (PHIBB->getNumber() < 0) {
139 dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
141 dbgs() << " non-existing " << printMBBReference(*PHIBB) << '\n';
142 llvm_unreachable(nullptr);
150 /// Tail duplicate the block and cleanup.
151 /// \p IsSimple - return value of isSimpleBB
152 /// \p MBB - block to be duplicated
153 /// \p ForcedLayoutPred - If non-null, treat this block as the layout
154 /// predecessor, instead of using the ordering in MF
155 /// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
156 /// all Preds that received a copy of \p MBB.
157 /// \p RemovalCallback - if non-null, called just before MBB is deleted.
158 bool TailDuplicator::tailDuplicateAndUpdate(
159 bool IsSimple, MachineBasicBlock *MBB,
160 MachineBasicBlock *ForcedLayoutPred,
161 SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
162 function_ref<void(MachineBasicBlock *)> *RemovalCallback,
163 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
164 // Save the successors list.
165 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
168 SmallVector<MachineBasicBlock *, 8> TDBBs;
169 SmallVector<MachineInstr *, 16> Copies;
170 if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred,
171 TDBBs, Copies, CandidatePtr))
176 SmallVector<MachineInstr *, 8> NewPHIs;
177 MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
179 // TailBB's immediate successors are now successors of those predecessors
180 // which duplicated TailBB. Add the predecessors as sources to the PHI
182 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
184 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
186 // If it is dead, remove it.
188 NumTailDupRemoved += MBB->size();
189 removeDeadBlock(MBB, RemovalCallback);
194 if (!SSAUpdateVRs.empty()) {
195 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
196 unsigned VReg = SSAUpdateVRs[i];
197 SSAUpdate.Initialize(VReg);
199 // If the original definition is still around, add it as an available
201 MachineInstr *DefMI = MRI->getVRegDef(VReg);
202 MachineBasicBlock *DefBB = nullptr;
204 DefBB = DefMI->getParent();
205 SSAUpdate.AddAvailableValue(DefBB, VReg);
208 // Add the new vregs as available values.
209 DenseMap<Register, AvailableValsTy>::iterator LI =
210 SSAUpdateVals.find(VReg);
211 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
212 MachineBasicBlock *SrcBB = LI->second[j].first;
213 Register SrcReg = LI->second[j].second;
214 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
217 // Rewrite uses that are outside of the original def's block.
218 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
219 while (UI != MRI->use_end()) {
220 MachineOperand &UseMO = *UI;
221 MachineInstr *UseMI = UseMO.getParent();
223 if (UseMI->isDebugValue()) {
224 // SSAUpdate can replace the use with an undef. That creates
225 // a debug instruction that is a kill.
226 // FIXME: Should it SSAUpdate job to delete debug instructions
227 // instead of replacing the use with undef?
228 UseMI->eraseFromParent();
231 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
233 SSAUpdate.RewriteUse(UseMO);
237 SSAUpdateVRs.clear();
238 SSAUpdateVals.clear();
241 // Eliminate some of the copies inserted by tail duplication to maintain
243 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
244 MachineInstr *Copy = Copies[i];
247 Register Dst = Copy->getOperand(0).getReg();
248 Register Src = Copy->getOperand(1).getReg();
249 if (MRI->hasOneNonDBGUse(Src) &&
250 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
251 // Copy is the only use. Do trivial copy propagation here.
252 MRI->replaceRegWith(Dst, Src);
253 Copy->eraseFromParent();
258 NumAddedPHIs += NewPHIs.size();
261 *DuplicatedPreds = std::move(TDBBs);
266 /// Look for small blocks that are unconditionally branched to and do not fall
267 /// through. Tail-duplicate their instructions into their predecessors to
268 /// eliminate (dynamic) branches.
269 bool TailDuplicator::tailDuplicateBlocks() {
270 bool MadeChange = false;
272 if (PreRegAlloc && TailDupVerify) {
273 LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
274 VerifyPHIs(*MF, true);
277 for (MachineFunction::iterator I = ++MF->begin(), E = MF->end(); I != E;) {
278 MachineBasicBlock *MBB = &*I++;
280 if (NumTails == TailDupLimit)
283 bool IsSimple = isSimpleBB(MBB);
285 if (!shouldTailDuplicate(IsSimple, *MBB))
288 MadeChange |= tailDuplicateAndUpdate(IsSimple, MBB, nullptr);
291 if (PreRegAlloc && TailDupVerify)
292 VerifyPHIs(*MF, false);
297 static bool isDefLiveOut(Register Reg, MachineBasicBlock *BB,
298 const MachineRegisterInfo *MRI) {
299 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
300 if (UseMI.isDebugValue())
302 if (UseMI.getParent() != BB)
308 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
309 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
310 if (MI->getOperand(i + 1).getMBB() == SrcBB)
315 // Remember which registers are used by phis in this block. This is
316 // used to determine which registers are liveout while modifying the
317 // block (which is why we need to copy the information).
318 static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
319 DenseSet<Register> *UsedByPhi) {
320 for (const auto &MI : BB) {
323 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
324 Register SrcReg = MI.getOperand(i).getReg();
325 UsedByPhi->insert(SrcReg);
330 /// Add a definition and source virtual registers pair for SSA update.
331 void TailDuplicator::addSSAUpdateEntry(Register OrigReg, Register NewReg,
332 MachineBasicBlock *BB) {
333 DenseMap<Register, AvailableValsTy>::iterator LI =
334 SSAUpdateVals.find(OrigReg);
335 if (LI != SSAUpdateVals.end())
336 LI->second.push_back(std::make_pair(BB, NewReg));
338 AvailableValsTy Vals;
339 Vals.push_back(std::make_pair(BB, NewReg));
340 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
341 SSAUpdateVRs.push_back(OrigReg);
345 /// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
346 /// source register that's contributed by PredBB and update SSA update map.
347 void TailDuplicator::processPHI(
348 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
349 DenseMap<Register, RegSubRegPair> &LocalVRMap,
350 SmallVectorImpl<std::pair<Register, RegSubRegPair>> &Copies,
351 const DenseSet<Register> &RegsUsedByPhi, bool Remove) {
352 Register DefReg = MI->getOperand(0).getReg();
353 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
354 assert(SrcOpIdx && "Unable to find matching PHI source?");
355 Register SrcReg = MI->getOperand(SrcOpIdx).getReg();
356 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
357 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
358 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
360 // Insert a copy from source to the end of the block. The def register is the
361 // available value liveout of the block.
362 Register NewDef = MRI->createVirtualRegister(RC);
363 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
364 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
365 addSSAUpdateEntry(DefReg, NewDef, PredBB);
370 // Remove PredBB from the PHI node.
371 MI->RemoveOperand(SrcOpIdx + 1);
372 MI->RemoveOperand(SrcOpIdx);
373 if (MI->getNumOperands() == 1)
374 MI->eraseFromParent();
377 /// Duplicate a TailBB instruction to PredBB and update
378 /// the source operands due to earlier PHI translation.
379 void TailDuplicator::duplicateInstruction(
380 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
381 DenseMap<Register, RegSubRegPair> &LocalVRMap,
382 const DenseSet<Register> &UsedByPhi) {
383 // Allow duplication of CFI instructions.
384 if (MI->isCFIInstruction()) {
385 BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()),
386 TII->get(TargetOpcode::CFI_INSTRUCTION)).addCFIIndex(
387 MI->getOperand(0).getCFIIndex());
390 MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI);
392 for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) {
393 MachineOperand &MO = NewMI.getOperand(i);
396 Register Reg = MO.getReg();
397 if (!Register::isVirtualRegister(Reg))
400 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
401 Register NewReg = MRI->createVirtualRegister(RC);
403 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
404 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
405 addSSAUpdateEntry(Reg, NewReg, PredBB);
407 auto VI = LocalVRMap.find(Reg);
408 if (VI != LocalVRMap.end()) {
409 // Need to make sure that the register class of the mapped register
410 // will satisfy the constraints of the class of the register being
412 auto *OrigRC = MRI->getRegClass(Reg);
413 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
414 const TargetRegisterClass *ConstrRC;
415 if (VI->second.SubReg != 0) {
416 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
419 // The actual constraining (as in "find appropriate new class")
420 // is done by getMatchingSuperRegClass, so now we only need to
421 // change the class of the mapped register.
422 MRI->setRegClass(VI->second.Reg, ConstrRC);
425 // For mapped registers that do not have sub-registers, simply
426 // restrict their class to match the original one.
427 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
431 // If the class constraining succeeded, we can simply replace
432 // the old register with the mapped one.
433 MO.setReg(VI->second.Reg);
434 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
435 // sub-register, we need to compose the sub-register indices.
436 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
439 // The direct replacement is not possible, due to failing register
440 // class constraints. An explicit COPY is necessary. Create one
441 // that can be reused
442 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
443 if (NewRC == nullptr)
445 Register NewReg = MRI->createVirtualRegister(NewRC);
446 BuildMI(*PredBB, NewMI, NewMI.getDebugLoc(),
447 TII->get(TargetOpcode::COPY), NewReg)
448 .addReg(VI->second.Reg, 0, VI->second.SubReg);
449 LocalVRMap.erase(VI);
450 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
452 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
453 // is equivalent to the whole register Reg. Hence, Reg:subreg
454 // is same as NewReg:subreg, so keep the sub-register index
457 // Clear any kill flags from this operand. The new register could
458 // have uses after this one, so kills are not valid here.
466 /// After FromBB is tail duplicated into its predecessor blocks, the successors
467 /// have gained new predecessors. Update the PHI instructions in them
469 void TailDuplicator::updateSuccessorsPHIs(
470 MachineBasicBlock *FromBB, bool isDead,
471 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
472 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
473 for (MachineBasicBlock *SuccBB : Succs) {
474 for (MachineInstr &MI : *SuccBB) {
477 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
479 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
480 MachineOperand &MO = MI.getOperand(i + 1);
481 if (MO.getMBB() == FromBB) {
488 MachineOperand &MO0 = MI.getOperand(Idx);
489 Register Reg = MO0.getReg();
491 // Folded into the previous BB.
492 // There could be duplicate phi source entries. FIXME: Should sdisel
493 // or earlier pass fixed this?
494 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
495 MachineOperand &MO = MI.getOperand(i + 1);
496 if (MO.getMBB() == FromBB) {
497 MI.RemoveOperand(i + 1);
504 // If Idx is set, the operands at Idx and Idx+1 must be removed.
505 // We reuse the location to avoid expensive RemoveOperand calls.
507 DenseMap<Register, AvailableValsTy>::iterator LI =
508 SSAUpdateVals.find(Reg);
509 if (LI != SSAUpdateVals.end()) {
510 // This register is defined in the tail block.
511 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
512 MachineBasicBlock *SrcBB = LI->second[j].first;
513 // If we didn't duplicate a bb into a particular predecessor, we
514 // might still have added an entry to SSAUpdateVals to correcly
515 // recompute SSA. If that case, avoid adding a dummy extra argument
517 if (!SrcBB->isSuccessor(SuccBB))
520 Register SrcReg = LI->second[j].second;
522 MI.getOperand(Idx).setReg(SrcReg);
523 MI.getOperand(Idx + 1).setMBB(SrcBB);
526 MIB.addReg(SrcReg).addMBB(SrcBB);
530 // Live in tail block, must also be live in predecessors.
531 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
532 MachineBasicBlock *SrcBB = TDBBs[j];
534 MI.getOperand(Idx).setReg(Reg);
535 MI.getOperand(Idx + 1).setMBB(SrcBB);
538 MIB.addReg(Reg).addMBB(SrcBB);
543 MI.RemoveOperand(Idx + 1);
544 MI.RemoveOperand(Idx);
550 /// Determine if it is profitable to duplicate this block.
551 bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
552 MachineBasicBlock &TailBB) {
553 // When doing tail-duplication during layout, the block ordering is in flux,
554 // so canFallThrough returns a result based on incorrect information and
555 // should just be ignored.
556 if (!LayoutMode && TailBB.canFallThrough())
559 // Don't try to tail-duplicate single-block loops.
560 if (TailBB.isSuccessor(&TailBB))
563 // Set the limit on the cost to duplicate. When optimizing for size,
564 // duplicate only one, because one branch instruction can be eliminated to
565 // compensate for the duplication.
566 unsigned MaxDuplicateCount;
567 bool OptForSize = MF->getFunction().hasOptSize() ||
568 llvm::shouldOptimizeForSize(&TailBB, PSI, MBFI);
569 if (TailDupSize == 0)
570 MaxDuplicateCount = TailDuplicateSize;
572 MaxDuplicateCount = TailDupSize;
574 MaxDuplicateCount = 1;
576 // If the block to be duplicated ends in an unanalyzable fallthrough, don't
578 // A similar check is necessary in MachineBlockPlacement to make sure pairs of
579 // blocks with unanalyzable fallthrough get layed out contiguously.
580 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
581 SmallVector<MachineOperand, 4> PredCond;
582 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
583 TailBB.canFallThrough())
586 // If the target has hardware branch prediction that can handle indirect
587 // branches, duplicating them can often make them predictable when there
588 // are common paths through the code. The limit needs to be high enough
589 // to allow undoing the effects of tail merging and other optimizations
590 // that rearrange the predecessors of the indirect branch.
592 bool HasIndirectbr = false;
594 HasIndirectbr = TailBB.back().isIndirectBranch();
596 if (HasIndirectbr && PreRegAlloc)
597 MaxDuplicateCount = TailDupIndirectBranchSize;
599 // Check the instructions in the block to determine whether tail-duplication
600 // is invalid or unlikely to be profitable.
601 unsigned InstrCount = 0;
602 for (MachineInstr &MI : TailBB) {
603 // Non-duplicable things shouldn't be tail-duplicated.
604 // CFI instructions are marked as non-duplicable, because Darwin compact
605 // unwind info emission can't handle multiple prologue setups. In case of
606 // DWARF, allow them be duplicated, so that their existence doesn't prevent
607 // tail duplication of some basic blocks, that would be duplicated otherwise.
608 if (MI.isNotDuplicable() &&
609 (TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() ||
610 !MI.isCFIInstruction()))
613 // Convergent instructions can be duplicated only if doing so doesn't add
614 // new control dependencies, which is what we're going to do here.
615 if (MI.isConvergent())
618 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
619 // A return may expand into a lot more instructions (e.g. reload of callee
620 // saved registers) after PEI.
621 if (PreRegAlloc && MI.isReturn())
624 // Avoid duplicating calls before register allocation. Calls presents a
625 // barrier to register allocation so duplicating them may end up increasing
627 if (PreRegAlloc && MI.isCall())
631 InstrCount += MI.getBundleSize();
632 else if (!MI.isPHI() && !MI.isMetaInstruction())
635 if (InstrCount > MaxDuplicateCount)
639 // Check if any of the successors of TailBB has a PHI node in which the
640 // value corresponding to TailBB uses a subregister.
641 // If a phi node uses a register paired with a subregister, the actual
642 // "value type" of the phi may differ from the type of the register without
643 // any subregisters. Due to a bug, tail duplication may add a new operand
644 // without a necessary subregister, producing an invalid code. This is
645 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
646 // Disable tail duplication for this case for now, until the problem is
648 for (auto SB : TailBB.successors()) {
649 for (auto &I : *SB) {
652 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
654 MachineOperand &PU = I.getOperand(Idx);
655 if (PU.getSubReg() != 0)
660 if (HasIndirectbr && PreRegAlloc)
669 return canCompletelyDuplicateBB(TailBB);
672 /// True if this BB has only one unconditional jump.
673 bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
674 if (TailBB->succ_size() != 1)
676 if (TailBB->pred_empty())
678 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
679 if (I == TailBB->end())
681 return I->isUnconditionalBranch();
684 static bool bothUsedInPHI(const MachineBasicBlock &A,
685 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
686 for (MachineBasicBlock *BB : A.successors())
687 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
693 bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
694 for (MachineBasicBlock *PredBB : BB.predecessors()) {
695 if (PredBB->succ_size() > 1)
698 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
699 SmallVector<MachineOperand, 4> PredCond;
700 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
703 if (!PredCond.empty())
709 bool TailDuplicator::duplicateSimpleBB(
710 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
711 const DenseSet<Register> &UsedByPhi,
712 SmallVectorImpl<MachineInstr *> &Copies) {
713 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
715 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
717 bool Changed = false;
718 for (MachineBasicBlock *PredBB : Preds) {
719 if (PredBB->hasEHPadSuccessor() || PredBB->mayHaveInlineAsmBr())
722 if (bothUsedInPHI(*PredBB, Succs))
725 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
726 SmallVector<MachineOperand, 4> PredCond;
727 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
731 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
732 << "From simple Succ: " << *TailBB);
734 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
735 MachineBasicBlock *NextBB = PredBB->getNextNode();
737 // Make PredFBB explicit.
738 if (PredCond.empty())
741 // Make fall through explicit.
748 if (PredFBB == TailBB)
750 if (PredTBB == TailBB)
753 // Make the branch unconditional if possible
754 if (PredTBB == PredFBB) {
759 // Avoid adding fall through branches.
760 if (PredFBB == NextBB)
762 if (PredTBB == NextBB && PredFBB == nullptr)
765 auto DL = PredBB->findBranchDebugLoc();
766 TII->removeBranch(*PredBB);
768 if (!PredBB->isSuccessor(NewTarget))
769 PredBB->replaceSuccessor(TailBB, NewTarget);
771 PredBB->removeSuccessor(TailBB, true);
772 assert(PredBB->succ_size() <= 1);
776 TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
778 TDBBs.push_back(PredBB);
783 bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
784 MachineBasicBlock *PredBB) {
785 // EH edges are ignored by analyzeBranch.
786 if (PredBB->succ_size() > 1)
789 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
790 SmallVector<MachineOperand, 4> PredCond;
791 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
793 if (!PredCond.empty())
798 /// If it is profitable, duplicate TailBB's contents in each
799 /// of its predecessors.
800 /// \p IsSimple result of isSimpleBB
801 /// \p TailBB Block to be duplicated.
802 /// \p ForcedLayoutPred When non-null, use this block as the layout predecessor
803 /// instead of the previous block in MF's order.
804 /// \p TDBBs A vector to keep track of all blocks tail-duplicated
806 /// \p Copies A vector of copy instructions inserted. Used later to
807 /// walk all the inserted copies and remove redundant ones.
808 bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
809 MachineBasicBlock *ForcedLayoutPred,
810 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
811 SmallVectorImpl<MachineInstr *> &Copies,
812 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
813 LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
816 bool ShouldUpdateTerminators = TailBB->canFallThrough();
818 DenseSet<Register> UsedByPhi;
819 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
822 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
824 // Iterate through all the unique predecessors and tail-duplicate this
825 // block into them, if possible. Copying the list ahead of time also
826 // avoids trouble with the predecessor list reallocating.
827 bool Changed = false;
828 SmallSetVector<MachineBasicBlock *, 8> Preds;
830 Preds.insert(CandidatePtr->begin(), CandidatePtr->end());
832 Preds.insert(TailBB->pred_begin(), TailBB->pred_end());
834 for (MachineBasicBlock *PredBB : Preds) {
835 assert(TailBB != PredBB &&
836 "Single-block loop should have been rejected earlier!");
838 if (!canTailDuplicate(TailBB, PredBB))
841 // Don't duplicate into a fall-through predecessor (at least for now).
842 // If profile is available, findDuplicateCandidates can choose better
843 // fall-through predecessor.
844 if (!(MF->getFunction().hasProfileData() && LayoutMode)) {
845 bool IsLayoutSuccessor = false;
846 if (ForcedLayoutPred)
847 IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
848 else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
849 IsLayoutSuccessor = true;
850 if (IsLayoutSuccessor)
854 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
855 << "From Succ: " << *TailBB);
857 TDBBs.push_back(PredBB);
859 // Remove PredBB's unconditional branch.
860 TII->removeBranch(*PredBB);
862 // Clone the contents of TailBB into PredBB.
863 DenseMap<Register, RegSubRegPair> LocalVRMap;
864 SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
865 for (MachineBasicBlock::iterator I = TailBB->begin(), E = TailBB->end();
866 I != E; /* empty */) {
867 MachineInstr *MI = &*I;
870 // Replace the uses of the def of the PHI with the register coming
872 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
874 // Replace def of virtual registers with new registers, and update
875 // uses with PHI source register or the new registers.
876 duplicateInstruction(MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
879 appendCopies(PredBB, CopyInfos, Copies);
881 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
884 PredBB->removeSuccessor(PredBB->succ_begin());
885 assert(PredBB->succ_empty() &&
886 "TailDuplicate called on block with multiple successors!");
887 for (MachineBasicBlock *Succ : TailBB->successors())
888 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
890 // Update branches in pred to jump to tail's layout successor if needed.
891 if (ShouldUpdateTerminators)
892 PredBB->updateTerminator(TailBB->getNextNode());
898 // If TailBB was duplicated into all its predecessors except for the prior
899 // block, which falls through unconditionally, move the contents of this
900 // block into the prior block.
901 MachineBasicBlock *PrevBB = ForcedLayoutPred;
903 PrevBB = &*std::prev(TailBB->getIterator());
904 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
905 SmallVector<MachineOperand, 4> PriorCond;
906 // This has to check PrevBB->succ_size() because EH edges are ignored by
908 if (PrevBB->succ_size() == 1 &&
909 // Layout preds are not always CFG preds. Check.
910 *PrevBB->succ_begin() == TailBB &&
911 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
913 (!PriorTBB || PriorTBB == TailBB) &&
914 TailBB->pred_size() == 1 &&
915 !TailBB->hasAddressTaken()) {
916 LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
917 << "From MBB: " << *TailBB);
918 // There may be a branch to the layout successor. This is unlikely but it
919 // happens. The correct thing to do is to remove the branch before
920 // duplicating the instructions in all cases.
921 TII->removeBranch(*PrevBB);
923 DenseMap<Register, RegSubRegPair> LocalVRMap;
924 SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
925 MachineBasicBlock::iterator I = TailBB->begin();
926 // Process PHI instructions first.
927 while (I != TailBB->end() && I->isPHI()) {
928 // Replace the uses of the def of the PHI with the register coming
930 MachineInstr *MI = &*I++;
931 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
934 // Now copy the non-PHI instructions.
935 while (I != TailBB->end()) {
936 // Replace def of virtual registers with new registers, and update
937 // uses with PHI source register or the new registers.
938 MachineInstr *MI = &*I++;
939 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
940 duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
941 MI->eraseFromParent();
943 appendCopies(PrevBB, CopyInfos, Copies);
945 TII->removeBranch(*PrevBB);
946 // No PHIs to worry about, just splice the instructions over.
947 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
949 PrevBB->removeSuccessor(PrevBB->succ_begin());
950 assert(PrevBB->succ_empty());
951 PrevBB->transferSuccessors(TailBB);
953 // Update branches in PrevBB based on Tail's layout successor.
954 if (ShouldUpdateTerminators)
955 PrevBB->updateTerminator(TailBB->getNextNode());
957 TDBBs.push_back(PrevBB);
961 // If this is after register allocation, there are no phis to fix.
965 // If we made no changes so far, we are safe.
969 // Handle the nasty case in that we duplicated a block that is part of a loop
970 // into some but not all of its predecessors. For example:
974 // if we duplicate 2 into 1 but not into 3, we end up with
975 // 12 -> 3 <-> 2 -> rest |
978 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
979 // with a phi in 3 (which now dominates 2).
980 // What we do here is introduce a copy in 3 of the register defined by the
981 // phi, just like when we are duplicating 2 into 3, but we don't copy any
982 // real instructions or remove the 3 -> 2 edge from the phi in 2.
983 for (MachineBasicBlock *PredBB : Preds) {
984 if (is_contained(TDBBs, PredBB))
988 if (PredBB->succ_size() != 1)
991 DenseMap<Register, RegSubRegPair> LocalVRMap;
992 SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
993 MachineBasicBlock::iterator I = TailBB->begin();
994 // Process PHI instructions first.
995 while (I != TailBB->end() && I->isPHI()) {
996 // Replace the uses of the def of the PHI with the register coming
998 MachineInstr *MI = &*I++;
999 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
1001 appendCopies(PredBB, CopyInfos, Copies);
1007 /// At the end of the block \p MBB generate COPY instructions between registers
1008 /// described by \p CopyInfos. Append resulting instructions to \p Copies.
1009 void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
1010 SmallVectorImpl<std::pair<Register, RegSubRegPair>> &CopyInfos,
1011 SmallVectorImpl<MachineInstr*> &Copies) {
1012 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1013 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
1014 for (auto &CI : CopyInfos) {
1015 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
1016 .addReg(CI.second.Reg, 0, CI.second.SubReg);
1017 Copies.push_back(C);
1021 /// Remove the specified dead machine basic block from the function, updating
1023 void TailDuplicator::removeDeadBlock(
1024 MachineBasicBlock *MBB,
1025 function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
1026 assert(MBB->pred_empty() && "MBB must be dead!");
1027 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
1029 MachineFunction *MF = MBB->getParent();
1030 // Update the call site info.
1031 std::for_each(MBB->begin(), MBB->end(), [MF](const MachineInstr &MI) {
1032 if (MI.shouldUpdateCallSiteInfo())
1033 MF->eraseCallSiteInfo(&MI);
1036 if (RemovalCallback)
1037 (*RemovalCallback)(MBB);
1039 // Remove all successors.
1040 while (!MBB->succ_empty())
1041 MBB->removeSuccessor(MBB->succ_end() - 1);
1043 // Remove the block.
1044 MBB->eraseFromParent();