46 #define DEBUG_TYPE "reg-scavenging"
48 STATISTIC(NumScavengedRegs,
"Number of frame index regs scavenged");
67 KillRegUnits.
resize(NumRegUnits);
68 DefRegUnits.
resize(NumRegUnits);
69 TmpRegUnits.
resize(NumRegUnits);
73 for (ScavengedInfo &SI : Scavenged) {
92 MBBI = std::prev(MBB.
end());
97 void RegScavenger::addRegUnits(
BitVector &BV,
unsigned Reg) {
102 void RegScavenger::removeRegUnits(
BitVector &BV,
unsigned Reg) {
107 void RegScavenger::determineKillsAndDefs() {
108 assert(Tracking &&
"Must be tracking to determine kills and defs");
115 KillRegUnits.
reset();
118 if (MO.isRegMask()) {
120 for (
unsigned RU = 0, RUEnd = TRI->
getNumRegUnits(); RU != RUEnd; ++RU) {
122 if (MO.clobbersPhysReg(*RURI)) {
130 KillRegUnits |= TmpRegUnits;
134 unsigned Reg = MO.getReg();
143 addRegUnits(KillRegUnits, Reg);
147 addRegUnits(KillRegUnits, Reg);
149 addRegUnits(DefRegUnits, Reg);
155 assert(Tracking &&
"Cannot unprocess because we're not tracking");
159 determineKillsAndDefs();
162 setUsed(KillRegUnits);
163 setUnused(DefRegUnits);
166 if (MBBI == MBB->
begin()) {
179 assert(MBBI != MBB->
end() &&
"Already past the end of the basic block!");
180 MBBI = std::next(MBBI);
182 assert(MBBI != MBB->
end() &&
"Already at the end of the basic block!");
188 if (
I->Restore != &MI)
192 I->Restore =
nullptr;
195 if (MI.isDebugValue())
198 determineKillsAndDefs();
205 unsigned Reg = MO.getReg();
220 bool SubUsed =
false;
226 bool SuperUsed =
false;
233 if (!SubUsed && !SuperUsed) {
245 assert((KillRegs.test(Reg) || isUnused(Reg) ||
246 isLiveInButUnusedBefore(Reg, MI, MBB, TRI,
MRI)) &&
247 "Re-defining a live register!");
254 setUnused(KillRegUnits);
255 setUsed(DefRegUnits);
259 assert(Tracking &&
"Must be tracking to determine kills and defs");
265 for (ScavengedInfo &
I : Scavenged) {
266 if (
I.Restore == &MI) {
272 if (MBBI == MBB->
begin()) {
281 return includeReserved;
286 for (
unsigned Reg : *RC) {
298 for (
unsigned Reg : *RC)
309 assert(Survivor > 0 &&
"No candidates for scavenging");
312 assert(StartMI != ME &&
"MI already at terminator");
316 bool inVirtLiveRange =
false;
317 for (++MI; InstrLimit > 0 && MI != ME; ++
MI, --
InstrLimit) {
318 if (MI->isDebugValue()) {
322 bool isVirtKillInsn =
false;
323 bool isVirtDefInsn =
false;
328 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
332 isVirtDefInsn =
true;
333 else if (MO.isKill())
334 isVirtKillInsn =
true;
338 Candidates.
reset(*AI);
342 if (!inVirtLiveRange) RestorePointMI =
MI;
345 if (isVirtKillInsn) inVirtLiveRange =
false;
346 if (isVirtDefInsn) inVirtLiveRange =
true;
349 if (Candidates.
test(Survivor))
353 if (Candidates.
none())
359 if (MI == ME) RestorePointMI = ME;
360 assert(RestorePointMI != StartMI &&
361 "No available scavenger restore location!");
364 UseMI = RestorePointMI;
375 static std::pair<MCPhysReg, MachineBasicBlock::iterator>
380 bool FoundTo =
false;
384 unsigned InstrLimit = 25;
399 return std::make_pair(Reg, MBB.
end());
412 if (Survivor == 0 || !Used.
available(Survivor)) {
420 if (AvilableReg == 0)
422 Survivor = AvilableReg;
424 if (--InstrCountDown == 0)
429 bool FoundVReg =
false;
445 return std::make_pair(Survivor, Pos);
457 RegScavenger::ScavengedInfo &
470 for (
unsigned I = 0;
I < Scavenged.
size(); ++
I) {
471 if (Scavenged[
I].Reg != 0)
474 int FI = Scavenged[
I].FrameIndex;
475 if (FI < FIB || FI >= FIE)
479 if (NeedSize > S || NeedAlign > A)
487 unsigned D = (S-NeedSize) + (A-NeedAlign);
494 if (SI == Scavenged.
size()) {
501 Scavenged[SI].Reg =
Reg;
507 int FI = Scavenged[SI].FrameIndex;
508 if (FI < FIB || FI >= FIE) {
509 std::string Msg = std::string(
"Error while trying to spill ") +
511 ": Cannot scavenge register without an emergency spill slot!";
524 II = std::prev(UseMI);
529 return Scavenged[SI];
542 if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
545 Candidates.
reset(*AI);
551 Available &= Candidates;
553 Candidates = Available;
557 unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
565 ScavengedInfo &Scavenged = spill(SReg, *RC, SPAdj, I, UseMI);
566 Scavenged.Restore = &*std::prev(UseMI);
568 DEBUG(
dbgs() <<
"Scavenged register (with spill): " << TRI->
getName(SReg) <<
576 bool RestoreAfter,
int SPAdj) {
583 std::pair<MCPhysReg, MachineBasicBlock::iterator>
P =
588 assert(Reg != 0 &&
"No register left to scavenge!");
590 if (SpillBefore != MBB.
end()) {
592 RestoreAfter ? std::next(MBBI) : MBBI;
594 DEBUG(
dbgs() <<
"Reload before: " << *ReloadBefore <<
'\n');
595 ScavengedInfo &Scavenged = spill(Reg, RC, SPAdj, SpillBefore, ReloadBefore);
596 Scavenged.Restore = &*std::prev(SpillBefore);
599 <<
" until " << *SpillBefore);
612 unsigned VReg,
bool ReserveAfter) {
621 if (CommonMBB ==
nullptr)
623 assert(MBB == CommonMBB &&
"All defs+uses must be in the same basic block");
627 assert((!RealDef || RealDef == &MI) &&
628 "Can have at most one definition which is not a redefinition");
633 assert(RealDef !=
nullptr &&
"Must have at least 1 Def");
645 return !MO.getParent()->readsRegister(VReg, &TRI);
648 "Must have one definition that does not redefine vreg");
656 ReserveAfter, SPAdj);
672 bool NextInstructionReadsVReg =
false;
679 if (NextInstructionReadsVReg) {
685 unsigned Reg = MO.getReg();
696 N->addRegisterKilled(SReg, &TRI,
false);
702 NextInstructionReadsVReg =
false;
707 unsigned Reg = MO.getReg();
715 assert(!MO.isInternalRead() &&
"Cannot assign inside bundles");
716 assert((!MO.isUndef() || MO.isDef()) &&
"Cannot handle undef uses");
718 NextInstructionReadsVReg =
true;
722 I->addRegisterDead(SReg, &TRI,
false);
730 assert(!MO.isInternalRead() &&
"Cannot assign inside bundles");
731 assert((!MO.isUndef() || MO.isDef()) &&
"Cannot handle undef uses");
732 assert(!MO.readsReg() &&
"Vreg use in first instruction not allowed");
757 DEBUG(
dbgs() <<
"Warning: Required two scavenging passes for block "
800 "Scavenge virtual registers inside basic blocks",
false,
false)
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
void push_back(const T &Elt)
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
bool isValid() const
Check if the iterator is at the end of the list.
int find_first() const
find_first - Returns the index of the first set bit, -1 if none of the bits are set.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use...
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
STATISTIC(NumFunctions,"Total number of functions")
static unsigned virtReg2Index(unsigned Reg)
Convert a virtual register number to a 0-based index.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
virtual bool saveScavengerRegister(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, MachineBasicBlock::iterator &UseMI, const TargetRegisterClass *RC, unsigned Reg) const
Spill the register so it can be used by the register scavenger.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
bool none() const
none - Returns true if none of the bits are set.
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const override
Store the specified register of the given register class to the specified stack frame index...
unsigned getSpillAlignment(const TargetRegisterClass &RC) const
Return the minimum required alignment for a spill slot for a register of this class.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
bool any() const
any - Returns true if any bit is set.
bool available(unsigned Reg) const
Returns true if no part of physical register Reg is live.
iterator_range< mop_iterator > operands()
void clearVirtRegs()
clearVirtRegs - Remove all virtual registers (after physreg assignment).
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
unsigned scavengeRegisterBackwards(const TargetRegisterClass &RC, MachineBasicBlock::iterator To, bool RestoreAfter, int SPAdj)
Make a register of the specific register class available from the current position backwards to the p...
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned DestReg, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const override
Load the specified register of the given register class from the specified stack frame index...
void clear()
clear - Removes all bits from the bitvector. Does not change capacity.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MCSuperRegIterator enumerates all super-registers of Reg.
virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
const TargetRegisterInfo * getTargetRegisterInfo() const
void addLiveOuts(const MachineBasicBlock &MBB)
Adds registers living out of block MBB.
void removeReg(unsigned Reg)
Removes all register units covered by physical register Reg.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
ArrayRef< MCPhysReg > getRawAllocationOrder(const MachineFunction &MF) const
Returns the preferred order for allocating registers from this register class in MF.
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
const MachineFunctionProperties & getProperties() const
Get the function properties.
Reg
All possible values of the reg field in the ModR/M byte.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
void backward()
Update internal register state and move MBB iterator backwards.
unsigned getNumOperands() const
Access to explicit operands of the instruction.
void scavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger &RS)
Replaces all frame index virtual registers with physical registers.
void forward()
Move the internal MBB iterator and update register states.
unsigned getNumRegs() const
Return the number of registers this target has (useful for sizing arrays holding per register informa...
void addLiveIns(const MachineBasicBlock &MBB)
Adds registers living into block MBB.
int getObjectIndexBegin() const
Return the minimum frame object index.
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
MCRegUnitRootIterator enumerates the root registers of a register unit.
BitVector getRegsAvailable(const TargetRegisterClass *RC)
Return all available registers in the register class in Mask.
const char * getRegClassName(const TargetRegisterClass *Class) const
Returns the name of the register class.
virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI, int SPAdj, unsigned FIOperandNum, RegScavenger *RS=nullptr) const =0
This method must be overriden to eliminate abstract frame indices from instructions which may use the...
BitVector getAllocatableSet(const MachineFunction &MF, const TargetRegisterClass *RC=nullptr) const
Returns a bitset indexed by register number indicating if a register is allocatable or not...
Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubRegIdx=0)
Prints virtual and physical registers with or without a TRI instance.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
const MachineBasicBlock * getParent() const
bool isDebugValue() const
initializer< Ty > init(const Ty &Val)
MachineInstrBundleIterator< MachineInstr > iterator
void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
This file declares the machine register scavenger class.
void init(const TargetRegisterInfo &TRI)
Initialize and clear the set.
unsigned const MachineRegisterInfo * MRI
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineInstrBuilder & UseMI
bool isReserved(unsigned PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
const MachineOperand & getOperand(unsigned i) const
void unprocess()
Invert the behavior of forward() on the current instruction (undo the changes to the available regist...
MCRegAliasIterator enumerates all registers aliasing Reg.
void stepBackward(const MachineInstr &MI)
Updates liveness when stepping backwards over the instruction MI.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MCSubRegIterator enumerates all sub-registers of Reg.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static bool scavengeFrameVirtualRegsInBlock(MachineRegisterInfo &MRI, RegScavenger &RS, MachineBasicBlock &MBB)
Allocate (scavenge) vregs inside a single basic block.
bool readsRegister(unsigned Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr reads the specified register.
virtual const TargetFrameLowering * getFrameLowering() const
MachineOperand class - Representation of each machine instruction operand.
unsigned getObjectAlignment(int ObjectIdx) const
Return the alignment of the specified stack object.
bool test(unsigned Idx) const
static unsigned scavengeVReg(MachineRegisterInfo &MRI, RegScavenger &RS, unsigned VReg, bool ReserveAfter)
Allocate a register for the virtual register VReg.
bool isRegUsed(unsigned Reg, bool includeReserved=true) const
Return if a specific register is currently used.
Information about stack frame layout on the target.
void enterBasicBlockEnd(MachineBasicBlock &MBB)
Start tracking liveness from the end of basic block MBB.
void accumulate(const MachineInstr &MI)
Adds all register units used, defined or clobbered in MI.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
void addRegMasked(unsigned Reg, LaneBitmask Mask)
Adds register units covered by physical register Reg that are part of the lanemask Mask...
unsigned getNumRegUnits() const
Return the number of (native) register units in the target.
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
def_iterator def_begin(unsigned RegNo) const
llvm_unreachable("Unknown RegBank!")
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
TargetSubtargetInfo - Generic base class for all target subtargets.
static unsigned getFrameIndexOperandNum(MachineInstr &MI)
Representation of each machine instruction.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
unsigned FindUnusedReg(const TargetRegisterClass *RegClass) const
Find an unused register of the specified register class.
void enterBasicBlock(MachineBasicBlock &MBB)
Start tracking liveness from the begin of basic block MBB.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
A set of register units used to track register liveness.
static cl::opt< unsigned > InstrLimit("dfa-instr-limit", cl::Hidden, cl::init(0), cl::desc("If present, stops packetizing after N instructions"))
iterator_range< reg_nodbg_iterator > reg_nodbg_operands(unsigned Reg) const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static def_iterator def_end()
void setRegUsed(unsigned Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Tell the scavenger a register is used.
virtual const TargetInstrInfo * getInstrInfo() const
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
const char * getName(unsigned RegNo) const
Return the human-readable symbolic target-specific name for the specified physical register...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
static std::pair< MCPhysReg, MachineBasicBlock::iterator > findSurvivorBackwards(const MachineRegisterInfo &MRI, MachineBasicBlock::iterator From, MachineBasicBlock::iterator To, const LiveRegUnits &LiveOut, ArrayRef< MCPhysReg > AllocationOrder, bool RestoreAfter)
Given the bitvector Available of free register units at position From.
unsigned getSpillSize(const TargetRegisterClass &RC) const
Return the size in bytes of the stack slot allocated to hold a spilled copy of a register from class ...
auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
reg_begin/reg_end - Provide iteration support to walk over all definitions and uses of a register wit...
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
unsigned scavengeRegister(const TargetRegisterClass *RegClass, MachineBasicBlock::iterator I, int SPAdj)
Make a register of the specific register class available and do the appropriate bookkeeping.