50#define DEBUG_TYPE "phi-node-elimination"
55 cl::desc(
"Disable critical edge splitting "
56 "during PHI elimination"));
61 cl::desc(
"Split all critical edges during "
66 cl::desc(
"Do not use an early exit if isLiveOutPastPHIs returns true."));
70class PHIEliminationImpl {
84 bool AllEdgesCritical);
104 using BBVRegPair = std::pair<unsigned, Register>;
108 VRegPHIUse VRegPHIUseCount;
114 using LoweredPHIMap =
116 LoweredPHIMap LoweredPHIs;
130 LV = LVWrapper ? &LVWrapper->getLV() :
nullptr;
131 LIS = LISWrapper ? &LISWrapper->getLIS() :
nullptr;
132 MLI = MLIWrapper ? &MLIWrapper->getLI() :
nullptr;
133 MDT = MDTWrapper ? &MDTWrapper->getDomTree() :
nullptr;
134 PDT = PDTWrapper ? &PDTWrapper->getPostDomTree() :
nullptr;
138 : LV(AM.getCachedResult<LiveVariablesAnalysis>(MF)),
139 LIS(AM.getCachedResult<LiveIntervalsAnalysis>(MF)),
140 MLI(AM.getCachedResult<MachineLoopAnalysis>(MF)),
141 MDT(AM.getCachedResult<MachineDominatorTreeAnalysis>(MF)),
142 PDT(AM.getCachedResult<MachinePostDominatorTreeAnalysis>(MF)),
145 bool run(MachineFunction &MF);
152 PHIElimination() : MachineFunctionPass(ID) {
156 bool runOnMachineFunction(MachineFunction &MF)
override {
157 PHIEliminationImpl Impl(
this);
161 MachineFunctionProperties getSetProperties()
const override {
162 return MachineFunctionProperties().setNoPHIs();
165 void getAnalysisUsage(AnalysisUsage &AU)
const override;
173 PHIEliminationImpl Impl(MF, MFAM);
188STATISTIC(NumCriticalEdgesSplit,
"Number of critical edges split");
191char PHIElimination::ID = 0;
196 "Eliminate PHI nodes for register allocation",
false,
202void PHIElimination::getAnalysisUsage(
AnalysisUsage &AU)
const {
217 MachineDomTreeUpdater::UpdateStrategy::Lazy);
225 std::vector<SparseBitVector<>> LiveInSets;
227 LiveInSets.resize(MF.
size());
228 for (
unsigned Index = 0, e =
MRI->getNumVirtRegs(); Index != e; ++Index) {
238 while (AliveBlockItr != EndItr) {
239 unsigned BlockNum = *(AliveBlockItr++);
240 LiveInSets[BlockNum].set(Index);
245 if (
VI.Kills.size() > 1 ||
246 (!
VI.Kills.empty() &&
VI.Kills.front()->getParent() != DefMBB))
247 for (
auto *
MI :
VI.Kills)
248 LiveInSets[
MI->getParent()->getNumber()].set(Index);
254 SplitPHIEdges(MF,
MBB, MLI, (LV ? &LiveInSets :
nullptr), MDTU);
271 if (
MRI->use_nodbg_empty(DefReg)) {
279 for (
auto &
I : LoweredPHIs) {
282 MF.deleteMachineInstr(
I.first);
287 VRegPHIUseCount.clear();
289 MF.getProperties().setNoPHIs();
311 if (Pred->succ_size() < 2) {
312 AllEdgesCritical =
false;
318 LowerPHINode(
MBB, LastPHIIt, AllEdgesCritical);
328 if (!DI.isImplicitDef())
346 bool AllEdgesCritical) {
362 bool EliminateNow =
true;
363 bool reusedIncoming =
false;
374 TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
381 if (AllEdgesCritical)
382 Entry = &LoweredPHIs[MPhi];
383 if (Entry && *Entry) {
385 IncomingReg = *
Entry;
386 reusedIncoming =
true;
394 EliminateNow =
false;
395 *
Entry = IncomingReg;
400 PHICopy =
TII->createPHIDestinationCopy(
420 bool IsPHICopyAfterOldKill =
false;
422 if (reusedIncoming && (OldKill =
VI.findKill(&
MBB))) {
434 IsPHICopyAfterOldKill =
true;
443 if (IsPHICopyAfterOldKill) {
454 if (!OldKill || IsPHICopyAfterOldKill)
484 MBBStartIndex, DestCopyIndex.
getRegSlot(), IncomingVNI));
488 assert(!DestLI.
empty() &&
"PHIs should have non-empty LiveIntervals.");
496 for (
auto LR : ToUpdate) {
497 auto DestSegment = LR->find(MBBStartIndex);
498 assert(DestSegment != LR->end() &&
499 "PHI destination must be live in block");
501 if (LR->endIndex().isDead()) {
505 VNInfo *OrigDestVNI = LR->getVNInfoAt(DestSegment->start);
506 assert(OrigDestVNI &&
"PHI destination should be live at block entry.");
507 LR->removeSegment(DestSegment->start, DestSegment->start.getDeadSlot());
509 LR->removeValNo(OrigDestVNI);
516 if (DestSegment->start > NewStart) {
517 VNInfo *VNI = LR->getVNInfoAt(DestSegment->start);
518 assert(VNI &&
"value should be defined for known segment");
521 }
else if (DestSegment->start < NewStart) {
522 assert(DestSegment->start >= MBBStartIndex);
524 LR->removeSegment(DestSegment->start, NewStart);
526 VNInfo *DestVNI = LR->getVNInfoAt(NewStart);
527 assert(DestVNI &&
"PHI destination should be live at its definition.");
528 DestVNI->
def = NewStart;
536 --VRegPHIUseCount[BBVRegPair(
546 for (
int i = NumSrcs - 1; i >= 0; --i) {
552 "Machine PHI Operands must all be virtual registers!");
561 if (!MBBsInsertedInto.
insert(&opBlock).second)
565 if (SrcRegDef &&
TII->isUnspillableTerminator(SrcRegDef)) {
568 "Expected operand 0 to be a reg def!");
572 "Expected a single use from UnspillableTerminator");
593 if (!reusedIncoming && IncomingReg) {
600 TII->get(TargetOpcode::IMPLICIT_DEF), IncomingReg);
605 ImpDefs.insert(
DefMI);
609 NewSrcInstr =
TII->createPHISourceCopy(opBlock, InsertPos,
nullptr,
610 SrcReg, SrcSubReg, IncomingReg);
617 if (LV && !SrcUndef &&
618 !VRegPHIUseCount[BBVRegPair(opBlock.
getNumber(), SrcReg)] &&
639 if (
Term->readsRegister(SrcReg,
nullptr))
643 if (KillInst == opBlock.
end()) {
646 if (reusedIncoming || !IncomingReg) {
648 KillInst = InsertPos;
649 while (KillInst != opBlock.
begin()) {
651 if (KillInst->isDebugInstr())
653 if (KillInst->readsRegister(SrcReg,
nullptr))
658 KillInst = NewSrcInstr;
661 assert(KillInst->readsRegister(SrcReg,
nullptr) &&
662 "Cannot find kill instruction");
668 unsigned opBlockNum = opBlock.
getNumber();
679 !VRegPHIUseCount[BBVRegPair(opBlock.
getNumber(), SrcReg)]) {
688 if (VNI && VNI->
def != startIdx) {
698 if (
Term->readsRegister(SrcReg,
nullptr))
702 if (KillInst == opBlock.
end()) {
705 if (reusedIncoming || !IncomingReg) {
707 KillInst = InsertPos;
708 while (KillInst != opBlock.
begin()) {
710 if (KillInst->isDebugInstr())
712 if (KillInst->readsRegister(SrcReg,
nullptr))
717 KillInst = std::prev(InsertPos);
720 assert(KillInst->readsRegister(SrcReg,
nullptr) &&
721 "Cannot find kill instruction");
739 MF.deleteMachineInstr(MPhi);
748 for (
const auto &
MBB : MF) {
749 for (
const auto &BBI :
MBB) {
752 for (
unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
753 if (!BBI.getOperand(i).isUndef()) {
754 ++VRegPHIUseCount[BBVRegPair(
755 BBI.getOperand(i + 1).getMBB()->getNumber(),
756 BBI.getOperand(i).getReg())];
763bool PHIEliminationImpl::SplitPHIEdges(
770 bool IsLoopHeader = CurLoop && &
MBB == CurLoop->
getHeader();
774 BBI != BBE && BBI->isPHI(); ++BBI) {
775 for (
unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
796 bool ShouldSplit = isLiveOutPastPHIs(
Reg, PreMBB);
813 ShouldSplit = ShouldSplit && !isLiveIn(
Reg, &
MBB);
816 if (!ShouldSplit && CurLoop != PreLoop) {
818 dbgs() <<
"Split wouldn't help, maybe avoid loop copies?\n";
820 dbgs() <<
"PreLoop: " << *PreLoop;
822 dbgs() <<
"CurLoop: " << *CurLoop;
828 ShouldSplit = PreLoop && !PreLoop->
contains(CurLoop);
838 ++NumCriticalEdgesSplit;
846 "isLiveIn() requires either LiveVariables or LiveIntervals");
853bool PHIEliminationImpl::isLiveOutPastPHIs(
Register Reg,
856 "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals");
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
const HexagonInstrInfo * TII
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.
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."))
static bool isImplicitlyDefined(Register VirtReg, const MachineRegisterInfo &MRI)
Return true if all defs of VirtReg are implicit-defs.
static cl::opt< bool > DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false), cl::Hidden, cl::desc("Disable critical edge splitting " "during PHI elimination"))
static cl::opt< bool > SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), cl::Hidden, cl::desc("Split all critical edges during " "PHI elimination"))
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg)
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
This file defines the SmallPtrSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Represent the analysis usage information of a pass.
LiveInterval - This class represents the liveness of a register, or stack slot.
iterator_range< subrange_iterator > subranges()
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LiveInterval & getOrCreateEmptyInterval(Register Reg)
Return an existing interval for Reg.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
VNInfo::Allocator & getVNInfoAllocator()
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
LLVM_ABI LiveInterval::Segment addSegmentToEndOfBlock(Register Reg, MachineInstr &startInst)
Given a register and an instruction, adds a live segment from that instruction to the end of its MBB.
bool isLiveInToMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
bool liveAt(SlotIndex index) const
VNInfo * getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
LLVM_ABI void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified interval from this live range.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
bool removeVirtualRegisterDead(Register Reg, MachineInstr &MI)
removeVirtualRegisterDead - Remove the specified kill of the virtual register from the live variable ...
bool removeVirtualRegisterKilled(Register Reg, MachineInstr &MI)
removeVirtualRegisterKilled - Remove the specified kill of the virtual register from the live variabl...
LLVM_ABI void removeVirtualRegistersKilled(MachineInstr &MI)
removeVirtualRegistersKilled - Remove all killed info for the specified instruction.
void addVirtualRegisterDead(Register IncomingReg, MachineInstr &MI, bool AddIfNotFound=false)
addVirtualRegisterDead - Add information about the fact that the specified register is dead after bei...
LLVM_ABI bool isLiveOut(Register Reg, const MachineBasicBlock &MBB)
isLiveOut - Determine if Reg is live out from MBB, when not considering PHI nodes.
bool isLiveIn(Register Reg, const MachineBasicBlock &MBB)
void addVirtualRegisterKilled(Register IncomingReg, MachineInstr &MI, bool AddIfNotFound=false)
addVirtualRegisterKilled - Add information about the fact that the specified register is killed after...
LLVM_ABI VarInfo & getVarInfo(Register Reg)
getVarInfo - Return the VarInfo structure for the specified VIRTUAL register.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
unsigned pred_size() const
bool isEHPad() const
Returns true if the block is a landing pad.
MachineBasicBlock * SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P, std::vector< SparseBitVector<> > *LiveInSets=nullptr, MachineDomTreeUpdater *MDTU=nullptr)
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator SkipPHIsAndLabels(iterator I)
Return the first instruction in MBB after I that is not a PHI or a label.
MachineInstr * remove(MachineInstr *I)
Remove the unbundled instruction from the instruction list without deleting it.
unsigned succ_size() const
LLVM_ABI void dump() const
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Location of a PHI instruction that is also a debug-info variable value, for the duration of register ...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
DenseMap< unsigned, DebugPHIRegallocPos > DebugPHIPositions
Map of debug instruction numbers to the position of their PHI instructions during register allocation...
Representation of each machine instruction.
bool isImplicitDef() const
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
unsigned peekDebugInstrNum() const
Examine the instruction number of this MachineInstr.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const MachineOperand & getOperand(unsigned i) const
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Wrapper class representing virtual and physical registers.
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
SlotIndex - An opaque wrapper around machine indexes.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
SparseBitVectorIterator iterator
TargetInstrInfo - Interface to description of machine instruction set.
virtual const TargetInstrInfo * getInstrInfo() const
VNInfo - Value Number Information.
SlotIndex def
The index of the defining instruction.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
MachineBasicBlock::iterator findPHICopyInsertPoint(MachineBasicBlock *MBB, MachineBasicBlock *SuccMBB, Register SrcReg)
findPHICopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg when following the CFG...
LLVM_ABI unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found.
LLVM_ABI void initializePHIEliminationPass(PassRegistry &)
LLVM_ABI char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions.
LLVM_ABI 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.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
This represents a simple continuous liveness interval for a value.
VarInfo - This represents the regions where a virtual register is live in the program.
SparseBitVector AliveBlocks
AliveBlocks - Set of blocks in which this value is alive completely through.