1 //===------ RegAllocPBQP.cpp ---- PBQP Register Allocator -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a Partitioned Boolean Quadratic Programming (PBQP) based
11 // register allocator for LLVM. This allocator works by constructing a PBQP
12 // problem representing the register allocation problem under consideration,
13 // solving this using a PBQP solver, and mapping the solution back to a
14 // register assignment. If any variables are selected for spilling then spill
15 // code is inserted and the process repeated.
17 // The PBQP solver (pbqp.c) provided for this allocator uses a heuristic tuned
18 // for register allocation. For more information on PBQP for register
19 // allocation, see the following papers:
21 // (1) Hames, L. and Scholz, B. 2006. Nearly optimal register allocation with
22 // PBQP. In Proceedings of the 7th Joint Modular Languages Conference
23 // (JMLC'06). LNCS, vol. 4228. Springer, New York, NY, USA. 346-361.
25 // (2) Scholz, B., Eckstein, E. 2002. Register allocation for irregular
26 // architectures. In Proceedings of the Joint Conference on Languages,
27 // Compilers and Tools for Embedded Systems (LCTES'02), ACM Press, New York,
30 //===----------------------------------------------------------------------===//
32 #include "llvm/CodeGen/RegAllocPBQP.h"
33 #include "RegisterCoalescer.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/CodeGen/CalcSpillWeights.h"
37 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
38 #include "llvm/CodeGen/LiveRangeEdit.h"
39 #include "llvm/CodeGen/LiveStackAnalysis.h"
40 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
41 #include "llvm/CodeGen/MachineDominators.h"
42 #include "llvm/CodeGen/MachineFunctionPass.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/CodeGen/RegAllocRegistry.h"
46 #include "llvm/CodeGen/VirtRegMap.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Target/TargetInstrInfo.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
62 #define DEBUG_TYPE "regalloc"
64 static RegisterRegAlloc
65 RegisterPBQPRepAlloc("pbqp", "PBQP register allocator",
66 createDefaultPBQPRegisterAllocator);
69 PBQPCoalescing("pbqp-coalescing",
70 cl::desc("Attempt coalescing during PBQP register allocation."),
71 cl::init(false), cl::Hidden);
75 PBQPDumpGraphs("pbqp-dump-graphs",
76 cl::desc("Dump graphs for each function/round in the compilation unit."),
77 cl::init(false), cl::Hidden);
83 /// PBQP based allocators solve the register allocation problem by mapping
84 /// register allocation problems to Partitioned Boolean Quadratic
85 /// Programming problems.
86 class RegAllocPBQP : public MachineFunctionPass {
91 /// Construct a PBQP register allocator.
92 RegAllocPBQP(char *cPassID = nullptr)
93 : MachineFunctionPass(ID), customPassID(cPassID) {
94 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
95 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
97 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
100 /// Return the pass name.
101 const char* getPassName() const override {
102 return "PBQP Register Allocator";
105 /// PBQP analysis usage.
106 void getAnalysisUsage(AnalysisUsage &au) const override;
108 /// Perform register allocation
109 bool runOnMachineFunction(MachineFunction &MF) override;
113 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
114 typedef std::vector<const LiveInterval*> Node2LIMap;
115 typedef std::vector<unsigned> AllowedSet;
116 typedef std::vector<AllowedSet> AllowedSetMap;
117 typedef std::pair<unsigned, unsigned> RegPair;
118 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
119 typedef std::set<unsigned> RegSet;
123 RegSet VRegsToAlloc, EmptyIntervalVRegs;
125 /// \brief Finds the initial set of vreg intervals to allocate.
126 void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS);
128 /// \brief Constructs an initial graph.
129 void initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM, Spiller &VRegSpiller);
131 /// \brief Spill the given VReg.
132 void spillVReg(unsigned VReg, SmallVectorImpl<unsigned> &NewIntervals,
133 MachineFunction &MF, LiveIntervals &LIS, VirtRegMap &VRM,
134 Spiller &VRegSpiller);
136 /// \brief Given a solved PBQP problem maps this solution back to a register
138 bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
139 const PBQP::Solution &Solution,
141 Spiller &VRegSpiller);
143 /// \brief Postprocessing before final spilling. Sets basic block "live in"
145 void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
146 VirtRegMap &VRM) const;
150 char RegAllocPBQP::ID = 0;
152 /// @brief Set spill costs for each node in the PBQP reg-alloc graph.
153 class SpillCosts : public PBQPRAConstraint {
155 void apply(PBQPRAGraph &G) override {
156 LiveIntervals &LIS = G.getMetadata().LIS;
158 // A minimum spill costs, so that register constraints can can be set
159 // without normalization in the [0.0:MinSpillCost( interval.
160 const PBQP::PBQPNum MinSpillCost = 10.0;
162 for (auto NId : G.nodeIds()) {
163 PBQP::PBQPNum SpillCost =
164 LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight;
165 if (SpillCost == 0.0)
166 SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
168 SpillCost += MinSpillCost;
169 PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
170 NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
171 G.setNodeCosts(NId, std::move(NodeCosts));
176 /// @brief Add interference edges between overlapping vregs.
177 class Interference : public PBQPRAConstraint {
180 typedef const PBQP::RegAlloc::AllowedRegVector* AllowedRegVecPtr;
181 typedef std::pair<AllowedRegVecPtr, AllowedRegVecPtr> IKey;
182 typedef DenseMap<IKey, PBQPRAGraph::MatrixPtr> IMatrixCache;
183 typedef DenseSet<IKey> DisjointAllowedRegsCache;
185 bool haveDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
186 PBQPRAGraph::NodeId MId,
187 const DisjointAllowedRegsCache &D) const {
188 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
189 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
195 return D.count(IKey(NRegs, MRegs)) > 0;
197 return D.count(IKey(MRegs, NRegs)) > 0;
200 void setDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
201 PBQPRAGraph::NodeId MId,
202 DisjointAllowedRegsCache &D) {
203 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
204 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
206 assert(NRegs != MRegs && "AllowedRegs can not be disjoint with itself");
209 D.insert(IKey(NRegs, MRegs));
211 D.insert(IKey(MRegs, NRegs));
214 // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
215 // for the fast interference graph construction algorithm. The last is there
216 // to save us from looking up node ids via the VRegToNode map in the graph
218 typedef std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>
221 static SlotIndex getStartPoint(const IntervalInfo &I) {
222 return std::get<0>(I)->segments[std::get<1>(I)].start;
225 static SlotIndex getEndPoint(const IntervalInfo &I) {
226 return std::get<0>(I)->segments[std::get<1>(I)].end;
229 static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
230 return std::get<2>(I);
233 static bool lowestStartPoint(const IntervalInfo &I1,
234 const IntervalInfo &I2) {
235 // Condition reversed because priority queue has the *highest* element at
236 // the front, rather than the lowest.
237 return getStartPoint(I1) > getStartPoint(I2);
240 static bool lowestEndPoint(const IntervalInfo &I1,
241 const IntervalInfo &I2) {
242 SlotIndex E1 = getEndPoint(I1);
243 SlotIndex E2 = getEndPoint(I2);
251 // If two intervals end at the same point, we need a way to break the tie or
252 // the set will assume they're actually equal and refuse to insert a
253 // "duplicate". Just compare the vregs - fast and guaranteed unique.
254 return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
257 static bool isAtLastSegment(const IntervalInfo &I) {
258 return std::get<1>(I) == std::get<0>(I)->size() - 1;
261 static IntervalInfo nextSegment(const IntervalInfo &I) {
262 return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
267 void apply(PBQPRAGraph &G) override {
268 // The following is loosely based on the linear scan algorithm introduced in
269 // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
270 // isn't linear, because the size of the active set isn't bound by the
271 // number of registers, but rather the size of the largest clique in the
272 // graph. Still, we expect this to be better than N^2.
273 LiveIntervals &LIS = G.getMetadata().LIS;
275 // Interferenc matrices are incredibly regular - they're only a function of
276 // the allowed sets, so we cache them to avoid the overhead of constructing
277 // and uniquing them.
280 // Cache known disjoint allowed registers pairs
281 DisjointAllowedRegsCache D;
283 typedef std::set<IntervalInfo, decltype(&lowestEndPoint)> IntervalSet;
284 typedef std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
285 decltype(&lowestStartPoint)> IntervalQueue;
286 IntervalSet Active(lowestEndPoint);
287 IntervalQueue Inactive(lowestStartPoint);
289 // Start by building the inactive set.
290 for (auto NId : G.nodeIds()) {
291 unsigned VReg = G.getNodeMetadata(NId).getVReg();
292 LiveInterval &LI = LIS.getInterval(VReg);
293 assert(!LI.empty() && "PBQP graph contains node for empty interval");
294 Inactive.push(std::make_tuple(&LI, 0, NId));
297 while (!Inactive.empty()) {
298 // Tentatively grab the "next" interval - this choice may be overriden
300 IntervalInfo Cur = Inactive.top();
302 // Retire any active intervals that end before Cur starts.
303 IntervalSet::iterator RetireItr = Active.begin();
304 while (RetireItr != Active.end() &&
305 (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
306 // If this interval has subsequent segments, add the next one to the
308 if (!isAtLastSegment(*RetireItr))
309 Inactive.push(nextSegment(*RetireItr));
313 Active.erase(Active.begin(), RetireItr);
315 // One of the newly retired segments may actually start before the
316 // Cur segment, so re-grab the front of the inactive list.
317 Cur = Inactive.top();
320 // At this point we know that Cur overlaps all active intervals. Add the
321 // interference edges.
322 PBQP::GraphBase::NodeId NId = getNodeId(Cur);
323 for (const auto &A : Active) {
324 PBQP::GraphBase::NodeId MId = getNodeId(A);
326 // Do not add an edge when the nodes' allowed registers do not
327 // intersect: there is obviously no interference.
328 if (haveDisjointAllowedRegs(G, NId, MId, D))
331 // Check that we haven't already added this edge
332 // FIXME: findEdge is expensive in the worst case (O(max_clique(G))).
333 // It might be better to replace this with a local bit-matrix.
334 if (G.findEdge(NId, MId) != PBQPRAGraph::invalidEdgeId())
337 // This is a new edge - add it to the graph.
338 if (!createInterferenceEdge(G, NId, MId, C))
339 setDisjointAllowedRegs(G, NId, MId, D);
342 // Finally, add Cur to the Active set.
349 // Create an Interference edge and add it to the graph, unless it is
350 // a null matrix, meaning the nodes' allowed registers do not have any
351 // interference. This case occurs frequently between integer and floating
352 // point registers for example.
353 // return true iff both nodes interferes.
354 bool createInterferenceEdge(PBQPRAGraph &G,
355 PBQPRAGraph::NodeId NId, PBQPRAGraph::NodeId MId,
358 const TargetRegisterInfo &TRI =
359 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
360 const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
361 const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
363 // Try looking the edge costs up in the IMatrixCache first.
364 IKey K(&NRegs, &MRegs);
365 IMatrixCache::iterator I = C.find(K);
367 G.addEdgeBypassingCostAllocator(NId, MId, I->second);
371 PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
372 bool NodesInterfere = false;
373 for (unsigned I = 0; I != NRegs.size(); ++I) {
374 unsigned PRegN = NRegs[I];
375 for (unsigned J = 0; J != MRegs.size(); ++J) {
376 unsigned PRegM = MRegs[J];
377 if (TRI.regsOverlap(PRegN, PRegM)) {
378 M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
379 NodesInterfere = true;
387 PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
388 C[K] = G.getEdgeCostsPtr(EId);
395 class Coalescing : public PBQPRAConstraint {
397 void apply(PBQPRAGraph &G) override {
398 MachineFunction &MF = G.getMetadata().MF;
399 MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
400 CoalescerPair CP(*MF.getSubtarget().getRegisterInfo());
402 // Scan the machine function and add a coalescing cost whenever CoalescerPair
404 for (const auto &MBB : MF) {
405 for (const auto &MI : MBB) {
407 // Skip not-coalescable or already coalesced copies.
408 if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
411 unsigned DstReg = CP.getDstReg();
412 unsigned SrcReg = CP.getSrcReg();
414 const float Scale = 1.0f / MBFI.getEntryFreq();
415 PBQP::PBQPNum CBenefit = MBFI.getBlockFreq(&MBB).getFrequency() * Scale;
418 if (!MF.getRegInfo().isAllocatable(DstReg))
421 PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
423 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
424 G.getNodeMetadata(NId).getAllowedRegs();
426 unsigned PRegOpt = 0;
427 while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
430 if (PRegOpt < Allowed.size()) {
431 PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
432 NewCosts[PRegOpt + 1] -= CBenefit;
433 G.setNodeCosts(NId, std::move(NewCosts));
436 PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
437 PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
438 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
439 &G.getNodeMetadata(N1Id).getAllowedRegs();
440 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
441 &G.getNodeMetadata(N2Id).getAllowedRegs();
443 PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
444 if (EId == G.invalidEdgeId()) {
445 PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
446 Allowed2->size() + 1, 0);
447 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
448 G.addEdge(N1Id, N2Id, std::move(Costs));
450 if (G.getEdgeNode1Id(EId) == N2Id) {
451 std::swap(N1Id, N2Id);
452 std::swap(Allowed1, Allowed2);
454 PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
455 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
456 G.updateEdgeCosts(EId, std::move(Costs));
465 void addVirtRegCoalesce(
466 PBQPRAGraph::RawMatrix &CostMat,
467 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
468 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
469 PBQP::PBQPNum Benefit) {
470 assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
471 assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
472 for (unsigned I = 0; I != Allowed1.size(); ++I) {
473 unsigned PReg1 = Allowed1[I];
474 for (unsigned J = 0; J != Allowed2.size(); ++J) {
475 unsigned PReg2 = Allowed2[J];
477 CostMat[I + 1][J + 1] -= Benefit;
484 } // End anonymous namespace.
486 // Out-of-line destructor/anchor for PBQPRAConstraint.
487 PBQPRAConstraint::~PBQPRAConstraint() {}
488 void PBQPRAConstraint::anchor() {}
489 void PBQPRAConstraintList::anchor() {}
491 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
492 au.setPreservesCFG();
493 au.addRequired<AliasAnalysis>();
494 au.addPreserved<AliasAnalysis>();
495 au.addRequired<SlotIndexes>();
496 au.addPreserved<SlotIndexes>();
497 au.addRequired<LiveIntervals>();
498 au.addPreserved<LiveIntervals>();
499 //au.addRequiredID(SplitCriticalEdgesID);
501 au.addRequiredID(*customPassID);
502 au.addRequired<LiveStacks>();
503 au.addPreserved<LiveStacks>();
504 au.addRequired<MachineBlockFrequencyInfo>();
505 au.addPreserved<MachineBlockFrequencyInfo>();
506 au.addRequired<MachineLoopInfo>();
507 au.addPreserved<MachineLoopInfo>();
508 au.addRequired<MachineDominatorTree>();
509 au.addPreserved<MachineDominatorTree>();
510 au.addRequired<VirtRegMap>();
511 au.addPreserved<VirtRegMap>();
512 MachineFunctionPass::getAnalysisUsage(au);
515 void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
516 LiveIntervals &LIS) {
517 const MachineRegisterInfo &MRI = MF.getRegInfo();
519 // Iterate over all live ranges.
520 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
521 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
522 if (MRI.reg_nodbg_empty(Reg))
524 LiveInterval &LI = LIS.getInterval(Reg);
526 // If this live interval is non-empty we will use pbqp to allocate it.
527 // Empty intervals we allocate in a simple post-processing stage in
530 VRegsToAlloc.insert(LI.reg);
532 EmptyIntervalVRegs.insert(LI.reg);
537 static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI,
538 const MachineFunction &MF) {
539 const MCPhysReg *CSR = TRI.getCalleeSavedRegs(&MF);
540 for (unsigned i = 0; CSR[i] != 0; ++i)
541 if (TRI.regsOverlap(reg, CSR[i]))
546 void RegAllocPBQP::initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM,
547 Spiller &VRegSpiller) {
548 MachineFunction &MF = G.getMetadata().MF;
550 LiveIntervals &LIS = G.getMetadata().LIS;
551 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
552 const TargetRegisterInfo &TRI =
553 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
555 std::vector<unsigned> Worklist(VRegsToAlloc.begin(), VRegsToAlloc.end());
557 while (!Worklist.empty()) {
558 unsigned VReg = Worklist.back();
561 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
562 LiveInterval &VRegLI = LIS.getInterval(VReg);
564 // Record any overlaps with regmask operands.
565 BitVector RegMaskOverlaps;
566 LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
568 // Compute an initial allowed set for the current vreg.
569 std::vector<unsigned> VRegAllowed;
570 ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
571 for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
572 unsigned PReg = RawPRegOrder[I];
573 if (MRI.isReserved(PReg))
576 // vregLI crosses a regmask operand that clobbers preg.
577 if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
580 // vregLI overlaps fixed regunit interference.
581 bool Interference = false;
582 for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
583 if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
591 // preg is usable for this virtual register.
592 VRegAllowed.push_back(PReg);
595 // Check for vregs that have no allowed registers. These should be
596 // pre-spilled and the new vregs added to the worklist.
597 if (VRegAllowed.empty()) {
598 SmallVector<unsigned, 8> NewVRegs;
599 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
600 Worklist.insert(Worklist.end(), NewVRegs.begin(), NewVRegs.end());
604 PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
606 // Tweak cost of callee saved registers, as using then force spilling and
607 // restoring them. This would only happen in the prologue / epilogue though.
608 for (unsigned i = 0; i != VRegAllowed.size(); ++i)
609 if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF))
610 NodeCosts[1 + i] += 1.0;
612 PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
613 G.getNodeMetadata(NId).setVReg(VReg);
614 G.getNodeMetadata(NId).setAllowedRegs(
615 G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
616 G.getMetadata().setNodeIdForVReg(VReg, NId);
620 void RegAllocPBQP::spillVReg(unsigned VReg,
621 SmallVectorImpl<unsigned> &NewIntervals,
622 MachineFunction &MF, LiveIntervals &LIS,
623 VirtRegMap &VRM, Spiller &VRegSpiller) {
625 VRegsToAlloc.erase(VReg);
626 LiveRangeEdit LRE(&LIS.getInterval(VReg), NewIntervals, MF, LIS, &VRM);
627 VRegSpiller.spill(LRE);
629 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
631 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> SPILLED (Cost: "
632 << LRE.getParent().weight << ", New vregs: ");
634 // Copy any newly inserted live intervals into the list of regs to
636 for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
638 const LiveInterval &LI = LIS.getInterval(*I);
639 assert(!LI.empty() && "Empty spill range.");
640 DEBUG(dbgs() << PrintReg(LI.reg, &TRI) << " ");
641 VRegsToAlloc.insert(LI.reg);
644 DEBUG(dbgs() << ")\n");
647 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
648 const PBQP::Solution &Solution,
650 Spiller &VRegSpiller) {
651 MachineFunction &MF = G.getMetadata().MF;
652 LiveIntervals &LIS = G.getMetadata().LIS;
653 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
656 // Set to true if we have any spills
657 bool AnotherRoundNeeded = false;
659 // Clear the existing allocation.
662 // Iterate over the nodes mapping the PBQP solution to a register
664 for (auto NId : G.nodeIds()) {
665 unsigned VReg = G.getNodeMetadata(NId).getVReg();
666 unsigned AllocOption = Solution.getSelection(NId);
668 if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
669 unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
670 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> "
671 << TRI.getName(PReg) << "\n");
672 assert(PReg != 0 && "Invalid preg selected.");
673 VRM.assignVirt2Phys(VReg, PReg);
675 // Spill VReg. If this introduces new intervals we'll need another round
677 SmallVector<unsigned, 8> NewVRegs;
678 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
679 AnotherRoundNeeded |= !NewVRegs.empty();
683 return !AnotherRoundNeeded;
686 void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
688 VirtRegMap &VRM) const {
689 MachineRegisterInfo &MRI = MF.getRegInfo();
691 // First allocate registers for the empty intervals.
692 for (RegSet::const_iterator
693 I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
695 LiveInterval &LI = LIS.getInterval(*I);
697 unsigned PReg = MRI.getSimpleHint(LI.reg);
700 const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg);
701 PReg = RC.getRawAllocationOrder(MF).front();
704 VRM.assignVirt2Phys(LI.reg, PReg);
708 static inline float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size,
710 // All intervals have a spill weight that is mostly proportional to the number
711 // of uses, with uses in loops having a bigger weight.
712 return NumInstr * normalizeSpillWeight(UseDefFreq, Size, 1);
715 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
716 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
717 MachineBlockFrequencyInfo &MBFI =
718 getAnalysis<MachineBlockFrequencyInfo>();
720 calculateSpillWeightsAndHints(LIS, MF, getAnalysis<MachineLoopInfo>(), MBFI,
721 normalizePBQPSpillWeight);
723 VirtRegMap &VRM = getAnalysis<VirtRegMap>();
725 std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
727 MF.getRegInfo().freezeReservedRegs(MF);
729 DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
731 // Allocator main loop:
733 // * Map current regalloc problem to a PBQP problem
734 // * Solve the PBQP problem
735 // * Map the solution back to a register allocation
736 // * Spill if necessary
738 // This process is continued till no more spills are generated.
740 // Find the vreg intervals in need of allocation.
741 findVRegIntervalsToAlloc(MF, LIS);
744 const Function &F = *MF.getFunction();
745 std::string FullyQualifiedName =
746 F.getParent()->getModuleIdentifier() + "." + F.getName().str();
749 // If there are non-empty intervals allocate them using pbqp.
750 if (!VRegsToAlloc.empty()) {
752 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
753 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
754 llvm::make_unique<PBQPRAConstraintList>();
755 ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
756 ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
758 ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
759 ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
761 bool PBQPAllocComplete = false;
764 while (!PBQPAllocComplete) {
765 DEBUG(dbgs() << " PBQP Regalloc round " << Round << ":\n");
767 PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
768 initializeGraph(G, VRM, *VRegSpiller);
769 ConstraintsRoot->apply(G);
772 if (PBQPDumpGraphs) {
773 std::ostringstream RS;
775 std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
778 raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text);
779 DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
780 << GraphFileName << "\"\n");
785 PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
786 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
791 // Finalise allocation, allocate empty ranges.
792 finalizeAlloc(MF, LIS, VRM);
793 VRegsToAlloc.clear();
794 EmptyIntervalVRegs.clear();
796 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
802 // A helper class for printing node and register info in a consistent way
803 class PrintNodeInfo {
805 typedef PBQP::RegAlloc::PBQPRAGraph Graph;
806 typedef PBQP::RegAlloc::PBQPRAGraph::NodeId NodeId;
808 PrintNodeInfo(NodeId NId, const Graph &G) : G(G), NId(NId) {}
810 void print(raw_ostream &OS) const {
811 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
812 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
813 unsigned VReg = G.getNodeMetadata(NId).getVReg();
814 const char *RegClassName = TRI->getRegClassName(MRI.getRegClass(VReg));
815 OS << NId << " (" << RegClassName << ':' << PrintReg(VReg, TRI) << ')';
823 inline raw_ostream &operator<<(raw_ostream &OS, const PrintNodeInfo &PR) {
827 } // anonymous namespace
829 void PBQP::RegAlloc::PBQPRAGraph::dump(raw_ostream &OS) const {
830 for (auto NId : nodeIds()) {
831 const Vector &Costs = getNodeCosts(NId);
832 assert(Costs.getLength() != 0 && "Empty vector in graph.");
833 OS << PrintNodeInfo(NId, *this) << ": " << Costs << '\n';
837 for (auto EId : edgeIds()) {
838 NodeId N1Id = getEdgeNode1Id(EId);
839 NodeId N2Id = getEdgeNode2Id(EId);
840 assert(N1Id != N2Id && "PBQP graphs should not have self-edges.");
841 const Matrix &M = getEdgeCosts(EId);
842 assert(M.getRows() != 0 && "No rows in matrix.");
843 assert(M.getCols() != 0 && "No cols in matrix.");
844 OS << PrintNodeInfo(N1Id, *this) << ' ' << M.getRows() << " rows / ";
845 OS << PrintNodeInfo(N2Id, *this) << ' ' << M.getCols() << " cols:\n";
850 void PBQP::RegAlloc::PBQPRAGraph::dump() const { dump(dbgs()); }
852 void PBQP::RegAlloc::PBQPRAGraph::printDot(raw_ostream &OS) const {
854 for (auto NId : nodeIds()) {
855 OS << " node" << NId << " [ label=\""
856 << PrintNodeInfo(NId, *this) << "\\n"
857 << getNodeCosts(NId) << "\" ]\n";
860 OS << " edge [ len=" << nodeIds().size() << " ]\n";
861 for (auto EId : edgeIds()) {
862 OS << " node" << getEdgeNode1Id(EId)
863 << " -- node" << getEdgeNode2Id(EId)
865 const Matrix &EdgeCosts = getEdgeCosts(EId);
866 for (unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
867 OS << EdgeCosts.getRowAsVector(i) << "\\n";
874 FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
875 return new RegAllocPBQP(customPassID);
878 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
879 return createPBQPRegisterAllocator();