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