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)
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))
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 {
570 VRegsToAlloc.insert(LI.
reg);
572 EmptyIntervalVRegs.insert(LI.
reg);
580 for (
unsigned i = 0; CSR[i] != 0; ++i)
593 *G.
getMetadata().MF.getSubtarget().getRegisterInfo();
595 std::vector<unsigned> Worklist(VRegsToAlloc.begin(), VRegsToAlloc.end());
597 while (!Worklist.empty()) {
598 unsigned VReg = Worklist.back();
609 std::vector<unsigned> VRegAllowed;
611 for (
unsigned I = 0; I != RawPRegOrder.
size(); ++
I) {
612 unsigned PReg = RawPRegOrder[
I];
617 if (!RegMaskOverlaps.
empty() && !RegMaskOverlaps.
test(PReg))
621 bool Interference =
false;
632 VRegAllowed.push_back(PReg);
637 if (VRegAllowed.empty()) {
639 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
640 Worklist.insert(Worklist.end(), NewVRegs.
begin(), NewVRegs.
end());
648 for (
unsigned i = 0; i != VRegAllowed.size(); ++i)
650 NodeCosts[1 + i] += 1.0;
655 G.
getMetadata().getAllowedRegs(std::move(VRegAllowed)));
660 void RegAllocPBQP::spillVReg(
unsigned VReg,
664 VRegsToAlloc.erase(VReg);
666 nullptr, &DeadRemats);
667 VRegSpiller.
spill(LRE);
672 << LRE.getParent().weight <<
", New vregs: ");
681 VRegsToAlloc.insert(LI.
reg);
687 bool RegAllocPBQP::mapPBQPToRegAlloc(
const PBQPRAGraph &G,
697 bool AnotherRoundNeeded =
false;
709 unsigned PReg = G.
getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
712 assert(PReg != 0 &&
"Invalid preg selected.");
718 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
719 AnotherRoundNeeded |= !NewVRegs.
empty();
723 return !AnotherRoundNeeded;
732 for (RegSet::const_iterator
733 I = EmptyIntervalVRegs.begin(),
E = EmptyIntervalVRegs.end();
742 for (
unsigned CandidateReg : RawPRegOrder) {
749 "No un-reserved physical registers in this register class");
759 for (
auto DeadInst : DeadRemats) {
761 DeadInst->eraseFromParent();
776 getAnalysis<MachineBlockFrequencyInfo>();
799 findVRegIntervalsToAlloc(MF, LIS);
803 std::string FullyQualifiedName =
808 if (!VRegsToAlloc.empty()) {
810 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
811 llvm::make_unique<PBQPRAConstraintList>();
812 ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
813 ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
815 ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
818 bool PBQPAllocComplete =
false;
821 while (!PBQPAllocComplete) {
822 DEBUG(
dbgs() <<
" PBQP Regalloc round " << Round <<
":\n");
825 initializeGraph(G, VRM, *VRegSpiller);
826 ConstraintsRoot->apply(G);
830 std::ostringstream RS;
832 std::string GraphFileName = FullyQualifiedName +
"." + RS.str() +
836 DEBUG(
dbgs() <<
"Dumping graph for round " << Round <<
" to \""
837 << GraphFileName <<
"\"\n");
843 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
849 finalizeAlloc(MF, LIS, VRM);
850 postOptimization(*VRegSpiller, LIS);
851 VRegsToAlloc.clear();
852 EmptyIntervalVRegs.clear();
854 DEBUG(
dbgs() <<
"Post alloc VirtRegMap:\n" << VRM <<
"\n");
867 OS << NId <<
" (" << RegClassName <<
':' <<
PrintReg(VReg, TRI) <<
')';
871 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
875 assert(Costs.getLength() != 0 &&
"Empty vector in graph.");
883 assert(N1Id != N2Id &&
"PBQP graphs should not have self-edges.");
885 assert(M.getRows() != 0 &&
"No rows in matrix.");
886 assert(M.getCols() != 0 &&
"No cols in matrix.");
887 OS <<
PrintNodeInfo(N1Id, *
this) <<
' ' << M.getRows() <<
" rows / ";
888 OS <<
PrintNodeInfo(N2Id, *
this) <<
' ' << M.getCols() <<
" cols:\n";
900 for (
auto NId : nodeIds()) {
901 OS <<
" node" << NId <<
" [ label=\""
903 << getNodeCosts(NId) <<
"\" ]\n";
906 OS <<
" edge [ len=" << nodeIds().size() <<
" ]\n";
907 for (
auto EId : edgeIds()) {
908 OS <<
" node" << getEdgeNode1Id(EId)
909 <<
" -- node" << getEdgeNode2Id(EId)
911 const Matrix &EdgeCosts = getEdgeCosts(EId);
912 for (
unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
913 OS << EdgeCosts.getRowAsVector(i) <<
"\\n";
921 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...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
NodeId getEdgeNode1Id(EdgeId EId) const
Get the first node connected to this edge.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
static unsigned index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
EdgeId addEdge(NodeId N1Id, NodeId N2Id, OtherVectorT Costs)
Add an edge between the given nodes with the given costs.
unsigned getSimpleHint(unsigned VReg) const
getSimpleHint - Return the preferred register allocation hint, or 0 if a standard simple hint (Type =...
Holds a vector of the allowed physical regs for a vreg.
static RegisterRegAlloc RegisterPBQPRepAlloc("pbqp","PBQP register allocator", createDefaultPBQPRegisterAllocator)
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
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
NodeId getEdgeNode2Id(EdgeId EId) const
Get the second node connected to this edge.
unsigned getSelection(GraphBase::NodeId nodeId) const
Get a node's selection.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
void updateEdgeCosts(EdgeId EId, OtherMatrixT Costs)
Update an edge's cost matrix.
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
NodeId addEdgeBypassingCostAllocator(NodeId N1Id, NodeId N2Id, OtherMatrixPtrT Costs)
Add an edge bypassing the cost allocator.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
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 Vector & getNodeCosts(NodeId NId) const
Get a node's cost vector.
BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
virtual void spill(LiveRangeEdit &LRE)=0
spill - Spill the LRE.getParent() live interval.
StringRef getName() const
Return a constant reference to the value's name.
FunctionPass * createPBQPRegisterAllocator(char *customPassID=nullptr)
Create a PBQP register allocator instance.
void dump() const
Dump this graph to dbgs().
NodeMetadata & getNodeMetadata(NodeId NId)
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
AnalysisUsage & addRequired()
uint64_t getEntryFreq() const
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetRegisterInfo * getTargetRegisterInfo() const
typename RegAllocSolverImpl::GraphMetadata GraphMetadata
virtual std::unique_ptr< PBQPRAConstraint > getCustomPBQPConstraints() const
Return PBQPConstraint(s) for the target.
A helper class for register coalescers.
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.
void freezeReservedRegs(const MachineFunction &)
freezeReservedRegs - Called by the register allocator to freeze the set of reserved registers before ...
Reg
All possible values of the reg field in the ModR/M byte.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
void printDot(raw_ostream &OS) const
Print a representation of this graph in DOT format.
static cl::opt< bool > PBQPCoalescing("pbqp-coalescing", cl::desc("Attempt coalescing during PBQP register allocation."), cl::init(false), cl::Hidden)
LLVM_NODISCARD bool empty() const
const char * getRegClassName(const TargetRegisterClass *Class) const
Returns the name of the register class.
RegisterRegAlloc class - Track the registration of register allocators.
typename RegAllocSolverImpl::Matrix Matrix
Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubRegIdx=0)
Prints virtual and physical registers with or without a TRI instance.
EdgeIdSet edgeIds() const
size_t size() const
size - Get the array size.
NodeIdSet nodeIds() const
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
initializer< Ty > init(const Ty &Val)
void initializeSlotIndexesPass(PassRegistry &)
bool regsOverlap(unsigned regA, unsigned regB) const
Returns true if the two registers are equal or alias each other.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
unsigned const MachineRegisterInfo * MRI
void initializeLiveStacksPass(PassRegistry &)
bool isReserved(unsigned PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
bool empty() const
empty - Tests whether there are no bits in this bitvector.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool overlaps(const LiveRange &other) const
overlaps - Return true if the intersection of the two live ranges is not empty.
Represent the analysis usage information of a pass.
void initializeLiveIntervalsPass(PassRegistry &)
FunctionPass * createDefaultPBQPRegisterAllocator()
PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean Quadratic Prograaming (PBQ...
FunctionPass class - This class is used to implement most global optimizations.
static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI, const MachineFunction &MF)
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
void apply(Opt *O, const Mod &M, const Mods &...Ms)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
GraphMetadata & getMetadata()
Get a reference to the graph metadata.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void assignVirt2Phys(unsigned virtReg, MCPhysReg physReg)
creates a mapping for the specified virtual register to the specified physical register ...
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.
bool test(unsigned Idx) const
const Matrix & getEdgeCosts(EdgeId EId) const
Get an edge's cost matrix.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
LiveInterval & getInterval(unsigned Reg)
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.
The file should be opened in text mode on platforms that make this distinction.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
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.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
A raw_ostream that writes to a file descriptor.
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.
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
MachineRegisterInfo & getRegInfo() const
const MatrixPtr & getEdgeCostsPtr(EdgeId EId) const
Get a MatrixPtr to a node's cost matrix.
This class implements an extremely fast bulk output stream that can only output to a stream...
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.
StringRef - Represent a constant reference to a string, i.e.
NodeId addNode(OtherVectorT Costs)
Add a node with the given costs.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Simple wrapper around std::function<void(raw_ostream&)>.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
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...
bool reg_nodbg_empty(unsigned RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions...
LiveRange & getRegUnit(unsigned Unit)
Return the live range for register unit Unit.
Properties which a MachineFunction may have at a given point in time.