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/TargetMachine.h"
53 #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(std::unique_ptr<PBQPBuilder> b, char *cPassID = nullptr)
93 : MachineFunctionPass(ID), builder(std::move(b)), 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;
121 std::unique_ptr<PBQPBuilder> builder;
126 const TargetMachine *tm;
127 const TargetRegisterInfo *tri;
128 const TargetInstrInfo *tii;
129 MachineRegisterInfo *mri;
130 const MachineBlockFrequencyInfo *mbfi;
132 std::unique_ptr<Spiller> spiller;
137 RegSet vregsToAlloc, emptyIntervalVRegs;
139 /// \brief Finds the initial set of vreg intervals to allocate.
140 void findVRegIntervalsToAlloc();
142 /// \brief Given a solved PBQP problem maps this solution back to a register
144 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
145 const PBQP::Solution &solution);
147 /// \brief Postprocessing before final spilling. Sets basic block "live in"
149 void finalizeAlloc() const;
153 char RegAllocPBQP::ID = 0;
155 } // End anonymous namespace.
157 unsigned PBQPRAProblem::getVRegForNode(PBQPRAGraph::NodeId node) const {
158 Node2VReg::const_iterator vregItr = node2VReg.find(node);
159 assert(vregItr != node2VReg.end() && "No vreg for node.");
160 return vregItr->second;
163 PBQPRAGraph::NodeId PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
164 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
165 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
166 return nodeItr->second;
170 const PBQPRAProblem::AllowedSet&
171 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
172 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
173 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
174 const AllowedSet &allowedSet = allowedSetItr->second;
178 unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
179 assert(isPRegOption(vreg, option) && "Not a preg option.");
181 const AllowedSet& allowedSet = getAllowedSet(vreg);
182 assert(option <= allowedSet.size() && "Option outside allowed set.");
183 return allowedSet[option - 1];
186 std::unique_ptr<PBQPRAProblem>
187 PBQPBuilder::build(MachineFunction *mf, const LiveIntervals *lis,
188 const MachineBlockFrequencyInfo *mbfi, const RegSet &vregs) {
190 LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
191 MachineRegisterInfo *mri = &mf->getRegInfo();
192 const TargetRegisterInfo *tri = mf->getSubtarget().getRegisterInfo();
194 auto p = llvm::make_unique<PBQPRAProblem>();
195 PBQPRAGraph &g = p->getGraph();
198 // Collect the set of preg intervals, record that they're used in the MF.
199 for (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
200 if (mri->def_empty(Reg))
203 mri->setPhysRegUsed(Reg);
206 // Iterate over vregs.
207 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
208 vregItr != vregEnd; ++vregItr) {
209 unsigned vreg = *vregItr;
210 const TargetRegisterClass *trc = mri->getRegClass(vreg);
211 LiveInterval *vregLI = &LIS->getInterval(vreg);
213 // Record any overlaps with regmask operands.
214 BitVector regMaskOverlaps;
215 LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
217 // Compute an initial allowed set for the current vreg.
218 typedef std::vector<unsigned> VRAllowed;
220 ArrayRef<MCPhysReg> rawOrder = trc->getRawAllocationOrder(*mf);
221 for (unsigned i = 0; i != rawOrder.size(); ++i) {
222 unsigned preg = rawOrder[i];
223 if (mri->isReserved(preg))
226 // vregLI crosses a regmask operand that clobbers preg.
227 if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
230 // vregLI overlaps fixed regunit interference.
231 bool Interference = false;
232 for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
233 if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
241 // preg is usable for this virtual register.
242 vrAllowed.push_back(preg);
245 PBQP::Vector nodeCosts(vrAllowed.size() + 1, 0);
247 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
248 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
250 addSpillCosts(nodeCosts, spillCost);
252 // Construct the node.
253 PBQPRAGraph::NodeId nId = g.addNode(std::move(nodeCosts));
255 // Record the mapping and allowed set in the problem.
256 p->recordVReg(vreg, nId, vrAllowed.begin(), vrAllowed.end());
260 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
261 vr1Itr != vrEnd; ++vr1Itr) {
262 unsigned vr1 = *vr1Itr;
263 const LiveInterval &l1 = lis->getInterval(vr1);
264 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
266 for (RegSet::const_iterator vr2Itr = std::next(vr1Itr); vr2Itr != vrEnd;
268 unsigned vr2 = *vr2Itr;
269 const LiveInterval &l2 = lis->getInterval(vr2);
270 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
272 assert(!l2.empty() && "Empty interval in vreg set?");
273 if (l1.overlaps(l2)) {
274 PBQP::Matrix edgeCosts(vr1Allowed.size()+1, vr2Allowed.size()+1, 0);
275 addInterferenceCosts(edgeCosts, vr1Allowed, vr2Allowed, tri);
277 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
278 std::move(edgeCosts));
286 void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
287 PBQP::PBQPNum spillCost) {
288 costVec[0] = spillCost;
291 void PBQPBuilder::addInterferenceCosts(
292 PBQP::Matrix &costMat,
293 const PBQPRAProblem::AllowedSet &vr1Allowed,
294 const PBQPRAProblem::AllowedSet &vr2Allowed,
295 const TargetRegisterInfo *tri) {
296 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
297 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
299 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
300 unsigned preg1 = vr1Allowed[i];
302 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
303 unsigned preg2 = vr2Allowed[j];
305 if (tri->regsOverlap(preg1, preg2)) {
306 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
312 std::unique_ptr<PBQPRAProblem>
313 PBQPBuilderWithCoalescing::build(MachineFunction *mf, const LiveIntervals *lis,
314 const MachineBlockFrequencyInfo *mbfi,
315 const RegSet &vregs) {
317 std::unique_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, mbfi, vregs);
318 PBQPRAGraph &g = p->getGraph();
320 const TargetMachine &tm = mf->getTarget();
321 CoalescerPair cp(*tm.getSubtargetImpl()->getRegisterInfo());
323 // Scan the machine function and add a coalescing cost whenever CoalescerPair
325 for (const auto &mbb : *mf) {
326 for (const auto &mi : mbb) {
327 if (!cp.setRegisters(&mi)) {
328 continue; // Not coalescable.
331 if (cp.getSrcReg() == cp.getDstReg()) {
332 continue; // Already coalesced.
335 unsigned dst = cp.getDstReg(),
336 src = cp.getSrcReg();
338 const float copyFactor = 0.5; // Cost of copy relative to load. Current
339 // value plucked randomly out of the air.
341 PBQP::PBQPNum cBenefit =
342 copyFactor * LiveIntervals::getSpillWeight(false, true, mbfi, &mi);
345 if (!mf->getRegInfo().isAllocatable(dst)) {
349 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
350 unsigned pregOpt = 0;
351 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
354 if (pregOpt < allowed.size()) {
355 ++pregOpt; // +1 to account for spill option.
356 PBQPRAGraph::NodeId node = p->getNodeForVReg(src);
357 DEBUG(llvm::dbgs() << "Reading node costs for node " << node << "\n");
358 DEBUG(llvm::dbgs() << "Source node: " << &g.getNodeCosts(node) << "\n");
359 PBQP::Vector newCosts(g.getNodeCosts(node));
360 addPhysRegCoalesce(newCosts, pregOpt, cBenefit);
361 g.setNodeCosts(node, newCosts);
364 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
365 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
366 PBQPRAGraph::NodeId node1 = p->getNodeForVReg(dst);
367 PBQPRAGraph::NodeId node2 = p->getNodeForVReg(src);
368 PBQPRAGraph::EdgeId edge = g.findEdge(node1, node2);
369 if (edge == g.invalidEdgeId()) {
370 PBQP::Matrix costs(allowed1->size() + 1, allowed2->size() + 1, 0);
371 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
372 g.addEdge(node1, node2, costs);
374 if (g.getEdgeNode1Id(edge) == node2) {
375 std::swap(node1, node2);
376 std::swap(allowed1, allowed2);
378 PBQP::Matrix costs(g.getEdgeCosts(edge));
379 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
380 g.setEdgeCosts(edge, costs);
389 void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
391 PBQP::PBQPNum benefit) {
392 costVec[pregOption] += -benefit;
395 void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
396 PBQP::Matrix &costMat,
397 const PBQPRAProblem::AllowedSet &vr1Allowed,
398 const PBQPRAProblem::AllowedSet &vr2Allowed,
399 PBQP::PBQPNum benefit) {
401 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
402 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
404 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
405 unsigned preg1 = vr1Allowed[i];
406 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
407 unsigned preg2 = vr2Allowed[j];
409 if (preg1 == preg2) {
410 costMat[i + 1][j + 1] += -benefit;
417 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
418 au.setPreservesCFG();
419 au.addRequired<AliasAnalysis>();
420 au.addPreserved<AliasAnalysis>();
421 au.addRequired<SlotIndexes>();
422 au.addPreserved<SlotIndexes>();
423 au.addRequired<LiveIntervals>();
424 au.addPreserved<LiveIntervals>();
425 //au.addRequiredID(SplitCriticalEdgesID);
427 au.addRequiredID(*customPassID);
428 au.addRequired<LiveStacks>();
429 au.addPreserved<LiveStacks>();
430 au.addRequired<MachineBlockFrequencyInfo>();
431 au.addPreserved<MachineBlockFrequencyInfo>();
432 au.addRequired<MachineLoopInfo>();
433 au.addPreserved<MachineLoopInfo>();
434 au.addRequired<MachineDominatorTree>();
435 au.addPreserved<MachineDominatorTree>();
436 au.addRequired<VirtRegMap>();
437 au.addPreserved<VirtRegMap>();
438 MachineFunctionPass::getAnalysisUsage(au);
441 void RegAllocPBQP::findVRegIntervalsToAlloc() {
443 // Iterate over all live ranges.
444 for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
445 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
446 if (mri->reg_nodbg_empty(Reg))
448 LiveInterval *li = &lis->getInterval(Reg);
450 // If this live interval is non-empty we will use pbqp to allocate it.
451 // Empty intervals we allocate in a simple post-processing stage in
454 vregsToAlloc.insert(li->reg);
456 emptyIntervalVRegs.insert(li->reg);
461 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
462 const PBQP::Solution &solution) {
463 // Set to true if we have any spills
464 bool anotherRoundNeeded = false;
466 // Clear the existing allocation.
469 const PBQPRAGraph &g = problem.getGraph();
470 // Iterate over the nodes mapping the PBQP solution to a register
472 for (auto NId : g.nodeIds()) {
473 unsigned vreg = problem.getVRegForNode(NId);
474 unsigned alloc = solution.getSelection(NId);
476 if (problem.isPRegOption(vreg, alloc)) {
477 unsigned preg = problem.getPRegForOption(vreg, alloc);
478 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
479 << tri->getName(preg) << "\n");
480 assert(preg != 0 && "Invalid preg selected.");
481 vrm->assignVirt2Phys(vreg, preg);
482 } else if (problem.isSpillOption(vreg, alloc)) {
483 vregsToAlloc.erase(vreg);
484 SmallVector<unsigned, 8> newSpills;
485 LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
488 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
489 << LRE.getParent().weight << ", New vregs: ");
491 // Copy any newly inserted live intervals into the list of regs to
493 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
495 LiveInterval &li = lis->getInterval(*itr);
496 assert(!li.empty() && "Empty spill range.");
497 DEBUG(dbgs() << PrintReg(li.reg, tri) << " ");
498 vregsToAlloc.insert(li.reg);
501 DEBUG(dbgs() << ")\n");
503 // We need another round if spill intervals were added.
504 anotherRoundNeeded |= !LRE.empty();
506 llvm_unreachable("Unknown allocation option.");
510 return !anotherRoundNeeded;
514 void RegAllocPBQP::finalizeAlloc() const {
515 // First allocate registers for the empty intervals.
516 for (RegSet::const_iterator
517 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
519 LiveInterval *li = &lis->getInterval(*itr);
521 unsigned physReg = mri->getSimpleHint(li->reg);
524 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
525 physReg = liRC->getRawAllocationOrder(*mf).front();
528 vrm->assignVirt2Phys(li->reg, physReg);
532 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
535 tm = &mf->getTarget();
536 tri = tm->getSubtargetImpl()->getRegisterInfo();
537 tii = tm->getSubtargetImpl()->getInstrInfo();
538 mri = &mf->getRegInfo();
540 lis = &getAnalysis<LiveIntervals>();
541 lss = &getAnalysis<LiveStacks>();
542 mbfi = &getAnalysis<MachineBlockFrequencyInfo>();
544 calculateSpillWeightsAndHints(*lis, MF, getAnalysis<MachineLoopInfo>(),
547 vrm = &getAnalysis<VirtRegMap>();
548 spiller.reset(createInlineSpiller(*this, MF, *vrm));
550 mri->freezeReservedRegs(MF);
552 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
554 // Allocator main loop:
556 // * Map current regalloc problem to a PBQP problem
557 // * Solve the PBQP problem
558 // * Map the solution back to a register allocation
559 // * Spill if necessary
561 // This process is continued till no more spills are generated.
563 // Find the vreg intervals in need of allocation.
564 findVRegIntervalsToAlloc();
567 const Function* func = mf->getFunction();
569 func->getParent()->getModuleIdentifier() + "." +
570 func->getName().str();
573 // If there are non-empty intervals allocate them using pbqp.
574 if (!vregsToAlloc.empty()) {
576 bool pbqpAllocComplete = false;
579 while (!pbqpAllocComplete) {
580 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
582 std::unique_ptr<PBQPRAProblem> problem =
583 builder->build(mf, lis, mbfi, vregsToAlloc);
586 if (pbqpDumpGraphs) {
587 std::ostringstream rs;
589 std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
591 raw_fd_ostream os(graphFileName, EC, sys::fs::F_Text);
592 DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
593 << graphFileName << "\"\n");
594 problem->getGraph().dump(os);
598 PBQP::Solution solution =
599 PBQP::RegAlloc::solve(problem->getGraph());
601 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
607 // Finalise allocation, allocate empty ranges.
609 vregsToAlloc.clear();
610 emptyIntervalVRegs.clear();
612 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
618 llvm::createPBQPRegisterAllocator(std::unique_ptr<PBQPBuilder> builder,
619 char *customPassID) {
620 return new RegAllocPBQP(std::move(builder), customPassID);
623 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
624 std::unique_ptr<PBQPBuilder> Builder;
626 Builder = llvm::make_unique<PBQPBuilderWithCoalescing>();
628 Builder = llvm::make_unique<PBQPBuilder>();
629 return createPBQPRegisterAllocator(std::move(Builder));