48 #define DEBUG_TYPE "phi-node-elimination" 53 "during PHI elimination"));
62 cl::desc(
"Do not use an early exit if isLiveOutPastPHIs returns true."));
105 using BBVRegPair = std::pair<unsigned, unsigned>;
108 VRegPHIUse VRegPHIUseCount;
114 using LoweredPHIMap =
116 LoweredPHIMap LoweredPHIs;
121 STATISTIC(NumLowered,
"Number of phis lowered");
122 STATISTIC(NumCriticalEdgesSplit,
"Number of critical edges split");
123 STATISTIC(NumReused,
"Number of reused lowered phis");
130 "Eliminate PHI nodes for register allocation",
136 void PHIElimination::getAnalysisUsage(
AnalysisUsage &AU)
const {
148 LV = getAnalysisIfAvailable<LiveVariables>();
149 LIS = getAnalysisIfAvailable<LiveIntervals>();
151 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 VRegPHIUseCount.clear();
210 LowerPHINode(MBB, LastPHIIt);
220 if (!DI.isImplicitDef())
252 unsigned IncomingReg = 0;
253 bool reusedIncoming =
false;
263 TII->
get(TargetOpcode::IMPLICIT_DEF), DestReg);
267 unsigned &
entry = LoweredPHIs[MPhi];
271 reusedIncoming =
true;
280 TII->
get(TargetOpcode::COPY), DestReg)
281 .addReg(IncomingReg);
292 LV->setPHIJoin(IncomingReg);
300 LV->removeVirtualRegisterKilled(IncomingReg, *OldKill);
308 LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
314 LV->removeVirtualRegistersKilled(*MPhi);
318 LV->addVirtualRegisterDead(DestReg, PHICopy);
319 LV->removeVirtualRegisterDead(DestReg, *MPhi);
326 LIS->InsertMachineInstrInMaps(*std::prev(AfterPHIsIt));
328 SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB);
332 LiveInterval &IncomingLI = LIS->createEmptyInterval(IncomingReg);
336 LIS->getVNInfoAllocator());
337 IncomingLI.
addSegment(LiveInterval::Segment(MBBStartIndex,
344 "PHIs should have nonempty LiveIntervals.");
350 assert(OrigDestVNI &&
"PHI destination should be live at block entry.");
353 LIS->getVNInfoAllocator());
360 assert(DestVNI &&
"PHI destination should be live at its definition.");
373 for (
int i = NumSrcs - 1; i >= 0; --i) {
379 "Machine PHI Operands must all be virtual registers!");
388 if (!MBBsInsertedInto.
insert(&opBlock).second)
398 if (!reusedIncoming && IncomingReg) {
404 TII->
get(TargetOpcode::IMPLICIT_DEF),
410 ImpDefs.insert(
DefMI);
413 TII->
get(TargetOpcode::COPY), IncomingReg)
414 .addReg(SrcReg, 0, SrcSubReg);
421 if (LV && !SrcUndef &&
422 !VRegPHIUseCount[BBVRegPair(opBlock.
getNumber(), SrcReg)] &&
423 !LV->isLiveOut(SrcReg, opBlock)) {
443 Term != opBlock.
end(); ++Term) {
444 if (Term->readsRegister(SrcReg))
448 if (KillInst == opBlock.
end()) {
451 if (reusedIncoming || !IncomingReg) {
453 KillInst = FirstTerm;
454 while (KillInst != opBlock.
begin()) {
456 if (KillInst->isDebugInstr())
458 if (KillInst->readsRegister(SrcReg))
463 KillInst = std::prev(InsertPos);
466 assert(KillInst->readsRegister(SrcReg) &&
"Cannot find kill instruction");
469 LV->addVirtualRegisterKilled(SrcReg, *KillInst);
472 unsigned opBlockNum = opBlock.
getNumber();
473 LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum);
478 LIS->InsertMachineInstrInMaps(*NewSrcInstr);
479 LIS->addSegmentToEndOfBlock(IncomingReg, *NewSrcInstr);
483 !VRegPHIUseCount[BBVRegPair(opBlock.
getNumber(), SrcReg)]) {
493 if (VNI && VNI->
def != startIdx) {
503 Term != opBlock.
end(); ++Term) {
504 if (Term->readsRegister(SrcReg))
508 if (KillInst == opBlock.
end()) {
511 if (reusedIncoming || !IncomingReg) {
513 KillInst = FirstTerm;
514 while (KillInst != opBlock.
begin()) {
516 if (KillInst->isDebugInstr())
518 if (KillInst->readsRegister(SrcReg))
523 KillInst = std::prev(InsertPos);
526 assert(KillInst->readsRegister(SrcReg) &&
527 "Cannot find kill instruction");
529 SlotIndex LastUseIndex = LIS->getInstructionIndex(*KillInst);
531 LIS->getMBBEndIdx(&opBlock));
538 if (reusedIncoming || !IncomingReg) {
540 LIS->RemoveMachineInstrFromMaps(*MPhi);
550 for (
const auto &MBB : MF)
551 for (
const auto &BBI : MBB) {
554 for (
unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
555 ++VRegPHIUseCount[BBVRegPair(BBI.getOperand(i+1).getMBB()->getNumber(),
556 BBI.getOperand(i).getReg())];
567 bool IsLoopHeader = CurLoop && &MBB == CurLoop->
getHeader();
569 bool Changed =
false;
571 BBI != BBE && BBI->isPHI(); ++BBI) {
572 for (
unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
573 unsigned Reg = BBI->getOperand(i).getReg();
593 bool ShouldSplit = isLiveOutPastPHIs(Reg, PreMBB);
610 ShouldSplit = ShouldSplit && !isLiveIn(Reg, &MBB);
613 if (!ShouldSplit && CurLoop != PreLoop) {
615 dbgs() <<
"Split wouldn't help, maybe avoid loop copies?\n";
617 dbgs() <<
"PreLoop: " << *PreLoop;
619 dbgs() <<
"CurLoop: " << *CurLoop;
625 ShouldSplit = PreLoop && !PreLoop->
contains(CurLoop);
634 ++NumCriticalEdgesSplit;
642 "isLiveIn() requires either LiveVariables or LiveIntervals");
644 return LIS->isLiveInToMBB(LIS->getInterval(Reg), MBB);
646 return LV->isLiveIn(Reg, *MBB);
649 bool PHIElimination::isLiveOutPastPHIs(
unsigned Reg,
652 "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals");
661 if (LI.
liveAt(LIS->getMBBStartIdx(
SI)))
665 return LV->isLiveOut(Reg, *MBB);
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
MachineBasicBlock * getMBB() const
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
SlotIndex def
The index of the defining instruction.
Compute iterated dominance frontiers using a linear time algorithm.
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.
unsigned getReg() const
getReg - Returns the register number.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
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. ...
MachineInstr * findKill(const MachineBasicBlock *MBB) const
findKill - Find a kill instruction in MBB. Return NULL if none is found.
VNInfo - Value Number Information.
static bool isImplicitlyDefined(unsigned VirtReg, const MachineRegisterInfo *MRI)
isImplicitlyDefined - Return true if all defs of VirtReg are implicit-defs.
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...
const HexagonInstrInfo * TII
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Printable printReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
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.
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.
bool liveAt(SlotIndex index) const
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
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...
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...
static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi, const MachineRegisterInfo *MRI)
isSourceDefinedByImplicitDef - Return true if all sources of the phi node are implicit_def's.
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
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
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
unsigned createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...