37 #include "llvm/Config/llvm-config.h" 49 #define DEBUG_TYPE "regalloc" 51 STATISTIC(NumSpillSlots,
"Number of spill slots allocated");
52 STATISTIC(NumIdCopies,
"Number of identity moves eliminated after rewriting");
63 MRI = &mf.getRegInfo();
64 TII = mf.getSubtarget().getInstrInfo();
65 TRI = mf.getSubtarget().getRegisterInfo();
69 Virt2StackSlotMap.clear();
70 Virt2SplitMap.clear();
78 Virt2PhysMap.resize(NumRegs);
79 Virt2StackSlotMap.resize(NumRegs);
80 Virt2SplitMap.resize(NumRegs);
86 "attempt to assign physical register to already mapped " 89 "Attempt to map virtReg to a reserved physReg");
90 Virt2PhysMap[virtReg.
id()] = physReg;
107 return getPhys(VirtReg) == Hint;
122 "attempt to assign stack slot to already spilled register");
124 return Virt2StackSlotMap[virtReg.
id()] = createSpillSlot(RC);
130 "attempt to assign stack slot to already spilled register");
133 "illegal fixed frame index");
134 Virt2StackSlotMap[virtReg.
id()] =
SS;
138 OS <<
"********** REGISTER MAP **********\n";
142 OS <<
'[' <<
printReg(Reg, TRI) <<
" -> " 143 <<
printReg(Virt2PhysMap[Reg], TRI) <<
"] " 151 OS <<
'[' <<
printReg(Reg, TRI) <<
" -> fi#" << Virt2StackSlotMap[
Reg]
158 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 185 void addMBBLiveIns();
214 "Virtual Register Rewriter",
false,
false)
224 AU.setPreservesCFG();
237 TRI = MF->getSubtarget().getRegisterInfo();
238 TII = MF->getSubtarget().getInstrInfo();
239 MRI = &MF->getRegInfo();
240 Indexes = &getAnalysis<SlotIndexes>();
241 LIS = &getAnalysis<LiveIntervals>();
242 VRM = &getAnalysis<VirtRegMap>();
243 LLVM_DEBUG(
dbgs() <<
"********** REWRITE VIRTUAL REGISTERS **********\n" 244 <<
"********** Function: " << MF->getName() <<
'\n');
248 LIS->addKillFlags(VRM);
257 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
262 MRI->clearVirtRegs();
266 void VirtRegRewriter::addLiveInsForSubRanges(
const LiveInterval &LI,
271 using SubRangeIteratorPair =
272 std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
278 SubRanges.
push_back(std::make_pair(&SR, SR.begin()));
279 if (!First.
isValid() || SR.segments.front().start < First)
280 First = SR.segments.front().start;
281 if (!Last.
isValid() || SR.segments.back().end > Last)
282 Last = SR.segments.back().end;
288 MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
293 for (
auto &RangeIterPair : SubRanges) {
296 while (SRI != SR->
end() && SRI->end <= MBBBegin)
298 if (SRI == SR->
end())
300 if (SRI->start <= MBBBegin)
312 void VirtRegRewriter::addMBBLiveIns() {
313 for (
unsigned Idx = 0, IdxE =
MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
315 if (
MRI->reg_nodbg_empty(VirtReg))
318 if (LI.
empty() || LIS->intervalIsInOneMBB(LI))
322 Register PhysReg = VRM->getPhys(VirtReg);
326 addLiveInsForSubRanges(LI, PhysReg);
332 for (
const auto &Seg : LI) {
333 I = Indexes->advanceMBBIndex(I, Seg.start);
334 for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++
I) {
345 MBB.sortUniqueLiveIns();
350 bool VirtRegRewriter::readsUndefSubreg(
const MachineOperand &MO)
const {
358 SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
362 "Reads of completely dead register should be marked undef already");
368 if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
374 void VirtRegRewriter::handleIdentityCopy(
MachineInstr &
MI)
const {
393 Indexes->removeSingleMachineInstrFromMaps(MI);
402 void VirtRegRewriter::expandCopyBundle(
MachineInstr &MI)
const {
413 I !=
E &&
I->isBundledWithSucc(); ++
I) {
426 Src->getOperand(1).getReg()))
434 for (
int E = MIs.size(), PrevE =
E;
E > 1; PrevE =
E) {
435 for (
int I =
E;
I--; )
442 MF->getFunction().getContext().emitError(
443 "register rewriting failed: cycle in copy bundle");
453 if (BundledMI != BundleStart) {
455 MBB.
insert(FirstMI, BundledMI);
456 }
else if (BundledMI->isBundledWithSucc()) {
457 BundledMI->unbundleFromSucc();
458 BundleStart = &*std::next(BundledMI->getIterator());
461 if (Indexes && BundledMI != FirstMI)
462 Indexes->insertMachineInstrInMaps(*BundledMI);
470 bool VirtRegRewriter::subRegLiveThrough(
const MachineInstr &MI,
472 SlotIndex MIIndex = LIS->getInstructionIndex(MI);
476 const LiveRange &UnitRange = LIS->getRegUnit(*Unit);
487 if (UnitRange.
liveAt(AfterMIDefs) && UnitRange.
liveAt(BeforeMIUses))
494 bool NoSubRegLiveness = !
MRI->subRegLivenessEnabled();
500 MBBI != MBBE; ++MBBI) {
503 MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
518 Register PhysReg = VRM->getPhys(VirtReg);
520 "Instruction uses unmapped VirtReg");
521 assert(!
MRI->isReserved(PhysReg) &&
"Reserved register assignment");
526 if (NoSubRegLiveness || !
MRI->shouldTrackSubRegLiveness(VirtReg)) {
531 (MO.
isDef() && subRegLiveThrough(*MI, PhysReg)))
543 if (readsUndefSubreg(MO))
548 }
else if (!MO.
isDead()) {
563 PhysReg =
TRI->getSubReg(PhysReg, SubReg);
564 assert(PhysReg.
isValid() &&
"Invalid SubReg for physical register");
575 while (!SuperKills.
empty())
578 while (!SuperDeads.
empty())
581 while (!SuperDefs.
empty())
586 expandCopyBundle(*MI);
589 handleIdentityCopy(*MI);
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
mop_iterator operands_end()
A common definition of LaneBitmask for use in TableGen and CodeGen.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
This class represents lattice values for constants.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
A Module instance is used to store all the information related to an LLVM module. ...
bool isBundledWithPred() const
Return true if this instruction is part of a bundle, and it is not the first instruction in the bundl...
void push_back(const T &Elt)
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
LiveInterval - This class represents the liveness of a register, or stack slot.
void setIsUndef(bool Val=true)
bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI defined a register without a use.
unsigned getSubReg() const
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
A live range for subregisters.
bool isValid() const
Returns true if this is a valid index.
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
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.
static unsigned index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
void setIsRenamable(bool Val=true)
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 ...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
This class represents the liveness of a register, stack slot, etc.
int assignVirt2StackSlot(Register virtReg)
create a mapping for the specifed virtual register to the next available stack slot ...
const char * getRegClassName(const TargetRegisterClass *Class) const
Returns the name of the register class.
unsigned getSpillAlignment(const TargetRegisterClass &RC) const
Return the minimum required alignment in bytes for a spill slot for a register of this class...
#define INITIALIZE_PASS_DEPENDENCY(depName)
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
unsigned getNumOperands() const
Retuns the total number of operands.
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
iterator_range< subrange_iterator > subranges()
bool hasSubRanges() const
Returns true if subregister liveness information is available.
SmallVectorImpl< IdxMBBPair >::const_iterator MBBIndexIterator
Iterator over the idx2MBBMap (sorted pairs of slot index of basic block begin and basic block) ...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register. ...
bool isIdentityCopy() const
Return true is the instruction is an identity copy.
bool addRegisterKilled(Register IncomingReg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI kills a register.
int getObjectIndexBegin() const
Return the minimum frame object index.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
void setReg(Register Reg)
Change the register this operand corresponds to.
int CreateSpillStackObject(uint64_t Size, Align Alignment)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
bool hasPreferredPhys(Register VirtReg)
returns true if VirtReg is assigned to its preferred physreg.
TargetInstrInfo - Interface to description of machine instruction set.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
unsigned const MachineRegisterInfo * MRI
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool liveAt(SlotIndex index) const
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
Represent the analysis usage information of a pass.
void assignVirt2Phys(Register virtReg, MCPhysReg physReg)
creates a mapping for the specified virtual register to the specified physical register ...
constexpr bool none() const
void setIsInternalRead(bool Val=true)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
This struct is a compact representation of a valid (non-zero power of two) alignment.
void eraseFromBundle()
Unlink 'this' form its basic block and delete it.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
MachineInstr * removeFromBundle()
Unlink this instruction from its basic block and return it without deleting it.
Iterator for intrusive lists based on ilist_node.
void setDesc(const MCInstrDesc &tid)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one...
std::pair< unsigned, unsigned > getRegAllocationHint(Register VReg) const
getRegAllocationHint - Return the register allocation hint for the specified virtual register...
Segments::const_iterator const_iterator
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
LLVM_NODISCARD T pop_back_val()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
iterator insert(iterator I, T &&Elt)
const MachineBasicBlock * getParent() const
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
Virtual Register Rewriter
Representation of each machine instruction.
reverse_self_iterator getReverseIterator()
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Register getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
LLVM_NODISCARD bool empty() const
void push_back(MachineInstr *MI)
void setSubReg(unsigned subReg)
virtual MachineFunctionProperties getSetProperties() const
static bool rewrite(Function &F)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
mop_iterator operands_begin()
void addRegisterDefined(Register Reg, const TargetRegisterInfo *RegInfo=nullptr)
We have determined MI defines a register.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
char & VirtRegRewriterID
VirtRegRewriter pass.
MachineFunctionPass(char &ID)
This class implements an extremely fast bulk output stream that can only output to a stream...
Register getReg() const
getReg - Returns the register number.
const MachineOperand & getOperand(unsigned i) const
Register getSimpleHint(Register VReg) const
getSimpleHint - same as getRegAllocationHint except it will only return a target independent hint...
bool hasKnownPreference(Register VirtReg)
returns true if VirtReg has a known preferred register.
SlotIndex - An opaque wrapper around machine indexes.
SlotIndex getBoundaryIndex() const
Returns the boundary index for associated with this index.
Properties which a MachineFunction may have at a given point in time.
Wrapper class representing virtual and physical registers.
INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter", "Virtual Register Rewriter", false, false) INITIALIZE_PASS_END(VirtRegRewriter