1//===------ RegAllocPBQP.cpp ---- PBQP Register Allocator -------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
16//
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:
20//
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.
24//
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,
28//   NY, USA, 139-148.
29//
30//===----------------------------------------------------------------------===//
31
32#define DEBUG_TYPE "regalloc"
33
34#include "Spiller.h"
35#include "VirtRegMap.h"
36#include "RegisterCoalescer.h"
37#include "llvm/Module.h"
38#include "llvm/Analysis/AliasAnalysis.h"
39#include "llvm/CodeGen/CalcSpillWeights.h"
40#include "llvm/CodeGen/LiveIntervalAnalysis.h"
41#include "llvm/CodeGen/LiveRangeEdit.h"
42#include "llvm/CodeGen/LiveStackAnalysis.h"
43#include "llvm/CodeGen/RegAllocPBQP.h"
44#include "llvm/CodeGen/MachineDominators.h"
45#include "llvm/CodeGen/MachineFunctionPass.h"
46#include "llvm/CodeGen/MachineLoopInfo.h"
47#include "llvm/CodeGen/MachineRegisterInfo.h"
48#include "llvm/CodeGen/PBQP/HeuristicSolver.h"
49#include "llvm/CodeGen/PBQP/Graph.h"
50#include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
51#include "llvm/CodeGen/RegAllocRegistry.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Support/raw_ostream.h"
54#include "llvm/Target/TargetInstrInfo.h"
55#include "llvm/Target/TargetMachine.h"
56#include <limits>
57#include <memory>
58#include <set>
59#include <sstream>
60#include <vector>
61
62using namespace llvm;
63
64static RegisterRegAlloc
65registerPBQPRepAlloc("pbqp", "PBQP register allocator",
66                       createDefaultPBQPRegisterAllocator);
67
68static cl::opt<bool>
69pbqpCoalescing("pbqp-coalescing",
70                cl::desc("Attempt coalescing during PBQP register allocation."),
71                cl::init(false), cl::Hidden);
72
73#ifndef NDEBUG
74static cl::opt<bool>
75pbqpDumpGraphs("pbqp-dump-graphs",
76               cl::desc("Dump graphs for each function/round in the compilation unit."),
77               cl::init(false), cl::Hidden);
78#endif
79
80namespace {
81
82///
83/// PBQP based allocators solve the register allocation problem by mapping
84/// register allocation problems to Partitioned Boolean Quadratic
85/// Programming problems.
86class RegAllocPBQP : public MachineFunctionPass {
87public:
88
89  static char ID;
90
91  /// Construct a PBQP register allocator.
92  RegAllocPBQP(std::auto_ptr<PBQPBuilder> b, char *cPassID=0)
93      : MachineFunctionPass(ID), builder(b), customPassID(cPassID) {
94    initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
95    initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96    initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
97    initializeLiveStacksPass(*PassRegistry::getPassRegistry());
98    initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
99    initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
100  }
101
102  /// Return the pass name.
103  virtual const char* getPassName() const {
104    return "PBQP Register Allocator";
105  }
106
107  /// PBQP analysis usage.
108  virtual void getAnalysisUsage(AnalysisUsage &au) const;
109
110  /// Perform register allocation
111  virtual bool runOnMachineFunction(MachineFunction &MF);
112
113private:
114
115  typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
116  typedef std::vector<const LiveInterval*> Node2LIMap;
117  typedef std::vector<unsigned> AllowedSet;
118  typedef std::vector<AllowedSet> AllowedSetMap;
119  typedef std::pair<unsigned, unsigned> RegPair;
120  typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
121  typedef std::vector<PBQP::Graph::NodeItr> NodeVector;
122  typedef std::set<unsigned> RegSet;
123
124
125  std::auto_ptr<PBQPBuilder> builder;
126
127  char *customPassID;
128
129  MachineFunction *mf;
130  const TargetMachine *tm;
131  const TargetRegisterInfo *tri;
132  const TargetInstrInfo *tii;
133  const MachineLoopInfo *loopInfo;
134  MachineRegisterInfo *mri;
135
136  std::auto_ptr<Spiller> spiller;
137  LiveIntervals *lis;
138  LiveStacks *lss;
139  VirtRegMap *vrm;
140
141  RegSet vregsToAlloc, emptyIntervalVRegs;
142
143  /// \brief Finds the initial set of vreg intervals to allocate.
144  void findVRegIntervalsToAlloc();
145
146  /// \brief Given a solved PBQP problem maps this solution back to a register
147  /// assignment.
148  bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
149                         const PBQP::Solution &solution);
150
151  /// \brief Postprocessing before final spilling. Sets basic block "live in"
152  /// variables.
153  void finalizeAlloc() const;
154
155};
156
157char RegAllocPBQP::ID = 0;
158
159} // End anonymous namespace.
160
161unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
162  Node2VReg::const_iterator vregItr = node2VReg.find(node);
163  assert(vregItr != node2VReg.end() && "No vreg for node.");
164  return vregItr->second;
165}
166
167PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
168  VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
169  assert(nodeItr != vreg2Node.end() && "No node for vreg.");
170  return nodeItr->second;
171
172}
173
174const PBQPRAProblem::AllowedSet&
175  PBQPRAProblem::getAllowedSet(unsigned vreg) const {
176  AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
177  assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
178  const AllowedSet &allowedSet = allowedSetItr->second;
179  return allowedSet;
180}
181
182unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
183  assert(isPRegOption(vreg, option) && "Not a preg option.");
184
185  const AllowedSet& allowedSet = getAllowedSet(vreg);
186  assert(option <= allowedSet.size() && "Option outside allowed set.");
187  return allowedSet[option - 1];
188}
189
190std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
191                                                const LiveIntervals *lis,
192                                                const MachineLoopInfo *loopInfo,
193                                                const RegSet &vregs) {
194
195  LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
196  MachineRegisterInfo *mri = &mf->getRegInfo();
197  const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
198
199  std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
200  PBQP::Graph &g = p->getGraph();
201  RegSet pregs;
202
203  // Collect the set of preg intervals, record that they're used in the MF.
204  for (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
205    if (mri->def_empty(Reg))
206      continue;
207    pregs.insert(Reg);
208    mri->setPhysRegUsed(Reg);
209  }
210
211  // Iterate over vregs.
212  for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
213       vregItr != vregEnd; ++vregItr) {
214    unsigned vreg = *vregItr;
215    const TargetRegisterClass *trc = mri->getRegClass(vreg);
216    LiveInterval *vregLI = &LIS->getInterval(vreg);
217
218    // Record any overlaps with regmask operands.
219    BitVector regMaskOverlaps(tri->getNumRegs());
220    LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
221
222    // Compute an initial allowed set for the current vreg.
223    typedef std::vector<unsigned> VRAllowed;
224    VRAllowed vrAllowed;
225    ArrayRef<uint16_t> rawOrder = trc->getRawAllocationOrder(*mf);
226    for (unsigned i = 0; i != rawOrder.size(); ++i) {
227      unsigned preg = rawOrder[i];
228      if (mri->isReserved(preg))
229        continue;
230
231      // vregLI crosses a regmask operand that clobbers preg.
232      if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
233        continue;
234
235      // vregLI overlaps fixed regunit interference.
236      bool Interference = false;
237      for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
238        if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
239          Interference = true;
240          break;
241        }
242      }
243      if (Interference)
244        continue;
245
246      // preg is usable for this virtual register.
247      vrAllowed.push_back(preg);
248    }
249
250    // Construct the node.
251    PBQP::Graph::NodeItr node =
252      g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
253
254    // Record the mapping and allowed set in the problem.
255    p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
256
257    PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
258        vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
259
260    addSpillCosts(g.getNodeCosts(node), spillCost);
261  }
262
263  for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
264         vr1Itr != vrEnd; ++vr1Itr) {
265    unsigned vr1 = *vr1Itr;
266    const LiveInterval &l1 = lis->getInterval(vr1);
267    const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
268
269    for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
270         vr2Itr != vrEnd; ++vr2Itr) {
271      unsigned vr2 = *vr2Itr;
272      const LiveInterval &l2 = lis->getInterval(vr2);
273      const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
274
275      assert(!l2.empty() && "Empty interval in vreg set?");
276      if (l1.overlaps(l2)) {
277        PBQP::Graph::EdgeItr edge =
278          g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
279                    PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
280
281        addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
282      }
283    }
284  }
285
286  return p;
287}
288
289void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
290                                PBQP::PBQPNum spillCost) {
291  costVec[0] = spillCost;
292}
293
294void PBQPBuilder::addInterferenceCosts(
295                                    PBQP::Matrix &costMat,
296                                    const PBQPRAProblem::AllowedSet &vr1Allowed,
297                                    const PBQPRAProblem::AllowedSet &vr2Allowed,
298                                    const TargetRegisterInfo *tri) {
299  assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
300  assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
301
302  for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
303    unsigned preg1 = vr1Allowed[i];
304
305    for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
306      unsigned preg2 = vr2Allowed[j];
307
308      if (tri->regsOverlap(preg1, preg2)) {
309        costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
310      }
311    }
312  }
313}
314
315std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
316                                                MachineFunction *mf,
317                                                const LiveIntervals *lis,
318                                                const MachineLoopInfo *loopInfo,
319                                                const RegSet &vregs) {
320
321  std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
322  PBQP::Graph &g = p->getGraph();
323
324  const TargetMachine &tm = mf->getTarget();
325  CoalescerPair cp(*tm.getRegisterInfo());
326
327  // Scan the machine function and add a coalescing cost whenever CoalescerPair
328  // gives the Ok.
329  for (MachineFunction::const_iterator mbbItr = mf->begin(),
330                                       mbbEnd = mf->end();
331       mbbItr != mbbEnd; ++mbbItr) {
332    const MachineBasicBlock *mbb = &*mbbItr;
333
334    for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
335                                           miEnd = mbb->end();
336         miItr != miEnd; ++miItr) {
337      const MachineInstr *mi = &*miItr;
338
339      if (!cp.setRegisters(mi)) {
340        continue; // Not coalescable.
341      }
342
343      if (cp.getSrcReg() == cp.getDstReg()) {
344        continue; // Already coalesced.
345      }
346
347      unsigned dst = cp.getDstReg(),
348               src = cp.getSrcReg();
349
350      const float copyFactor = 0.5; // Cost of copy relative to load. Current
351      // value plucked randomly out of the air.
352
353      PBQP::PBQPNum cBenefit =
354        copyFactor * LiveIntervals::getSpillWeight(false, true,
355                                                   loopInfo->getLoopDepth(mbb));
356
357      if (cp.isPhys()) {
358        if (!mf->getRegInfo().isAllocatable(dst)) {
359          continue;
360        }
361
362        const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
363        unsigned pregOpt = 0;
364        while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
365          ++pregOpt;
366        }
367        if (pregOpt < allowed.size()) {
368          ++pregOpt; // +1 to account for spill option.
369          PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
370          addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
371        }
372      } else {
373        const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
374        const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
375        PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
376        PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
377        PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
378        if (edge == g.edgesEnd()) {
379          edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
380                                                      allowed2->size() + 1,
381                                                      0));
382        } else {
383          if (g.getEdgeNode1(edge) == node2) {
384            std::swap(node1, node2);
385            std::swap(allowed1, allowed2);
386          }
387        }
388
389        addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
390                           cBenefit);
391      }
392    }
393  }
394
395  return p;
396}
397
398void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
399                                                   unsigned pregOption,
400                                                   PBQP::PBQPNum benefit) {
401  costVec[pregOption] += -benefit;
402}
403
404void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
405                                    PBQP::Matrix &costMat,
406                                    const PBQPRAProblem::AllowedSet &vr1Allowed,
407                                    const PBQPRAProblem::AllowedSet &vr2Allowed,
408                                    PBQP::PBQPNum benefit) {
409
410  assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
411  assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
412
413  for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
414    unsigned preg1 = vr1Allowed[i];
415    for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
416      unsigned preg2 = vr2Allowed[j];
417
418      if (preg1 == preg2) {
419        costMat[i + 1][j + 1] += -benefit;
420      }
421    }
422  }
423}
424
425
426void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
427  au.setPreservesCFG();
428  au.addRequired<AliasAnalysis>();
429  au.addPreserved<AliasAnalysis>();
430  au.addRequired<SlotIndexes>();
431  au.addPreserved<SlotIndexes>();
432  au.addRequired<LiveIntervals>();
433  //au.addRequiredID(SplitCriticalEdgesID);
434  if (customPassID)
435    au.addRequiredID(*customPassID);
436  au.addRequired<CalculateSpillWeights>();
437  au.addRequired<LiveStacks>();
438  au.addPreserved<LiveStacks>();
439  au.addRequired<MachineDominatorTree>();
440  au.addPreserved<MachineDominatorTree>();
441  au.addRequired<MachineLoopInfo>();
442  au.addPreserved<MachineLoopInfo>();
443  au.addRequired<VirtRegMap>();
444  MachineFunctionPass::getAnalysisUsage(au);
445}
446
447void RegAllocPBQP::findVRegIntervalsToAlloc() {
448
449  // Iterate over all live ranges.
450  for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
451    unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
452    if (mri->reg_nodbg_empty(Reg))
453      continue;
454    LiveInterval *li = &lis->getInterval(Reg);
455
456    // If this live interval is non-empty we will use pbqp to allocate it.
457    // Empty intervals we allocate in a simple post-processing stage in
458    // finalizeAlloc.
459    if (!li->empty()) {
460      vregsToAlloc.insert(li->reg);
461    } else {
462      emptyIntervalVRegs.insert(li->reg);
463    }
464  }
465}
466
467bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
468                                     const PBQP::Solution &solution) {
469  // Set to true if we have any spills
470  bool anotherRoundNeeded = false;
471
472  // Clear the existing allocation.
473  vrm->clearAllVirt();
474
475  const PBQP::Graph &g = problem.getGraph();
476  // Iterate over the nodes mapping the PBQP solution to a register
477  // assignment.
478  for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
479                                 nodeEnd = g.nodesEnd();
480       node != nodeEnd; ++node) {
481    unsigned vreg = problem.getVRegForNode(node);
482    unsigned alloc = solution.getSelection(node);
483
484    if (problem.isPRegOption(vreg, alloc)) {
485      unsigned preg = problem.getPRegForOption(vreg, alloc);
486      DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
487            << tri->getName(preg) << "\n");
488      assert(preg != 0 && "Invalid preg selected.");
489      vrm->assignVirt2Phys(vreg, preg);
490    } else if (problem.isSpillOption(vreg, alloc)) {
491      vregsToAlloc.erase(vreg);
492      SmallVector<LiveInterval*, 8> newSpills;
493      LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
494      spiller->spill(LRE);
495
496      DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
497                   << LRE.getParent().weight << ", New vregs: ");
498
499      // Copy any newly inserted live intervals into the list of regs to
500      // allocate.
501      for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
502           itr != end; ++itr) {
503        assert(!(*itr)->empty() && "Empty spill range.");
504        DEBUG(dbgs() << PrintReg((*itr)->reg, tri) << " ");
505        vregsToAlloc.insert((*itr)->reg);
506      }
507
508      DEBUG(dbgs() << ")\n");
509
510      // We need another round if spill intervals were added.
511      anotherRoundNeeded |= !LRE.empty();
512    } else {
513      llvm_unreachable("Unknown allocation option.");
514    }
515  }
516
517  return !anotherRoundNeeded;
518}
519
520
521void RegAllocPBQP::finalizeAlloc() const {
522  // First allocate registers for the empty intervals.
523  for (RegSet::const_iterator
524         itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
525         itr != end; ++itr) {
526    LiveInterval *li = &lis->getInterval(*itr);
527
528    unsigned physReg = vrm->getRegAllocPref(li->reg);
529
530    if (physReg == 0) {
531      const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
532      physReg = liRC->getRawAllocationOrder(*mf).front();
533    }
534
535    vrm->assignVirt2Phys(li->reg, physReg);
536  }
537}
538
539bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
540
541  mf = &MF;
542  tm = &mf->getTarget();
543  tri = tm->getRegisterInfo();
544  tii = tm->getInstrInfo();
545  mri = &mf->getRegInfo();
546
547  lis = &getAnalysis<LiveIntervals>();
548  lss = &getAnalysis<LiveStacks>();
549  loopInfo = &getAnalysis<MachineLoopInfo>();
550
551  vrm = &getAnalysis<VirtRegMap>();
552  spiller.reset(createInlineSpiller(*this, MF, *vrm));
553
554  mri->freezeReservedRegs(MF);
555
556  DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
557
558  // Allocator main loop:
559  //
560  // * Map current regalloc problem to a PBQP problem
561  // * Solve the PBQP problem
562  // * Map the solution back to a register allocation
563  // * Spill if necessary
564  //
565  // This process is continued till no more spills are generated.
566
567  // Find the vreg intervals in need of allocation.
568  findVRegIntervalsToAlloc();
569
570#ifndef NDEBUG
571  const Function* func = mf->getFunction();
572  std::string fqn =
573    func->getParent()->getModuleIdentifier() + "." +
574    func->getName().str();
575#endif
576
577  // If there are non-empty intervals allocate them using pbqp.
578  if (!vregsToAlloc.empty()) {
579
580    bool pbqpAllocComplete = false;
581    unsigned round = 0;
582
583    while (!pbqpAllocComplete) {
584      DEBUG(dbgs() << "  PBQP Regalloc round " << round << ":\n");
585
586      std::auto_ptr<PBQPRAProblem> problem =
587        builder->build(mf, lis, loopInfo, vregsToAlloc);
588
589#ifndef NDEBUG
590      if (pbqpDumpGraphs) {
591        std::ostringstream rs;
592        rs << round;
593        std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
594        std::string tmp;
595        raw_fd_ostream os(graphFileName.c_str(), tmp);
596        DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
597              << graphFileName << "\"\n");
598        problem->getGraph().dump(os);
599      }
600#endif
601
602      PBQP::Solution solution =
603        PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
604          problem->getGraph());
605
606      pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
607
608      ++round;
609    }
610  }
611
612  // Finalise allocation, allocate empty ranges.
613  finalizeAlloc();
614  vregsToAlloc.clear();
615  emptyIntervalVRegs.clear();
616
617  DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
618
619  return true;
620}
621
622FunctionPass* llvm::createPBQPRegisterAllocator(
623                                           std::auto_ptr<PBQPBuilder> builder,
624                                           char *customPassID) {
625  return new RegAllocPBQP(builder, customPassID);
626}
627
628FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
629  if (pbqpCoalescing) {
630    return createPBQPRegisterAllocator(
631             std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
632  } // else
633  return createPBQPRegisterAllocator(
634           std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
635}
636
637#undef DEBUG_TYPE
638