54#define DEBUG_TYPE "phi-node-elimination"
58class PHIEliminationImpl {
59 const CodeGenOptions *Opts =
nullptr;
75 bool AllEdgesCritical);
92 using BBVRegPair = std::pair<unsigned, Register>;
96 VRegPHIUse VRegPHIUseCount;
98 struct PHISrcLaneKill {
103 using PHISrcLaneKillMap =
110 auto It = Kills.
end();
111 if (!Kills.
empty() && Index < Kills.
back().Index) {
114 return Idx <
Kill.Index;
118 Kills.
insert(It, {Lanes, Index});
123 PHISrcLaneKillMap PHISrcLaneKills;
129 using LoweredPHIMap =
131 LoweredPHIMap LoweredPHIs;
135 std::vector<SparseBitVector<>> LiveOutSets;
151 SI = SIWrapper ? &SIWrapper->getSI() :
nullptr;
152 LIS = LISWrapper ? &LISWrapper->getLIS() :
nullptr;
153 MLI = MLIWrapper ? &MLIWrapper->getLI() :
nullptr;
154 MDT = MDTWrapper ? &MDTWrapper->getDomTree() :
nullptr;
155 PDT = PDTWrapper ? &PDTWrapper->getPostDomTree() :
nullptr;
156 MBPI = MBPIWrapper ? &MBPIWrapper->getMBPI() :
nullptr;
179 PHIEliminationImpl Impl(
this);
195 PHIEliminationImpl Impl(MF, MFAM);
210STATISTIC(NumCriticalEdgesSplit,
"Number of critical edges split");
213char PHIElimination::ID = 0;
218 "Eliminate PHI nodes for register allocation",
false,
227void PHIElimination::getAnalysisUsage(
AnalysisUsage &AU)
const {
246 MachineDomTreeUpdater::UpdateStrategy::Lazy);
251 if (Opts->phi_elim_edge_splitting && LIS) {
272 SI->removeMachineInstrFromMaps(*
DefMI);
278 for (
auto &
I : LoweredPHIs) {
280 SI->removeMachineInstrFromMaps(*
I.first);
281 MF.deleteMachineInstr(
I.first);
286 VRegPHIUseCount.clear();
287 PHISrcLaneKills.clear();
289 MF.getProperties().setNoPHIs();
298 for (
auto I =
MBB.begin();
I != Position;) {
299 if (!
I->isDebugInstr()) {
307 MBB.splice(InsertPt, &
MBB, DebugBegin,
I);
333 if (
Pred->succ_size() < 2) {
334 AllEdgesCritical =
false;
340 LowerPHINode(
MBB, LastPHIIt, AllEdgesCritical);
350 if (!DI.isImplicitDef())
368 bool AllEdgesCritical) {
383 bool EliminateNow =
true;
384 bool reusedIncoming =
false;
396 TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
403 if (AllEdgesCritical)
404 Entry = &LoweredPHIs[MPhi];
405 if (Entry && *Entry) {
407 IncomingReg = *
Entry;
408 reusedIncoming =
true;
416 EliminateNow =
false;
417 *
Entry = IncomingReg;
422 PHICopy =
TII->createPHIDestinationCopy(
439 DestCopyIndex =
SI->insertMachineInstrInMaps(*PHICopy);
443 "Expected a valid SlotIndex if LIS is available.");
448 LiveInterval &IncomingLI = LIS->getOrCreateEmptyInterval(IncomingReg);
452 IncomingLI.
getNextValue(MBBStartIndex, LIS->getVNInfoAllocator());
454 MBBStartIndex, DestCopyIndex.
getRegSlot(), IncomingVNI));
458 assert(!DestLI.
empty() &&
"PHIs should have non-empty LiveIntervals.");
471 for (
auto LR : ToUpdate) {
472 auto DestSegment = LR->find(MBBStartIndex);
473 assert(DestSegment != LR->end() &&
474 "PHI destination must be live in block");
476 if (LR->endIndex().isDead()) {
480 VNInfo *OrigDestVNI = LR->getVNInfoAt(DestSegment->start);
481 assert(OrigDestVNI &&
"PHI destination should be live at block entry.");
482 LR->removeSegment(DestSegment->start, DestSegment->start.getDeadSlot());
483 LR->createDeadDef(NewStart, LIS->getVNInfoAllocator());
484 LR->removeValNo(OrigDestVNI);
491 if (DestSegment->start > NewStart) {
492 VNInfo *VNI = LR->getVNInfoAt(DestSegment->start);
493 assert(VNI &&
"value should be defined for known segment");
496 }
else if (DestSegment->start < NewStart) {
497 assert(DestSegment->start >= MBBStartIndex);
499 LR->removeSegment(DestSegment->start, NewStart);
501 VNInfo *DestVNI = LR->getVNInfoAt(NewStart);
502 assert(DestVNI &&
"PHI destination should be live at its definition.");
503 DestVNI->
def = NewStart;
510 --VRegPHIUseCount[BBVRegPair(
520 for (
int i = NumSrcs - 1; i >= 0; --i) {
526 "Machine PHI Operands must all be virtual registers!");
535 if (!MBBsInsertedInto.
insert(&opBlock).second)
539 if (SrcRegDef &&
TII->isUnspillableTerminator(SrcRegDef)) {
542 "Expected operand 0 to be a reg def!");
546 "Expected a single use from UnspillableTerminator");
552 LiveInterval &IncomingLI = LIS->getOrCreateEmptyInterval(IncomingReg);
554 IncomingLI.
getNextValue(DefIdx, LIS->getVNInfoAllocator());
557 LIS->removeInterval(SrcReg);
570 if (!reusedIncoming && IncomingReg) {
577 TII->get(TargetOpcode::IMPLICIT_DEF), IncomingReg);
582 ImpDefs.insert(
DefMI);
586 NewSrcInstr =
TII->createPHISourceCopy(opBlock, InsertPos,
nullptr,
587 SrcReg, SrcSubReg, IncomingReg);
591 BBVRegPair SrcKey(opBlock.
getNumber(), SrcReg);
592 bool IsLastPHIUse = !VRegPHIUseCount.lookup(SrcKey);
594 if (
SI && NewSrcInstr)
595 SI->insertMachineInstrInMaps(*NewSrcInstr);
601 "Expected SI to be available to insert new MI if LIS is available");
602 LIS->addSegmentToEndOfBlock(IncomingReg, *NewSrcInstr);
604 if (!SrcUndef && LIS->getInterval(SrcReg).hasSubRanges()) {
606 PHISrcLaneKills[SrcKey],
TRI.getSubRegIndexLaneMask(SrcSubReg),
607 LIS->getInstructionIndex(*NewSrcInstr).getRegSlot());
611 if (!SrcUndef && IsLastPHIUse) {
616 SlotIndex startIdx = LIS->getMBBStartIdx(Succ);
620 if (VNI && VNI->
def != startIdx) {
626 PHISrcLaneKillMap::iterator KillsIt = PHISrcLaneKills.end();
628 KillsIt = PHISrcLaneKills.find(SrcKey);
635 LIS->getInstructionIndex(
MI).getRegSlot());
644 if (KillsIt != PHISrcLaneKills.end()) {
645 SlotIndex FirstCopyIndex = KillsIt->second.front().Index;
646 if (InsertPos == opBlock.
end() ||
647 FirstCopyIndex <= SI->getIndexBefore(*InsertPos).getRegSlot()) {
649 LIS->getInstructionFromIndex(FirstCopyIndex)));
656 if (
MI->isDebugInstr() ||
657 !
MI->readsRegister(SrcReg,
nullptr))
660 if (KillsIt != PHISrcLaneKills.end())
664 if (KillInst == opBlock.
end()) {
667 if (reusedIncoming || !IncomingReg) {
669 KillInst = InsertPos;
670 while (KillInst != opBlock.
begin()) {
672 if (KillInst->isDebugInstr())
674 if (KillInst->readsRegister(SrcReg,
nullptr))
677 if (KillsIt != PHISrcLaneKills.end())
678 RecordLaneKill(*KillInst);
681 KillInst = std::prev(InsertPos);
684 assert(KillInst->readsRegister(SrcReg,
nullptr) &&
685 "Cannot find kill instruction");
687 SlotIndex LastUseIndex = LIS->getInstructionIndex(*KillInst);
688 SlotIndex BlockEndIndex = LIS->getMBBEndIdx(&opBlock);
690 if (KillsIt != PHISrcLaneKills.end()) {
699 for (
const PHISrcLaneKill &
Kill :
reverse(KillsIt->second)) {
700 if ((
Kill.Lanes & SR.LaneMask).any()) {
701 if (
Kill.Index < EndIndex)
702 SR.removeSegment(
Kill.Index, EndIndex);
710 if (KillsIt != PHISrcLaneKills.end())
711 PHISrcLaneKills.erase(KillsIt);
719 SI->removeMachineInstrFromMaps(*MPhi);
720 MF.deleteMachineInstr(MPhi);
729 for (
const auto &
MBB : MF) {
730 for (
const auto &BBI :
MBB) {
733 for (
unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
734 if (!BBI.getOperand(i).isUndef()) {
735 ++VRegPHIUseCount[BBVRegPair(
736 BBI.getOperand(i + 1).getMBB()->getNumber(),
737 BBI.getOperand(i).getReg())];
752 bool IsLoopHeader = CurLoop && &
MBB == CurLoop->
getHeader();
756 BBI != BBE && BBI->isPHI(); ++BBI) {
757 for (
unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
766 if (PreMBB == &
MBB && !Opts->phi_elim_split_all_critical_edges)
769 if (IsLoopHeader && PreLoop == CurLoop &&
770 !Opts->phi_elim_split_all_critical_edges)
779 bool ShouldSplit = isLiveOutPastPHIs(
Reg, PreMBB);
780 if (!ShouldSplit && Opts->phi_elim_live_out_early_exit)
797 ShouldSplit && !LIS->isLiveInToMBB(LIS->getInterval(
Reg), &
MBB);
800 if (!ShouldSplit && CurLoop != PreLoop) {
802 dbgs() <<
"Split wouldn't help, maybe avoid loop copies?\n";
804 dbgs() <<
"PreLoop: " << *PreLoop;
806 dbgs() <<
"CurLoop: " << *CurLoop;
812 ShouldSplit = PreLoop && !PreLoop->
contains(CurLoop);
814 if (!ShouldSplit && !Opts->phi_elim_split_all_critical_edges)
816 if (LiveOutSets.empty())
817 computeLiveOutSets(MF);
828 MBFI->onEdgeSplit(*PreMBB, *NewBB, *MBPI);
832 ++NumCriticalEdgesSplit;
838void PHIEliminationImpl::computeLiveOutSets(
const MachineFunction &MF) {
843 if (!LIS->hasInterval(
Reg))
853bool PHIEliminationImpl::isLiveOutPastPHIs(
Register Reg,
860 if (LIS->isLiveInToMBB(LI,
SI))
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
Register const TargetRegisterInfo * TRI
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 bool isImplicitlyDefined(Register VirtReg, const MachineRegisterInfo &MRI)
Return true if all defs of VirtReg are implicit-defs.
static void moveDebugInstructionsAfter(MachineBasicBlock &MBB, MachineBasicBlock::iterator Position)
Move debug instructions preceding Position to immediately after it.
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
MachineRegisterInfo & MRI
static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg)
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)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
const HexagonRegisterInfo & getRegisterInfo() const
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
Result of a LiveRange query.
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction,...
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
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 contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
const MachineBlockFrequencyInfo & getMBFI() const
unsigned pred_size() const
bool isEHPad() const
Returns true if the block is a landing pad.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator SkipPHIsLabelsAndDebug(iterator I, Register Reg=Register(), bool SkipPseudoOp=true)
Return the first instruction in MBB after I that is not a PHI, label or debug.
MachineInstr * remove(MachineInstr *I)
Remove the unbundled instruction from the instruction list without deleting it.
unsigned succ_size() const
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineBasicBlock * SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P, MachineDomTreeUpdater *MDTU=nullptr)
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
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.
Properties which a MachineFunction may have at a given point in time.
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.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
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
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.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
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
void setIsDead(bool Val=true)
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 LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified 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...
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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.
bool isValid() const
Returns true if this is a valid index.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
bool isDead() const
isDead - Returns true if this is a dead def kill slot.
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.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
VNInfo - Value Number Information.
SlotIndex def
The index of the defining instruction.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
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.
@ Kill
The last use of a register.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
auto reverse(ContainerTy &&C)
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 char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions.
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
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.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
LLVM_ABI std::pair< LaneBitmask, LaneBitmask > AnalyzeVirtRegLanesInBundle(const MachineInstr &MI, Register Reg, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI)
Return a pair of lane masks (reads, writes) indicating which lanes this instruction uses with Reg.
MCRegisterClass TargetRegisterClass
This represents a simple continuous liveness interval for a value.