#include "llvm/CodeGen/TailDuplicator.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/MachineSSAUpdater.h"
#include "llvm/CodeGen/MachineSizeOpts.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <utility>
using namespace llvm;
#define DEBUG_TYPE "tailduplication"
STATISTIC(NumTails, "Number of tails duplicated");
STATISTIC(NumTailDups, "Number of tail duplicated blocks");
STATISTIC(NumTailDupAdded,
"Number of instructions added due to tail duplication");
STATISTIC(NumTailDupRemoved,
"Number of instructions removed due to tail duplication");
STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
STATISTIC(NumAddedPHIs, "Number of phis added");
static cl::opt<unsigned> TailDuplicateSize(
"tail-dup-size",
cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
cl::Hidden);
static cl::opt<unsigned> TailDupIndirectBranchSize(
"tail-dup-indirect-size",
cl::desc("Maximum instructions to consider tail duplicating blocks that "
"end with indirect branches."), cl::init(20),
cl::Hidden);
static cl::opt<bool>
TailDupVerify("tail-dup-verify",
cl::desc("Verify sanity of PHI instructions during taildup"),
cl::init(false), cl::Hidden);
static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
cl::Hidden);
void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc,
const MachineBranchProbabilityInfo *MBPIin,
MBFIWrapper *MBFIin,
ProfileSummaryInfo *PSIin,
bool LayoutModeIn, unsigned TailDupSizeIn) {
MF = &MFin;
TII = MF->getSubtarget().getInstrInfo();
TRI = MF->getSubtarget().getRegisterInfo();
MRI = &MF->getRegInfo();
MMI = &MF->getMMI();
MBPI = MBPIin;
MBFI = MBFIin;
PSI = PSIin;
TailDupSize = TailDupSizeIn;
assert(MBPI != nullptr && "Machine Branch Probability Info required");
LayoutMode = LayoutModeIn;
this->PreRegAlloc = PreRegAlloc;
}
static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
for (MachineBasicBlock &MBB : llvm::drop_begin(MF)) {
SmallSetVector<MachineBasicBlock *, 8> Preds(MBB.pred_begin(),
MBB.pred_end());
MachineBasicBlock::iterator MI = MBB.begin();
while (MI != MBB.end()) {
if (!MI->isPHI())
break;
for (MachineBasicBlock *PredBB : Preds) {
bool Found = false;
for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
if (PHIBB == PredBB) {
Found = true;
break;
}
}
if (!Found) {
dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": "
<< *MI;
dbgs() << " missing input from predecessor "
<< printMBBReference(*PredBB) << '\n';
llvm_unreachable(nullptr);
}
}
for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
if (CheckExtra && !Preds.count(PHIBB)) {
dbgs() << "Warning: malformed PHI in " << printMBBReference(MBB)
<< ": " << *MI;
dbgs() << " extra input from predecessor "
<< printMBBReference(*PHIBB) << '\n';
llvm_unreachable(nullptr);
}
if (PHIBB->getNumber() < 0) {
dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": "
<< *MI;
dbgs() << " non-existing " << printMBBReference(*PHIBB) << '\n';
llvm_unreachable(nullptr);
}
}
++MI;
}
}
}
bool TailDuplicator::tailDuplicateAndUpdate(
bool IsSimple, MachineBasicBlock *MBB,
MachineBasicBlock *ForcedLayoutPred,
SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
function_ref<void(MachineBasicBlock *)> *RemovalCallback,
SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
MBB->succ_end());
SmallVector<MachineBasicBlock *, 8> TDBBs;
SmallVector<MachineInstr *, 16> Copies;
if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred,
TDBBs, Copies, CandidatePtr))
return false;
++NumTails;
SmallVector<MachineInstr *, 8> NewPHIs;
MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
if (PreRegAlloc)
updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
if (isDead) {
NumTailDupRemoved += MBB->size();
removeDeadBlock(MBB, RemovalCallback);
++NumDeadBlocks;
}
if (!SSAUpdateVRs.empty()) {
for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
unsigned VReg = SSAUpdateVRs[i];
SSAUpdate.Initialize(VReg);
MachineInstr *DefMI = MRI->getVRegDef(VReg);
MachineBasicBlock *DefBB = nullptr;
if (DefMI) {
DefBB = DefMI->getParent();
SSAUpdate.AddAvailableValue(DefBB, VReg);
}
DenseMap<Register, AvailableValsTy>::iterator LI =
SSAUpdateVals.find(VReg);
for (std::pair<MachineBasicBlock *, Register> &J : LI->second) {
MachineBasicBlock *SrcBB = J.first;
Register SrcReg = J.second;
SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
}
SmallVector<MachineOperand *> DebugUses;
for (MachineOperand &UseMO :
llvm::make_early_inc_range(MRI->use_operands(VReg))) {
MachineInstr *UseMI = UseMO.getParent();
if (UseMI->isDebugValue()) {
DebugUses.push_back(&UseMO);
continue;
}
if (UseMI->getParent() == DefBB && !UseMI->isPHI())
continue;
SSAUpdate.RewriteUse(UseMO);
}
for (auto *UseMO : DebugUses) {
MachineInstr *UseMI = UseMO->getParent();
UseMO->setReg(
SSAUpdate.GetValueInMiddleOfBlock(UseMI->getParent(), true));
}
}
SSAUpdateVRs.clear();
SSAUpdateVals.clear();
}
for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
MachineInstr *Copy = Copies[i];
if (!Copy->isCopy())
continue;
Register Dst = Copy->getOperand(0).getReg();
Register Src = Copy->getOperand(1).getReg();
if (MRI->hasOneNonDBGUse(Src) &&
MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
MRI->replaceRegWith(Dst, Src);
Copy->eraseFromParent();
}
}
if (NewPHIs.size())
NumAddedPHIs += NewPHIs.size();
if (DuplicatedPreds)
*DuplicatedPreds = std::move(TDBBs);
return true;
}
bool TailDuplicator::tailDuplicateBlocks() {
bool MadeChange = false;
if (PreRegAlloc && TailDupVerify) {
LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
VerifyPHIs(*MF, true);
}
for (MachineBasicBlock &MBB :
llvm::make_early_inc_range(llvm::drop_begin(*MF))) {
if (NumTails == TailDupLimit)
break;
bool IsSimple = isSimpleBB(&MBB);
if (!shouldTailDuplicate(IsSimple, MBB))
continue;
MadeChange |= tailDuplicateAndUpdate(IsSimple, &MBB, nullptr);
}
if (PreRegAlloc && TailDupVerify)
VerifyPHIs(*MF, false);
return MadeChange;
}
static bool isDefLiveOut(Register Reg, MachineBasicBlock *BB,
const MachineRegisterInfo *MRI) {
for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
if (UseMI.isDebugValue())
continue;
if (UseMI.getParent() != BB)
return true;
}
return false;
}
static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
if (MI->getOperand(i + 1).getMBB() == SrcBB)
return i;
return 0;
}
static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
DenseSet<Register> *UsedByPhi) {
for (const auto &MI : BB) {
if (!MI.isPHI())
break;
for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
Register SrcReg = MI.getOperand(i).getReg();
UsedByPhi->insert(SrcReg);
}
}
}
void TailDuplicator::addSSAUpdateEntry(Register OrigReg, Register NewReg,
MachineBasicBlock *BB) {
DenseMap<Register, AvailableValsTy>::iterator LI =
SSAUpdateVals.find(OrigReg);
if (LI != SSAUpdateVals.end())
LI->second.push_back(std::make_pair(BB, NewReg));
else {
AvailableValsTy Vals;
Vals.push_back(std::make_pair(BB, NewReg));
SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
SSAUpdateVRs.push_back(OrigReg);
}
}
void TailDuplicator::processPHI(
MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
DenseMap<Register, RegSubRegPair> &LocalVRMap,
SmallVectorImpl<std::pair<Register, RegSubRegPair>> &Copies,
const DenseSet<Register> &RegsUsedByPhi, bool Remove) {
Register DefReg = MI->getOperand(0).getReg();
unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
assert(SrcOpIdx && "Unable to find matching PHI source?");
Register SrcReg = MI->getOperand(SrcOpIdx).getReg();
unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
Register NewDef = MRI->createVirtualRegister(RC);
Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
addSSAUpdateEntry(DefReg, NewDef, PredBB);
if (!Remove)
return;
MI->removeOperand(SrcOpIdx + 1);
MI->removeOperand(SrcOpIdx);
if (MI->getNumOperands() == 1)
MI->eraseFromParent();
}
void TailDuplicator::duplicateInstruction(
MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
DenseMap<Register, RegSubRegPair> &LocalVRMap,
const DenseSet<Register> &UsedByPhi) {
if (MI->isCFIInstruction()) {
BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()),
TII->get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(MI->getOperand(0).getCFIIndex())
.setMIFlags(MI->getFlags());
return;
}
MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI);
if (PreRegAlloc) {
for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) {
MachineOperand &MO = NewMI.getOperand(i);
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (!Register::isVirtualRegister(Reg))
continue;
if (MO.isDef()) {
const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Register NewReg = MRI->createVirtualRegister(RC);
MO.setReg(NewReg);
LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
addSSAUpdateEntry(Reg, NewReg, PredBB);
} else {
auto VI = LocalVRMap.find(Reg);
if (VI != LocalVRMap.end()) {
auto *OrigRC = MRI->getRegClass(Reg);
auto *MappedRC = MRI->getRegClass(VI->second.Reg);
const TargetRegisterClass *ConstrRC;
if (VI->second.SubReg != 0) {
ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
VI->second.SubReg);
if (ConstrRC) {
MRI->setRegClass(VI->second.Reg, ConstrRC);
}
} else {
ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
}
if (ConstrRC) {
MO.setReg(VI->second.Reg);
MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
VI->second.SubReg));
} else {
auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
if (NewRC == nullptr)
NewRC = OrigRC;
Register NewReg = MRI->createVirtualRegister(NewRC);
BuildMI(*PredBB, NewMI, NewMI.getDebugLoc(),
TII->get(TargetOpcode::COPY), NewReg)
.addReg(VI->second.Reg, 0, VI->second.SubReg);
LocalVRMap.erase(VI);
LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
MO.setReg(NewReg);
}
MO.setIsKill(false);
}
}
}
}
}
void TailDuplicator::updateSuccessorsPHIs(
MachineBasicBlock *FromBB, bool isDead,
SmallVectorImpl<MachineBasicBlock *> &TDBBs,
SmallSetVector<MachineBasicBlock *, 8> &Succs) {
for (MachineBasicBlock *SuccBB : Succs) {
for (MachineInstr &MI : *SuccBB) {
if (!MI.isPHI())
break;
MachineInstrBuilder MIB(*FromBB->getParent(), MI);
unsigned Idx = 0;
for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
MachineOperand &MO = MI.getOperand(i + 1);
if (MO.getMBB() == FromBB) {
Idx = i;
break;
}
}
assert(Idx != 0);
MachineOperand &MO0 = MI.getOperand(Idx);
Register Reg = MO0.getReg();
if (isDead) {
for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
MachineOperand &MO = MI.getOperand(i + 1);
if (MO.getMBB() == FromBB) {
MI.removeOperand(i + 1);
MI.removeOperand(i);
}
}
} else
Idx = 0;
DenseMap<Register, AvailableValsTy>::iterator LI =
SSAUpdateVals.find(Reg);
if (LI != SSAUpdateVals.end()) {
for (const std::pair<MachineBasicBlock *, Register> &J : LI->second) {
MachineBasicBlock *SrcBB = J.first;
if (!SrcBB->isSuccessor(SuccBB))
continue;
Register SrcReg = J.second;
if (Idx != 0) {
MI.getOperand(Idx).setReg(SrcReg);
MI.getOperand(Idx + 1).setMBB(SrcBB);
Idx = 0;
} else {
MIB.addReg(SrcReg).addMBB(SrcBB);
}
}
} else {
for (MachineBasicBlock *SrcBB : TDBBs) {
if (Idx != 0) {
MI.getOperand(Idx).setReg(Reg);
MI.getOperand(Idx + 1).setMBB(SrcBB);
Idx = 0;
} else {
MIB.addReg(Reg).addMBB(SrcBB);
}
}
}
if (Idx != 0) {
MI.removeOperand(Idx + 1);
MI.removeOperand(Idx);
}
}
}
}
bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
MachineBasicBlock &TailBB) {
if (!LayoutMode && TailBB.canFallThrough())
return false;
if (TailBB.isSuccessor(&TailBB))
return false;
unsigned MaxDuplicateCount;
bool OptForSize = MF->getFunction().hasOptSize() ||
llvm::shouldOptimizeForSize(&TailBB, PSI, MBFI);
if (TailDupSize == 0)
MaxDuplicateCount = TailDuplicateSize;
else
MaxDuplicateCount = TailDupSize;
if (OptForSize)
MaxDuplicateCount = 1;
MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
SmallVector<MachineOperand, 4> PredCond;
if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
TailBB.canFallThrough())
return false;
bool HasIndirectbr = false;
if (!TailBB.empty())
HasIndirectbr = TailBB.back().isIndirectBranch();
if (HasIndirectbr && PreRegAlloc)
MaxDuplicateCount = TailDupIndirectBranchSize;
unsigned InstrCount = 0;
for (MachineInstr &MI : TailBB) {
if (MI.isNotDuplicable() &&
(TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() ||
!MI.isCFIInstruction()))
return false;
if (MI.isConvergent())
return false;
if (PreRegAlloc && MI.isReturn())
return false;
if (PreRegAlloc && MI.isCall())
return false;
if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
return false;
if (MI.isBundle())
InstrCount += MI.getBundleSize();
else if (!MI.isPHI() && !MI.isMetaInstruction())
InstrCount += 1;
if (InstrCount > MaxDuplicateCount)
return false;
}
for (auto *SB : TailBB.successors()) {
for (auto &I : *SB) {
if (!I.isPHI())
break;
unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
assert(Idx != 0);
MachineOperand &PU = I.getOperand(Idx);
if (PU.getSubReg() != 0)
return false;
}
}
if (HasIndirectbr && PreRegAlloc)
return true;
if (IsSimple)
return true;
if (!PreRegAlloc)
return true;
return canCompletelyDuplicateBB(TailBB);
}
bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
if (TailBB->succ_size() != 1)
return false;
if (TailBB->pred_empty())
return false;
MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr(true);
if (I == TailBB->end())
return true;
return I->isUnconditionalBranch();
}
static bool bothUsedInPHI(const MachineBasicBlock &A,
const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
for (MachineBasicBlock *BB : A.successors())
if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
return true;
return false;
}
bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
for (MachineBasicBlock *PredBB : BB.predecessors()) {
if (PredBB->succ_size() > 1)
return false;
MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
SmallVector<MachineOperand, 4> PredCond;
if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
return false;
if (!PredCond.empty())
return false;
}
return true;
}
bool TailDuplicator::duplicateSimpleBB(
MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
const DenseSet<Register> &UsedByPhi,
SmallVectorImpl<MachineInstr *> &Copies) {
SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
TailBB->succ_end());
SmallVector<MachineBasicBlock *, 8> Preds(TailBB->predecessors());
bool Changed = false;
for (MachineBasicBlock *PredBB : Preds) {
if (PredBB->hasEHPadSuccessor() || PredBB->mayHaveInlineAsmBr())
continue;
if (bothUsedInPHI(*PredBB, Succs))
continue;
MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
SmallVector<MachineOperand, 4> PredCond;
if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
continue;
Changed = true;
LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
<< "From simple Succ: " << *TailBB);
MachineBasicBlock *NewTarget = *TailBB->succ_begin();
MachineBasicBlock *NextBB = PredBB->getNextNode();
if (PredCond.empty())
PredFBB = PredTBB;
if (!PredTBB)
PredTBB = NextBB;
if (!PredFBB)
PredFBB = NextBB;
if (PredFBB == TailBB)
PredFBB = NewTarget;
if (PredTBB == TailBB)
PredTBB = NewTarget;
if (PredTBB == PredFBB) {
PredCond.clear();
PredFBB = nullptr;
}
if (PredFBB == NextBB)
PredFBB = nullptr;
if (PredTBB == NextBB && PredFBB == nullptr)
PredTBB = nullptr;
auto DL = PredBB->findBranchDebugLoc();
TII->removeBranch(*PredBB);
if (!PredBB->isSuccessor(NewTarget))
PredBB->replaceSuccessor(TailBB, NewTarget);
else {
PredBB->removeSuccessor(TailBB, true);
assert(PredBB->succ_size() <= 1);
}
if (PredTBB)
TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
TDBBs.push_back(PredBB);
}
return Changed;
}
bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
MachineBasicBlock *PredBB) {
if (PredBB->succ_size() > 1)
return false;
MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
SmallVector<MachineOperand, 4> PredCond;
if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
return false;
if (!PredCond.empty())
return false;
return true;
}
bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
MachineBasicBlock *ForcedLayoutPred,
SmallVectorImpl<MachineBasicBlock *> &TDBBs,
SmallVectorImpl<MachineInstr *> &Copies,
SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
<< '\n');
bool ShouldUpdateTerminators = TailBB->canFallThrough();
DenseSet<Register> UsedByPhi;
getRegsUsedByPHIs(*TailBB, &UsedByPhi);
if (IsSimple)
return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
bool Changed = false;
SmallSetVector<MachineBasicBlock *, 8> Preds;
if (CandidatePtr)
Preds.insert(CandidatePtr->begin(), CandidatePtr->end());
else
Preds.insert(TailBB->pred_begin(), TailBB->pred_end());
for (MachineBasicBlock *PredBB : Preds) {
assert(TailBB != PredBB &&
"Single-block loop should have been rejected earlier!");
if (!canTailDuplicate(TailBB, PredBB))
continue;
if (!(MF->getFunction().hasProfileData() && LayoutMode)) {
bool IsLayoutSuccessor = false;
if (ForcedLayoutPred)
IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
IsLayoutSuccessor = true;
if (IsLayoutSuccessor)
continue;
}
LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
<< "From Succ: " << *TailBB);
TDBBs.push_back(PredBB);
TII->removeBranch(*PredBB);
DenseMap<Register, RegSubRegPair> LocalVRMap;
SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
for (MachineInstr &MI : llvm::make_early_inc_range(*TailBB)) {
if (MI.isPHI()) {
processPHI(&MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
} else {
duplicateInstruction(&MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
}
}
appendCopies(PredBB, CopyInfos, Copies);
NumTailDupAdded += TailBB->size() - 1;
PredBB->removeSuccessor(PredBB->succ_begin());
assert(PredBB->succ_empty() &&
"TailDuplicate called on block with multiple successors!");
for (MachineBasicBlock *Succ : TailBB->successors())
PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
if (ShouldUpdateTerminators)
PredBB->updateTerminator(TailBB->getNextNode());
Changed = true;
++NumTailDups;
}
MachineBasicBlock *PrevBB = ForcedLayoutPred;
if (!PrevBB)
PrevBB = &*std::prev(TailBB->getIterator());
MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
SmallVector<MachineOperand, 4> PriorCond;
if (PrevBB->succ_size() == 1 &&
*PrevBB->succ_begin() == TailBB &&
!TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
PriorCond.empty() &&
(!PriorTBB || PriorTBB == TailBB) &&
TailBB->pred_size() == 1 &&
!TailBB->hasAddressTaken()) {
LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
<< "From MBB: " << *TailBB);
bool RemovedBranches = TII->removeBranch(*PrevBB) != 0;
if (PrevBB->getFirstTerminator() == PrevBB->end()) {
if (PreRegAlloc) {
DenseMap<Register, RegSubRegPair> LocalVRMap;
SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
MachineBasicBlock::iterator I = TailBB->begin();
while (I != TailBB->end() && I->isPHI()) {
MachineInstr *MI = &*I++;
processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi,
true);
}
while (I != TailBB->end()) {
MachineInstr *MI = &*I++;
assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
MI->eraseFromParent();
}
appendCopies(PrevBB, CopyInfos, Copies);
} else {
TII->removeBranch(*PrevBB);
PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
}
PrevBB->removeSuccessor(PrevBB->succ_begin());
assert(PrevBB->succ_empty());
PrevBB->transferSuccessors(TailBB);
if (ShouldUpdateTerminators)
PrevBB->updateTerminator(TailBB->getNextNode());
TDBBs.push_back(PrevBB);
Changed = true;
} else {
LLVM_DEBUG(dbgs() << "Abort merging blocks, the predecessor still "
"contains terminator instructions");
if (!Changed)
return RemovedBranches;
}
Changed |= RemovedBranches;
}
if (!PreRegAlloc)
return Changed;
if (!Changed)
return Changed;
for (MachineBasicBlock *PredBB : Preds) {
if (is_contained(TDBBs, PredBB))
continue;
if (PredBB->succ_size() != 1)
continue;
DenseMap<Register, RegSubRegPair> LocalVRMap;
SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
MachineBasicBlock::iterator I = TailBB->begin();
while (I != TailBB->end() && I->isPHI()) {
MachineInstr *MI = &*I++;
processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
}
appendCopies(PredBB, CopyInfos, Copies);
}
return Changed;
}
void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
SmallVectorImpl<std::pair<Register, RegSubRegPair>> &CopyInfos,
SmallVectorImpl<MachineInstr*> &Copies) {
MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
for (auto &CI : CopyInfos) {
auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
.addReg(CI.second.Reg, 0, CI.second.SubReg);
Copies.push_back(C);
}
}
void TailDuplicator::removeDeadBlock(
MachineBasicBlock *MBB,
function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
assert(MBB->pred_empty() && "MBB must be dead!");
LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
MachineFunction *MF = MBB->getParent();
for (const MachineInstr &MI : *MBB)
if (MI.shouldUpdateCallSiteInfo())
MF->eraseCallSiteInfo(&MI);
if (RemovalCallback)
(*RemovalCallback)(MBB);
while (!MBB->succ_empty())
MBB->removeSuccessor(MBB->succ_end() - 1);
MBB->eraseFromParent();
}