49 #define DEBUG_TYPE "phi-node-elimination" 54 "during PHI elimination"));
63 cl::desc(
"Do not use an early exit if isLiveOutPastPHIs returns true."));
106 using BBVRegPair = std::pair<unsigned, unsigned>;
109 VRegPHIUse VRegPHIUseCount;
115 using LoweredPHIMap =
117 LoweredPHIMap LoweredPHIs;
122 STATISTIC(NumLowered,
"Number of phis lowered");
123 STATISTIC(NumCriticalEdgesSplit,
"Number of critical edges split");
124 STATISTIC(NumReused,
"Number of reused lowered phis");
131 "Eliminate PHI nodes for register allocation",
137 void PHIElimination::getAnalysisUsage(
AnalysisUsage &AU)
const {
149 LV = getAnalysisIfAvailable<LiveVariables>();
150 LIS = getAnalysisIfAvailable<LiveIntervals>();
152 bool Changed =
false;
161 Changed |= SplitPHIEdges(MF, MBB, MLI);
169 Changed |= EliminatePHINodes(MF, MBB);
174 if (
MRI->use_nodbg_empty(DefReg)) {
176 LIS->RemoveMachineInstrFromMaps(*
DefMI);
182 for (
auto &
I : LoweredPHIs) {
184 LIS->RemoveMachineInstrFromMaps(*
I.first);
185 MF.DeleteMachineInstr(
I.first);
190 if (
auto *MDT = getAnalysisIfAvailable<MachineDominatorTree>())
191 MDT->getBase().recalculate(MF);
195 VRegPHIUseCount.clear();
214 LowerPHINode(MBB, LastPHIIt);
224 if (!DI.isImplicitDef())
256 unsigned IncomingReg = 0;
257 bool reusedIncoming =
false;
268 TII->
get(TargetOpcode::IMPLICIT_DEF), DestReg);
272 unsigned &
entry = LoweredPHIs[MPhi];
276 reusedIncoming =
true;
286 IncomingReg, DestReg);
295 LV->setPHIJoin(IncomingReg);
303 LV->removeVirtualRegisterKilled(IncomingReg, *OldKill);
311 LV->addVirtualRegisterKilled(IncomingReg, *PHICopy);
317 LV->removeVirtualRegistersKilled(*MPhi);
321 LV->addVirtualRegisterDead(DestReg, *PHICopy);
322 LV->removeVirtualRegisterDead(DestReg, *MPhi);
328 SlotIndex DestCopyIndex = LIS->InsertMachineInstrInMaps(*PHICopy);
330 SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB);
334 LiveInterval &IncomingLI = LIS->createEmptyInterval(IncomingReg);
338 LIS->getVNInfoAllocator());
339 IncomingLI.
addSegment(LiveInterval::Segment(MBBStartIndex,
346 "PHIs should have nonempty LiveIntervals.");
352 assert(OrigDestVNI &&
"PHI destination should be live at block entry.");
355 LIS->getVNInfoAllocator());
362 assert(DestVNI &&
"PHI destination should be live at its definition.");
375 for (
int i = NumSrcs - 1; i >= 0; --i) {
381 "Machine PHI Operands must all be virtual registers!");
390 if (!MBBsInsertedInto.
insert(&opBlock).second)
400 if (!reusedIncoming && IncomingReg) {
406 TII->
get(TargetOpcode::IMPLICIT_DEF),
412 ImpDefs.insert(
DefMI);
416 SrcReg, SrcSubReg, IncomingReg);
423 if (LV && !SrcUndef &&
424 !VRegPHIUseCount[BBVRegPair(opBlock.
getNumber(), SrcReg)] &&
425 !LV->isLiveOut(SrcReg, opBlock)) {
445 Term != opBlock.
end(); ++Term) {
446 if (Term->readsRegister(SrcReg))
450 if (KillInst == opBlock.
end()) {
453 if (reusedIncoming || !IncomingReg) {
455 KillInst = FirstTerm;
456 while (KillInst != opBlock.
begin()) {
458 if (KillInst->isDebugInstr())
460 if (KillInst->readsRegister(SrcReg))
465 KillInst = NewSrcInstr;
468 assert(KillInst->readsRegister(SrcReg) &&
"Cannot find kill instruction");
471 LV->addVirtualRegisterKilled(SrcReg, *KillInst);
474 unsigned opBlockNum = opBlock.
getNumber();
475 LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum);
480 LIS->InsertMachineInstrInMaps(*NewSrcInstr);
481 LIS->addSegmentToEndOfBlock(IncomingReg, *NewSrcInstr);
485 !VRegPHIUseCount[BBVRegPair(opBlock.
getNumber(), SrcReg)]) {
495 if (VNI && VNI->
def != startIdx) {
505 Term != opBlock.
end(); ++Term) {
506 if (Term->readsRegister(SrcReg))
510 if (KillInst == opBlock.
end()) {
513 if (reusedIncoming || !IncomingReg) {
515 KillInst = FirstTerm;
516 while (KillInst != opBlock.
begin()) {
518 if (KillInst->isDebugInstr())
520 if (KillInst->readsRegister(SrcReg))
525 KillInst = std::prev(InsertPos);
528 assert(KillInst->readsRegister(SrcReg) &&
529 "Cannot find kill instruction");
531 SlotIndex LastUseIndex = LIS->getInstructionIndex(*KillInst);
533 LIS->getMBBEndIdx(&opBlock));
540 if (reusedIncoming || !IncomingReg) {
542 LIS->RemoveMachineInstrFromMaps(*MPhi);
552 for (
const auto &MBB : MF)
553 for (
const auto &BBI : MBB) {
556 for (
unsigned i = 1,
e = BBI.getNumOperands(); i !=
e; i += 2)
557 ++VRegPHIUseCount[BBVRegPair(BBI.getOperand(i+1).getMBB()->getNumber(),
558 BBI.getOperand(i).getReg())];
569 bool IsLoopHeader = CurLoop && &MBB == CurLoop->
getHeader();
571 bool Changed =
false;
573 BBI != BBE && BBI->isPHI(); ++BBI) {
574 for (
unsigned i = 1,
e = BBI->getNumOperands(); i !=
e; i += 2) {
595 bool ShouldSplit = isLiveOutPastPHIs(Reg, PreMBB);
612 ShouldSplit = ShouldSplit && !isLiveIn(Reg, &MBB);
615 if (!ShouldSplit && CurLoop != PreLoop) {
617 dbgs() <<
"Split wouldn't help, maybe avoid loop copies?\n";
619 dbgs() <<
"PreLoop: " << *PreLoop;
621 dbgs() <<
"CurLoop: " << *CurLoop;
627 ShouldSplit = PreLoop && !PreLoop->
contains(CurLoop);
636 ++NumCriticalEdgesSplit;
644 "isLiveIn() requires either LiveVariables or LiveIntervals");
646 return LIS->isLiveInToMBB(LIS->getInterval(Reg), MBB);
648 return LV->isLiveIn(Reg, *MBB);
651 bool PHIElimination::isLiveOutPastPHIs(
unsigned Reg,
654 "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals");
663 if (LI.
liveAt(LIS->getMBBStartIdx(
SI)))
667 return LV->isLiveOut(Reg, *MBB);
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
MachineBasicBlock * getMBB() const
SlotIndex def
The index of the defining instruction.
This class represents lattice values for constants.
Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LiveInterval - This class represents the liveness of a register, or stack slot.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
MachineBasicBlock::iterator findPHICopyInsertPoint(MachineBasicBlock *MBB, MachineBasicBlock *SuccMBB, unsigned SrcReg)
findPHICopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg when following the CFG...
unsigned getSubReg() const
bool isDead() const
isDead - Returns true if this is a dead def kill slot.
VarInfo - This represents the regions where a virtual register is live in the program.
STATISTIC(NumFunctions, "Total number of functions")
unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found. ...
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MachineInstr * findKill(const MachineBasicBlock *MBB) const
findKill - Find a kill instruction in MBB. Return NULL if none is found.
VNInfo - Value Number Information.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< succ_iterator > successors()
#define INITIALIZE_PASS_DEPENDENCY(depName)
SlotIndex getDeadSlot() const
Returns the dead def kill slot for the current instruction.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
static bool isImplicitlyDefined(unsigned VirtReg, const MachineRegisterInfo &MRI)
Return true if all defs of VirtReg are implicit-defs.
const HexagonInstrInfo * TII
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
unsigned getNumOperands() const
Retuns the total number of operands.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
BlockT * getHeader() const
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
virtual const TargetInstrInfo * getInstrInfo() const
static cl::opt< bool > NoPhiElimLiveOutEarlyExit("no-phi-elim-live-out-early-exit", cl::init(false), cl::Hidden, cl::desc("Do not use an early exit if isLiveOutPastPHIs returns true."))
VNInfo * createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc)
createDeadDef - Make sure the range has a value defined at Def.
TargetInstrInfo - Interface to description of machine instruction set.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions...
Eliminate PHI nodes for register allocation
void removeValNo(VNInfo *ValNo)
removeValNo - Remove all the segments defined by the specified value#.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
virtual MachineInstr * createPHIDestinationCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
initializer< Ty > init(const Ty &Val)
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
iterator SkipPHIsAndLabels(iterator I)
Return the first instruction in MBB after I that is not a PHI or a label.
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual MachineInstr * createPHISourceCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
bool liveAt(SlotIndex index) const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
INITIALIZE_PASS_BEGIN(PHIElimination, DEBUG_TYPE, "Eliminate PHI nodes for register allocation", false, false) INITIALIZE_PASS_END(PHIElimination
static bool allPhiOperandsUndefined(const MachineInstr &MPhi, const MachineRegisterInfo &MRI)
Return true if all sources of the phi node are implicit_def's, or undef's.
succ_iterator succ_begin()
void DeleteMachineInstr(MachineInstr *MI)
DeleteMachineInstr - Delete the given MachineInstr.
bool isImplicitDef() const
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void initializePHIEliminationPass(PassRegistry &)
void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified segment from this range.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
MachineOperand class - Representation of each machine instruction operand.
MachineInstrBuilder MachineInstrBuilder & DefMI
MachineInstr * remove(MachineInstr *I)
Remove the unbundled instruction from the instruction list without deleting it.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
unsigned succ_size() const
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< typename GraphTraits< GraphType >::nodes_iterator > nodes(const GraphType &G)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
static cl::opt< bool > DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false), cl::Hidden, cl::desc("Disable critical edge splitting " "during PHI elimination"))
bool isEHPad() const
Returns true if the block is a landing pad.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
VNInfo * getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
MachineBasicBlock * SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P)
Split the critical edge from this block to the given successor block, and return the newly created bl...
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
iterator_range< def_instr_iterator > def_instructions(unsigned Reg) const
static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg)
print Instructions which execute on loop entry
Register getReg() const
getReg - Returns the register number.
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
const MachineOperand & getOperand(unsigned i) const
SlotIndex - An opaque wrapper around machine indexes.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
std::vector< MachineBasicBlock * >::iterator succ_iterator
Wrapper class representing virtual and physical registers.
This file describes how to lower LLVM code to machine code.