39#include "llvm/Config/llvm-config.h"
51#define DEBUG_TYPE "regalloc"
53STATISTIC(NumSpillSlots,
"Number of spill slots allocated");
54STATISTIC(NumIdCopies,
"Number of identity moves eliminated after rewriting");
67 TII = mf.getSubtarget().getInstrInfo();
68 TRI = mf.getSubtarget().getRegisterInfo();
72 Virt2StackSlotMap.clear();
73 Virt2SplitMap.clear();
74 Virt2ShapeMap.clear();
81 for (
const auto &
P : MRI->getPendingVirtRegMapEntries()) {
82 if (
P.AssignedPhys.isValid())
83 assignVirt2Phys(
P.VReg,
P.AssignedPhys);
86 if (
P.SplitFrom.isValid() &&
P.SplitFrom !=
P.VReg)
87 setIsSplitFromReg(
P.VReg,
P.SplitFrom);
89 MRI->clearPendingVirtRegMapEntries();
93 unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
94 Virt2PhysMap.resize(NumRegs);
95 Virt2StackSlotMap.resize(NumRegs);
96 Virt2SplitMap.resize(NumRegs);
101 assert(!Virt2PhysMap[virtReg] &&
102 "attempt to assign physical register to already mapped "
105 "Attempt to map virtReg to a reserved physReg");
106 Virt2PhysMap[virtReg] = physReg;
110 unsigned Size =
TRI->getSpillSize(*RC);
111 Align Alignment =
TRI->getSpillAlign(*RC);
114 Align CurrentAlign = ST.getFrameLowering()->getStackAlign();
115 if (Alignment > CurrentAlign && !
TRI->canRealignStack(*MF)) {
116 Alignment = CurrentAlign;
119 TRI->getSpillStackID(*RC));
125 Register Hint = MRI->getSimpleHint(VirtReg);
128 if (Hint.isVirtual())
134 std::pair<unsigned, Register> Hint = MRI->getRegAllocationHint(VirtReg);
135 if (Hint.second.isPhysical())
137 if (Hint.second.isVirtual())
145 "attempt to assign stack slot to already spilled register");
147 return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
153 "attempt to assign stack slot to already spilled register");
155 (SS >= MF->getFrameInfo().getObjectIndexBegin())) &&
156 "illegal fixed frame index");
157 Virt2StackSlotMap[virtReg] = SS;
161 OS <<
"********** REGISTER MAP **********\n";
162 for (
unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
164 if (Virt2PhysMap[Reg]) {
165 OS <<
'[' <<
printReg(Reg, TRI) <<
" -> "
166 <<
printReg(Virt2PhysMap[Reg], TRI) <<
"] "
167 << TRI->getRegClassName(MRI->getRegClass(Reg)) <<
"\n";
171 for (
unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
174 OS <<
'[' <<
printReg(Reg, TRI) <<
" -> fi#" << Virt2StackSlotMap[Reg]
175 <<
"] " << TRI->getRegClassName(MRI->getRegClass(Reg)) <<
"\n";
181#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
214class VirtRegRewriter {
228 void addMBBLiveIns();
242 : Indexes(Indexes), LIS(LIS), LRM(LRM), VRM(VRM), DebugVars(DebugVars),
243 ClearVirtRegs(ClearVirtRegs) {}
252 VirtRegRewriterLegacy(
bool ClearVirtRegs =
true)
253 : MachineFunctionPass(
ID), ClearVirtRegs(ClearVirtRegs) {}
255 void getAnalysisUsage(AnalysisUsage &AU)
const override;
257 bool runOnMachineFunction(MachineFunction&)
override;
259 MachineFunctionProperties getSetProperties()
const override {
261 return MachineFunctionProperties().setNoVRegs();
264 return MachineFunctionProperties();
270char VirtRegRewriterLegacy::ID = 0;
275 "Virtual Register Rewriter",
false,
false)
285void VirtRegRewriterLegacy::getAnalysisUsage(
AnalysisUsage &AU)
const {
286 AU.setPreservesCFG();
304 VirtRegMap &VRM = getAnalysis<VirtRegMapWrapperLegacy>().getVRM();
305 LiveIntervals &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
306 LiveRegMatrix &LRM = getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM();
307 SlotIndexes &Indexes = getAnalysis<SlotIndexesWrapperPass>().getSI();
309 getAnalysis<LiveDebugVariablesWrapperLegacy>().getLDV();
311 VirtRegRewriter
R(ClearVirtRegs, &Indexes, &LIS, &LRM, &VRM, &DebugVars);
327 VirtRegRewriter R(ClearVirtRegs, &Indexes, &LIS, &LRM, &VRM, &DebugVars);
349 LLVM_DEBUG(
dbgs() <<
"********** REWRITE VIRTUAL REGISTERS **********\n"
350 <<
"********** Function: " << MF->
getName() <<
'\n');
372 MRI->clearVirtRegs();
378void VirtRegRewriter::addLiveInsForSubRanges(
const LiveInterval &LI,
383 using SubRangeIteratorPair =
384 std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
390 SubRanges.
push_back(std::make_pair(&SR, SR.begin()));
391 if (!
First.isValid() || SR.segments.front().start <
First)
392 First = SR.segments.front().start;
393 if (!
Last.isValid() || SR.segments.back().end >
Last)
394 Last = SR.segments.back().end;
405 for (
auto &RangeIterPair : SubRanges) {
408 while (SRI != SR->
end() && SRI->end <= MBBBegin)
410 if (SRI == SR->
end())
412 if (SRI->start <= MBBBegin)
424void VirtRegRewriter::addMBBLiveIns() {
425 for (
unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
427 if (MRI->reg_nodbg_empty(VirtReg))
438 assert(!ClearVirtRegs &&
"Unmapped virtual register");
443 addLiveInsForSubRanges(LI, PhysReg);
449 for (
const auto &Seg : LI) {
467bool VirtRegRewriter::readsUndefSubreg(
const MachineOperand &MO)
const {
479 "Reads of completely dead register should be marked undef already");
492 if (!
MI.isIdentityCopy())
504 RewriteRegs.insert(DstReg);
512 if (
MI.getOperand(1).isUndef() ||
MI.getNumOperands() > 2) {
513 MI.setDesc(
TII->get(TargetOpcode::KILL));
520 MI.eraseFromBundle();
529 if (!
MI.isCopy() && !
MI.isKill())
532 if (
MI.isBundledWithPred() && !
MI.isBundledWithSucc()) {
539 I !=
E &&
I->isBundledWithSucc(); ++
I) {
540 if (!
I->isCopy() && !
I->isKill())
551 if (
TRI->regsOverlap(Dst->getOperand(0).getReg(),
552 Src->getOperand(1).getReg()))
560 for (
int E = MIs.size(), PrevE =
E;
E > 1; PrevE =
E) {
561 for (
int I =
E;
I--; )
562 if (!anyRegsAlias(MIs[
I],
ArrayRef(MIs).take_front(
E),
TRI)) {
568 MF->getFunction().getContext().emitError(
569 "register rewriting failed: cycle in copy bundle");
579 if (BundledMI != BundleStart) {
580 BundledMI->removeFromBundle();
582 }
else if (BundledMI->isBundledWithSucc()) {
583 BundledMI->unbundleFromSucc();
584 BundleStart = &*std::next(BundledMI->getIterator());
587 if (Indexes && BundledMI != FirstMI)
601 for (MCRegUnit Unit :
TRI->regunits(SuperPhysReg)) {
613 if (UnitRange.
liveAt(AfterMIDefs) && UnitRange.
liveAt(BeforeMIUses))
622LaneBitmask VirtRegRewriter::liveOutUndefPhiLanesForUndefSubregDef(
625 LaneBitmask UndefMask = ~TRI->getSubRegIndexLaneMask(SubReg);
634 LiveOutUndefLanes |= NeedImpDefLanes;
643 LiveOutUndefLanes &= ~InterferingLanes;
646 dbgs() <<
"Need live out undef defs for " << printReg(PhysReg)
647 << LiveOutUndefLanes <<
" from " << printMBBReference(MBB) <<
'\n';
650 return LiveOutUndefLanes;
653void VirtRegRewriter::rewrite() {
654 bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
666 MRI->addPhysRegsUsedFromRegMask(MO.
getRegMask());
677 RewriteRegs.insert(PhysReg);
678 assert(!MRI->isReserved(PhysReg) &&
"Reserved register assignment");
683 if (NoSubRegLiveness || !MRI->shouldTrackSubRegLiveness(VirtReg)) {
688 (MO.
isDef() && subRegLiveThrough(
MI, PhysReg)))
700 if (readsUndefSubreg(MO))
705 }
else if (!MO.
isDead()) {
711 liveOutUndefPhiLanesForUndefSubregDef(LI, *
MBBI, SubReg,
713 if (LiveOutUndefLanes.
any()) {
718 if (!
TRI->getCoveringSubRegIndexes(MRI->getRegClass(VirtReg),
722 "cannot represent required subregister defs");
729 for (
unsigned SubIdx : CoveringIndexes)
746 PhysReg =
TRI->getSubReg(PhysReg, SubReg);
747 assert(PhysReg.
isValid() &&
"Invalid SubReg for physical register");
758 while (!SuperKills.
empty())
761 while (!SuperDeads.
empty())
764 while (!SuperDefs.
empty())
769 expandCopyBundle(
MI);
772 handleIdentityCopy(
MI);
779 for (
Register PhysReg : RewriteRegs) {
780 for (MCRegUnit Unit :
TRI->regunits(PhysReg)) {
791 OS <<
"virt-reg-rewriter";
793 OS <<
"<no-clear-vregs>";
797 return new VirtRegRewriterLegacy(ClearVirtRegs);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
const HexagonInstrInfo * TII
A common definition of LaneBitmask for use in TableGen and CodeGen.
Register const TargetRegisterInfo * TRI
Promote Memory to Register
ModuleAnalysisManager MAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static bool isPhysical(const MachineOperand &MO)
This file defines the SmallVector 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 & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Represents analyses that only rely on functions' control flow.
Implements a dense probed hash-table based set.
FunctionPass class - This class is used to implement most global optimizations.
LLVM_ABI void emitDebugValues(VirtRegMap *VRM)
emitDebugValues - Emit new DBG_VALUE instructions reflecting the changes that happened during registe...
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()
LLVM_ABI void addKillFlags(const VirtRegMap *)
Add kill flags to any instruction that kills a virtual register.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void removeRegUnit(MCRegUnit Unit)
Remove computed live range for register unit Unit.
LiveInterval & getInterval(Register Reg)
LiveRange & getRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit.
LLVM_ABI MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
If LI is confined to a single basic block, return a pointer to that block.
bool isLiveOutOfMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
bool isLiveInToMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
This class represents the liveness of a register, stack slot, etc.
Segments::const_iterator const_iterator
bool liveAt(SlotIndex index) const
LLVM_ABI LaneBitmask checkInterferenceLanes(SlotIndex Start, SlotIndex End, MCRegister PhysReg)
Check for interference in the segment [Start, End) that may prevent assignment to PhysReg,...
Wrapper class representing physical registers. Should be passed by value.
constexpr bool isValid() const
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
LLVM_ABI void print(raw_ostream &OS, const SlotIndexes *=nullptr, bool IsStandalone=true) const
reverse_instr_iterator instr_rend()
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
iterator_range< succ_iterator > successors()
Instructions::reverse_iterator reverse_instr_iterator
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
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.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
BasicBlockListType::iterator iterator
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
void setIsInternalRead(bool Val=true)
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A Module instance is used to store all the information related to an LLVM module.
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 getBoundaryIndex() const
Returns the boundary index for associated with this index.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
MBBIndexIterator getMBBLowerBound(MBBIndexIterator Start, SlotIndex Idx) const
Get an iterator pointing to the first IdxMBBPair with SlotIndex greater than or equal to Idx.
LLVM_ABI void removeSingleMachineInstrFromMaps(MachineInstr &MI)
Removes a single machine instruction MI from the mapping.
MBBIndexIterator MBBIndexBegin() const
Returns an iterator for the begin of the idx2MBBMap.
MBBIndexIterator MBBIndexEnd() const
Return an iterator for the end of the idx2MBBMap.
SmallVectorImpl< IdxMBBPair >::const_iterator MBBIndexIterator
Iterator over the idx2MBBMap (sorted pairs of slot index of basic block begin and basic block)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
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
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
LLVM_ABI VirtRegMap run(MachineFunction &MF, MachineFunctionAnalysisManager &MAM)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI bool hasKnownPreference(Register VirtReg) const
returns true if VirtReg has a known preferred register.
LLVM_ABI int assignVirt2StackSlot(Register virtReg)
create a mapping for the specifed virtual register to the next available stack slot
void clearAllVirt()
clears all virtual to physical register mappings
LLVM_ABI void init(MachineFunction &MF)
LLVM_ABI bool hasPreferredPhys(Register VirtReg) const
returns true if VirtReg is assigned to its preferred physreg.
LLVM_ABI void dump() const
MachineRegisterInfo & getRegInfo() const
LLVM_ABI void assignVirt2Phys(Register virtReg, MCRegister physReg)
creates a mapping for the specified virtual register to the specified physical register
MCRegister getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr) const
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
static constexpr int NO_STACK_SLOT
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)>) const
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI char & VirtRegRewriterID
VirtRegRewriter pass.
LLVM_ABI FunctionPass * createVirtRegRewriter(bool ClearVirtRegs=true)
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
This struct is a compact representation of a valid (non-zero power of two) alignment.
A special type used by analysis passes to provide an address that identifies that particular analysis...
constexpr bool none() const
constexpr bool any() const