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