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