64 #include "llvm/Config/llvm-config.h" 85 #include <system_error> 92 #define DEBUG_TYPE "regalloc" 100 cl::desc(
"Attempt coalescing during PBQP register allocation."),
106 cl::desc(
"Dump graphs for each function/round in the compilation unit."),
121 RegAllocPBQP(
char *cPassID =
nullptr)
130 StringRef getPassName()
const override {
return "PBQP Register Allocator"; }
144 using LI2NodeMap = std::map<const LiveInterval *, unsigned>;
145 using Node2LIMap = std::vector<const LiveInterval *>;
146 using AllowedSet = std::vector<unsigned>;
147 using AllowedSetMap = std::vector<AllowedSet>;
148 using RegPair = std::pair<unsigned, unsigned>;
149 using CoalesceMap = std::map<RegPair, PBQP::PBQPNum>;
150 using RegSet = std::set<unsigned>;
154 RegSet VRegsToAlloc, EmptyIntervalVRegs;
203 if (SpillCost == 0.0)
204 SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
206 SpillCost += MinSpillCost;
218 using IKey = std::pair<AllowedRegVecPtr, AllowedRegVecPtr>;
221 using IEdgeKey = std::pair<PBQP::GraphBase::NodeId, PBQP::GraphBase::NodeId>;
226 const DisjointAllowedRegsCache &
D)
const {
234 return D.count(IKey(NRegs, MRegs)) > 0;
236 return D.count(IKey(MRegs, NRegs)) > 0;
241 DisjointAllowedRegsCache &D) {
245 assert(NRegs != MRegs &&
"AllowedRegs can not be disjoint with itself");
248 D.insert(IKey(NRegs, MRegs));
250 D.insert(IKey(MRegs, NRegs));
258 std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>;
260 static SlotIndex getStartPoint(
const IntervalInfo &
I) {
261 return std::get<0>(
I)->segments[std::get<1>(I)].start;
264 static SlotIndex getEndPoint(
const IntervalInfo &
I) {
265 return std::get<0>(
I)->segments[std::get<1>(I)].end;
269 return std::get<2>(
I);
272 static bool lowestStartPoint(
const IntervalInfo &I1,
273 const IntervalInfo &I2) {
276 return getStartPoint(I1) > getStartPoint(I2);
279 static bool lowestEndPoint(
const IntervalInfo &I1,
280 const IntervalInfo &I2) {
293 return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
296 static bool isAtLastSegment(
const IntervalInfo &
I) {
297 return std::get<1>(
I) == std::get<0>(I)->size() - 1;
300 static IntervalInfo nextSegment(
const IntervalInfo &I) {
301 return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
323 DisjointAllowedRegsCache
D;
325 using IntervalSet = std::set<IntervalInfo, decltype(&lowestEndPoint)>;
326 using IntervalQueue =
327 std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
328 decltype(&lowestStartPoint)>;
329 IntervalSet Active(lowestEndPoint);
330 IntervalQueue Inactive(lowestStartPoint);
336 assert(!LI.
empty() &&
"PBQP graph contains node for empty interval");
337 Inactive.push(std::make_tuple(&LI, 0, NId));
340 while (!Inactive.empty()) {
343 IntervalInfo Cur = Inactive.top();
346 IntervalSet::iterator RetireItr = Active.begin();
347 while (RetireItr != Active.end() &&
348 (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
351 if (!isAtLastSegment(*RetireItr))
352 Inactive.push(nextSegment(*RetireItr));
356 Active.erase(Active.begin(), RetireItr);
360 Cur = Inactive.top();
366 for (
const auto &A : Active) {
371 if (haveDisjointAllowedRegs(G, NId, MId, D))
375 IEdgeKey EK(std::min(NId, MId),
std::max(NId, MId));
380 if (!createInterferenceEdge(G, NId, MId, C))
381 setDisjointAllowedRegs(G, NId, MId, D);
401 *G.
getMetadata().MF.getSubtarget().getRegisterInfo();
406 IKey K(&NRegs, &MRegs);
407 IMatrixCache::iterator I = C.find(K);
414 bool NodesInterfere =
false;
415 for (
unsigned I = 0; I != NRegs.size(); ++
I) {
416 unsigned PRegN = NRegs[
I];
417 for (
unsigned J = 0; J != MRegs.size(); ++J) {
418 unsigned PRegM = MRegs[J];
420 M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
421 NodesInterfere =
true;
445 for (
const auto &MBB : MF) {
446 for (
const auto &
MI : MBB) {
448 if (!
CP.setRegisters(&
MI) ||
CP.getSrcReg() ==
CP.getDstReg())
451 unsigned DstReg =
CP.getDstReg();
452 unsigned SrcReg =
CP.getSrcReg();
458 if (!MF.getRegInfo().isAllocatable(DstReg))
463 const PBQPRAGraph::NodeMetadata::AllowedRegVector &
Allowed =
466 unsigned PRegOpt = 0;
467 while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
470 if (PRegOpt < Allowed.size()) {
472 NewCosts[PRegOpt + 1] -= CBenefit;
478 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
480 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
486 Allowed2->size() + 1, 0);
487 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
488 G.
addEdge(N1Id, N2Id, std::move(Costs));
495 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
504 void addVirtRegCoalesce(
506 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
507 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
509 assert(CostMat.getRows() == Allowed1.size() + 1 &&
"Size mismatch.");
510 assert(CostMat.getCols() == Allowed2.size() + 1 &&
"Size mismatch.");
511 for (
unsigned I = 0; I != Allowed1.size(); ++
I) {
512 unsigned PReg1 = Allowed1[
I];
513 for (
unsigned J = 0; J != Allowed2.size(); ++J) {
514 unsigned PReg2 = Allowed2[J];
516 CostMat[I + 1][J + 1] -= Benefit;
527 void PBQPRAConstraint::anchor() {}
529 void PBQPRAConstraintList::anchor() {}
531 void RegAllocPBQP::getAnalysisUsage(
AnalysisUsage &au)
const {
564 VRegsToAlloc.insert(Reg);
571 for (
unsigned i = 0; CSR[i] != 0; ++i)
584 *G.
getMetadata().MF.getSubtarget().getRegisterInfo();
586 std::vector<unsigned> Worklist(VRegsToAlloc.begin(), VRegsToAlloc.end());
588 std::map<unsigned, std::vector<unsigned>> VRegAllowedMap;
590 while (!Worklist.empty()) {
591 unsigned VReg = Worklist.back();
598 if (VRegLI.
empty()) {
599 EmptyIntervalVRegs.insert(VRegLI.
reg);
600 VRegsToAlloc.erase(VRegLI.
reg);
611 std::vector<unsigned> VRegAllowed;
613 for (
unsigned I = 0; I != RawPRegOrder.
size(); ++
I) {
614 unsigned PReg = RawPRegOrder[
I];
619 if (!RegMaskOverlaps.
empty() && !RegMaskOverlaps.
test(PReg))
623 bool Interference =
false;
634 VRegAllowed.push_back(PReg);
639 if (VRegAllowed.empty()) {
641 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
642 Worklist.insert(Worklist.end(), NewVRegs.
begin(), NewVRegs.
end());
645 VRegAllowedMap[VReg] = std::move(VRegAllowed);
648 for (
auto &KV : VRegAllowedMap) {
649 auto VReg = KV.first;
653 EmptyIntervalVRegs.insert(VReg);
654 VRegsToAlloc.erase(VReg);
658 auto &VRegAllowed = KV.second;
664 for (
unsigned i = 0; i != VRegAllowed.size(); ++i)
666 NodeCosts[1 + i] += 1.0;
671 G.
getMetadata().getAllowedRegs(std::move(VRegAllowed)));
676 void RegAllocPBQP::spillVReg(
unsigned VReg,
680 VRegsToAlloc.erase(VReg);
682 nullptr, &DeadRemats);
683 VRegSpiller.
spill(LRE);
688 << LRE.getParent().weight <<
", New vregs: ");
697 VRegsToAlloc.insert(LI.
reg);
703 bool RegAllocPBQP::mapPBQPToRegAlloc(
const PBQPRAGraph &G,
713 bool AnotherRoundNeeded =
false;
725 unsigned PReg = G.
getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
728 assert(PReg != 0 &&
"Invalid preg selected.");
734 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
735 AnotherRoundNeeded |= !NewVRegs.
empty();
739 return !AnotherRoundNeeded;
748 for (RegSet::const_iterator
749 I = EmptyIntervalVRegs.begin(),
E = EmptyIntervalVRegs.end();
758 for (
unsigned CandidateReg : RawPRegOrder) {
765 "No un-reserved physical registers in this register class");
775 for (
auto DeadInst : DeadRemats) {
777 DeadInst->eraseFromParent();
792 getAnalysis<MachineBlockFrequencyInfo>();
815 findVRegIntervalsToAlloc(MF, LIS);
819 std::string FullyQualifiedName =
824 if (!VRegsToAlloc.empty()) {
826 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
827 std::make_unique<PBQPRAConstraintList>();
828 ConstraintsRoot->addConstraint(std::make_unique<SpillCosts>());
829 ConstraintsRoot->addConstraint(std::make_unique<Interference>());
831 ConstraintsRoot->addConstraint(std::make_unique<Coalescing>());
834 bool PBQPAllocComplete =
false;
837 while (!PBQPAllocComplete) {
841 initializeGraph(G, VRM, *VRegSpiller);
842 ConstraintsRoot->apply(G);
846 std::ostringstream RS;
848 std::string GraphFileName = FullyQualifiedName +
"." + RS.str() +
852 LLVM_DEBUG(
dbgs() <<
"Dumping graph for round " << Round <<
" to \"" 853 << GraphFileName <<
"\"\n");
859 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
865 finalizeAlloc(MF, LIS, VRM);
866 postOptimization(*VRegSpiller, LIS);
867 VRegsToAlloc.clear();
868 EmptyIntervalVRegs.clear();
883 OS << NId <<
" (" << RegClassName <<
':' <<
printReg(VReg, TRI) <<
')';
887 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 889 for (
auto NId : nodeIds()) {
890 const Vector &Costs = getNodeCosts(NId);
891 assert(Costs.getLength() != 0 &&
"Empty vector in graph.");
896 for (
auto EId : edgeIds()) {
897 NodeId N1Id = getEdgeNode1Id(EId);
898 NodeId N2Id = getEdgeNode2Id(EId);
899 assert(N1Id != N2Id &&
"PBQP graphs should not have self-edges.");
900 const Matrix &M = getEdgeCosts(EId);
901 assert(M.getRows() != 0 &&
"No rows in matrix.");
902 assert(M.getCols() != 0 &&
"No cols in matrix.");
903 OS <<
PrintNodeInfo(N1Id, *
this) <<
' ' << M.getRows() <<
" rows / ";
904 OS <<
PrintNodeInfo(N2Id, *
this) <<
' ' << M.getCols() <<
" cols:\n";
916 for (
auto NId : nodeIds()) {
917 OS <<
" node" << NId <<
" [ label=\"" 919 << getNodeCosts(NId) <<
"\" ]\n";
922 OS <<
" edge [ len=" << nodeIds().size() <<
" ]\n";
923 for (
auto EId : edgeIds()) {
924 OS <<
" node" << getEdgeNode1Id(EId)
925 <<
" -- node" << getEdgeNode2Id(EId)
927 const Matrix &EdgeCosts = getEdgeCosts(EId);
928 for (
unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
929 OS << EdgeCosts.getRowAsVector(i) <<
"\\n";
937 return new RegAllocPBQP(customPassID);
Represents a solution to a PBQP problem.
static Printable PrintNodeInfo(PBQP::RegAlloc::PBQPRAGraph::NodeId NId, const PBQP::RegAlloc::PBQPRAGraph &G)
Create Printable object for node and register info.
Abstract base for classes implementing PBQP register allocation constraints (e.g. ...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
bool isReserved(Register PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
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...
bool empty() const
empty - Tests whether there are no bits in this bitvector.
EdgeId addEdge(NodeId N1Id, NodeId N2Id, OtherVectorT Costs)
Add an edge between the given nodes with the given costs.
Holds a vector of the allowed physical regs for a vreg.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
ArrayRef< MCPhysReg > getRawAllocationOrder(const MachineFunction &MF) const
Returns the preferred order for allocating registers from this register class in MF.
Implements a dense probed hash-table based set.
EdgeId findEdge(NodeId N1Id, NodeId N2Id)
Get the edge connecting two nodes.
LiveInterval - This class represents the liveness of a register, or stack slot.
virtual ~PBQPRAConstraint()=0
bool test(unsigned Idx) const
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
void updateEdgeCosts(EdgeId EId, OtherMatrixT Costs)
Update an edge's cost matrix.
unsigned const TargetRegisterInfo * TRI
NodeId addEdgeBypassingCostAllocator(NodeId N1Id, NodeId N2Id, OtherMatrixPtrT Costs)
Add an edge bypassing the cost allocator.
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.
NodeId getEdgeNode1Id(EdgeId EId) const
Get the first node connected to this edge.
bool checkRegMaskInterference(LiveInterval &LI, BitVector &UsableRegs)
Test if LI is live across any register mask instructions, and compute a bit mask of physical register...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
virtual void spill(LiveRangeEdit &LRE)=0
spill - Spill the LRE.getParent() live interval.
FunctionPass * createPBQPRegisterAllocator(char *customPassID=nullptr)
Create a PBQP register allocator instance.
virtual std::unique_ptr< PBQPRAConstraint > getCustomPBQPConstraints() const
Return PBQPConstraint(s) for the target.
const char * getRegClassName(const TargetRegisterClass *Class) const
Returns the name of the register class.
NodeMetadata & getNodeMetadata(NodeId NId)
AnalysisUsage & addRequired()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
typename RegAllocSolverImpl ::GraphMetadata GraphMetadata
A helper class for register coalescers.
void apply(Opt *O, const Mod &M, const Mods &... Ms)
void freezeReservedRegs(const MachineFunction &)
freezeReservedRegs - Called by the register allocator to freeze the set of reserved registers before ...
static cl::opt< bool > PBQPCoalescing("pbqp-coalescing", cl::desc("Attempt coalescing during PBQP register allocation."), cl::init(false), cl::Hidden)
bool regsOverlap(Register regA, Register regB) const
Returns true if the two registers are equal or alias each other.
NodeIdSet nodeIds() const
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
typename RegAllocSolverImpl ::Matrix Matrix
The file should be opened in text mode on platforms that make this distinction.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
const Matrix & getEdgeCosts(EdgeId EId) const
Get an edge's cost matrix.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
const MatrixPtr & getEdgeCostsPtr(EdgeId EId) const
Get a MatrixPtr to a node's cost matrix.
initializer< Ty > init(const Ty &Val)
void initializeSlotIndexesPass(PassRegistry &)
const TargetRegisterInfo * getTargetRegisterInfo() const
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
unsigned const MachineRegisterInfo * MRI
const Vector & getNodeCosts(NodeId NId) const
Get a node's cost vector.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void initializeLiveStacksPass(PassRegistry &)
size_t size() const
size - Get the array size.
MachineRegisterInfo & getRegInfo() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
Represent the analysis usage information of a pass.
void initializeLiveIntervalsPass(PassRegistry &)
void assignVirt2Phys(Register virtReg, MCPhysReg physReg)
creates a mapping for the specified virtual register to the specified physical register ...
FunctionPass * createDefaultPBQPRegisterAllocator()
PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean Quadratic Prograaming (PBQ...
bool reg_nodbg_empty(Register RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions...
FunctionPass class - This class is used to implement most global optimizations.
static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI, const MachineFunction &MF)
LiveInterval & getInterval(Register Reg)
static RegisterRegAlloc RegisterPBQPRepAlloc("pbqp", "PBQP register allocator", createDefaultPBQPRegisterAllocator)
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...
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
GraphMetadata & getMetadata()
Get a reference to the graph metadata.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Align max(MaybeAlign Lhs, Align Rhs)
void calculateSpillWeightsAndHints(LiveIntervals &LIS, MachineFunction &MF, VirtRegMap *VRM, const MachineLoopInfo &MLI, const MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo::NormalizingFn norm=normalizeSpillWeight)
Compute spill weights and allocation hints for all virtual register live intervals.
AnalysisUsage & addRequiredID(const void *ID)
Module.h This file contains the declarations for the Module class.
void printDot(raw_ostream &OS) const
Print a representation of this graph in DOT format.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
void setPreservesCFG()
This function should be called by the pass, iff they do not:
const Function & getFunction() const
Return the LLVM function that this machine code represents.
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.
void dump() const
Dump this graph to dbgs().
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
const char * getName(MCRegister RegNo) const
Return the human-readable symbolic target-specific name for the specified physical register...
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
typename RegAllocSolverImpl ::RawVector RawVector
TargetSubtargetInfo - Generic base class for all target subtargets.
void initializeVirtRegMapPass(PassRegistry &)
Spiller * createInlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
static EdgeId invalidEdgeId()
Returns a value representing an invalid (non-existent) edge.
A raw_ostream that writes to a file descriptor.
bool overlaps(const LiveRange &other) const
overlaps - Return true if the intersection of the two live ranges is not empty.
SmallVectorImpl< unsigned >::const_iterator iterator
Iterator for accessing the new registers added by this edit.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
unsigned getSelection(GraphBase::NodeId nodeId) const
Get a node's selection.
uint64_t getEntryFreq() const
Solution solve(PBQPRAGraph &G)
virtual void postOptimization()
unsigned getSpillOptionIdx()
Spill option index.
typename RegAllocSolverImpl ::Vector Vector
static cl::opt< bool > PBQPDumpGraphs("pbqp-dump-graphs", cl::desc("Dump graphs for each function/round in the compilation unit."), cl::init(false), cl::Hidden)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static float normalizeSpillWeight(float UseDefFreq, unsigned Size, unsigned NumInstr)
Normalize the spill weight of a live interval.
void clearAllVirt()
clears all virtual to physical register mappings
Module * getParent()
Get the module that this global value is contained inside of...
typename RegAllocSolverImpl ::RawMatrix RawMatrix
simple register Simple Register Coalescing
const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
This class implements an extremely fast bulk output stream that can only output to a stream...
StringRef - Represent a constant reference to a string, i.e.
NodeId addNode(OtherVectorT Costs)
Add a node with the given costs.
Simple wrapper around std::function<void(raw_ostream&)>.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
Register getSimpleHint(Register VReg) const
getSimpleHint - same as getRegAllocationHint except it will only return a target independent hint...
SlotIndex - An opaque wrapper around machine indexes.
void setNodeCosts(NodeId NId, OtherVectorT Costs)
Set a node's cost vector.
static float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size, unsigned NumInstr)
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
LiveRange & getRegUnit(unsigned Unit)
Return the live range for register unit Unit.
Properties which a MachineFunction may have at a given point in time.