7c35ceb1f561f6a0f270c2c9719b7bf5e6039afa
[oota-llvm.git] / lib / CodeGen / RegAllocGreedy.cpp
1 //===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
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 defines the RAGreedy function pass for register allocation in
11 // optimized builds.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "regalloc"
16 #include "AllocationOrder.h"
17 #include "LiveIntervalUnion.h"
18 #include "LiveRangeEdit.h"
19 #include "RegAllocBase.h"
20 #include "Spiller.h"
21 #include "SpillPlacement.h"
22 #include "SplitKit.h"
23 #include "VirtRegMap.h"
24 #include "VirtRegRewriter.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Function.h"
28 #include "llvm/PassAnalysisSupport.h"
29 #include "llvm/CodeGen/CalcSpillWeights.h"
30 #include "llvm/CodeGen/EdgeBundles.h"
31 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
32 #include "llvm/CodeGen/LiveStackAnalysis.h"
33 #include "llvm/CodeGen/MachineDominators.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineLoopRanges.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/Passes.h"
39 #include "llvm/CodeGen/RegAllocRegistry.h"
40 #include "llvm/CodeGen/RegisterCoalescer.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Support/Timer.h"
46
47 using namespace llvm;
48
49 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
50 STATISTIC(NumLocalSplits,  "Number of split local live ranges");
51 STATISTIC(NumReassigned,   "Number of interferences reassigned");
52 STATISTIC(NumEvicted,      "Number of interferences evicted");
53
54 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
55                                        createGreedyRegisterAllocator);
56
57 namespace {
58 class RAGreedy : public MachineFunctionPass, public RegAllocBase {
59   // context
60   MachineFunction *MF;
61   BitVector ReservedRegs;
62
63   // analyses
64   SlotIndexes *Indexes;
65   LiveStacks *LS;
66   MachineDominatorTree *DomTree;
67   MachineLoopInfo *Loops;
68   MachineLoopRanges *LoopRanges;
69   EdgeBundles *Bundles;
70   SpillPlacement *SpillPlacer;
71
72   // state
73   std::auto_ptr<Spiller> SpillerInstance;
74   std::auto_ptr<SplitAnalysis> SA;
75
76   // splitting state.
77
78   /// All basic blocks where the current register is live.
79   SmallVector<SpillPlacement::BlockConstraint, 8> SpillConstraints;
80
81   /// For every instruction in SA->UseSlots, store the previous non-copy
82   /// instruction.
83   SmallVector<SlotIndex, 8> PrevSlot;
84
85 public:
86   RAGreedy();
87
88   /// Return the pass name.
89   virtual const char* getPassName() const {
90     return "Greedy Register Allocator";
91   }
92
93   /// RAGreedy analysis usage.
94   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
95
96   virtual void releaseMemory();
97
98   virtual Spiller &spiller() { return *SpillerInstance; }
99
100   virtual float getPriority(LiveInterval *LI);
101
102   virtual unsigned selectOrSplit(LiveInterval&,
103                                  SmallVectorImpl<LiveInterval*>&);
104
105   /// Perform register allocation.
106   virtual bool runOnMachineFunction(MachineFunction &mf);
107
108   static char ID;
109
110 private:
111   bool checkUncachedInterference(LiveInterval&, unsigned);
112   LiveInterval *getSingleInterference(LiveInterval&, unsigned);
113   bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
114   float calcInterferenceWeight(LiveInterval&, unsigned);
115   float calcInterferenceInfo(LiveInterval&, unsigned);
116   float calcGlobalSplitCost(const BitVector&);
117   void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
118                          SmallVectorImpl<LiveInterval*>&);
119   void calcGapWeights(unsigned, SmallVectorImpl<float>&);
120   SlotIndex getPrevMappedIndex(const MachineInstr*);
121   void calcPrevSlots();
122   unsigned nextSplitPoint(unsigned);
123
124   unsigned tryReassignOrEvict(LiveInterval&, AllocationOrder&,
125                               SmallVectorImpl<LiveInterval*>&);
126   unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
127                           SmallVectorImpl<LiveInterval*>&);
128   unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
129     SmallVectorImpl<LiveInterval*>&);
130   unsigned trySplit(LiveInterval&, AllocationOrder&,
131                     SmallVectorImpl<LiveInterval*>&);
132   unsigned trySpillInterferences(LiveInterval&, AllocationOrder&,
133                                  SmallVectorImpl<LiveInterval*>&);
134 };
135 } // end anonymous namespace
136
137 char RAGreedy::ID = 0;
138
139 FunctionPass* llvm::createGreedyRegisterAllocator() {
140   return new RAGreedy();
141 }
142
143 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
144   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
145   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
146   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
147   initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
148   initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
149   initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
150   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
151   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
152   initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
153   initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
154   initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
155   initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
156   initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
157 }
158
159 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
160   AU.setPreservesCFG();
161   AU.addRequired<AliasAnalysis>();
162   AU.addPreserved<AliasAnalysis>();
163   AU.addRequired<LiveIntervals>();
164   AU.addRequired<SlotIndexes>();
165   AU.addPreserved<SlotIndexes>();
166   if (StrongPHIElim)
167     AU.addRequiredID(StrongPHIEliminationID);
168   AU.addRequiredTransitive<RegisterCoalescer>();
169   AU.addRequired<CalculateSpillWeights>();
170   AU.addRequired<LiveStacks>();
171   AU.addPreserved<LiveStacks>();
172   AU.addRequired<MachineDominatorTree>();
173   AU.addPreserved<MachineDominatorTree>();
174   AU.addRequired<MachineLoopInfo>();
175   AU.addPreserved<MachineLoopInfo>();
176   AU.addRequired<MachineLoopRanges>();
177   AU.addPreserved<MachineLoopRanges>();
178   AU.addRequired<VirtRegMap>();
179   AU.addPreserved<VirtRegMap>();
180   AU.addRequired<EdgeBundles>();
181   AU.addRequired<SpillPlacement>();
182   MachineFunctionPass::getAnalysisUsage(AU);
183 }
184
185 void RAGreedy::releaseMemory() {
186   SpillerInstance.reset(0);
187   RegAllocBase::releaseMemory();
188 }
189
190 float RAGreedy::getPriority(LiveInterval *LI) {
191   float Priority = LI->weight;
192
193   // Prioritize hinted registers so they are allocated first.
194   std::pair<unsigned, unsigned> Hint;
195   if (Hint.first || Hint.second) {
196     // The hint can be target specific, a virtual register, or a physreg.
197     Priority *= 2;
198
199     // Prefer physreg hints above anything else.
200     if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
201       Priority *= 2;
202   }
203   return Priority;
204 }
205
206
207 //===----------------------------------------------------------------------===//
208 //                         Register Reassignment
209 //===----------------------------------------------------------------------===//
210
211 // Check interference without using the cache.
212 bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
213                                          unsigned PhysReg) {
214   for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
215     LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
216     if (subQ.checkInterference())
217       return true;
218   }
219   return false;
220 }
221
222 /// getSingleInterference - Return the single interfering virtual register
223 /// assigned to PhysReg. Return 0 if more than one virtual register is
224 /// interfering.
225 LiveInterval *RAGreedy::getSingleInterference(LiveInterval &VirtReg,
226                                               unsigned PhysReg) {
227   // Check physreg and aliases.
228   LiveInterval *Interference = 0;
229   for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
230     LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
231     if (Q.checkInterference()) {
232       if (Interference)
233         return 0;
234       Q.collectInterferingVRegs(1);
235       if (!Q.seenAllInterferences())
236         return 0;
237       Interference = Q.interferingVRegs().front();
238     }
239   }
240   return Interference;
241 }
242
243 // Attempt to reassign this virtual register to a different physical register.
244 //
245 // FIXME: we are not yet caching these "second-level" interferences discovered
246 // in the sub-queries. These interferences can change with each call to
247 // selectOrSplit. However, we could implement a "may-interfere" cache that
248 // could be conservatively dirtied when we reassign or split.
249 //
250 // FIXME: This may result in a lot of alias queries. We could summarize alias
251 // live intervals in their parent register's live union, but it's messy.
252 bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
253                             unsigned WantedPhysReg) {
254   assert(TargetRegisterInfo::isVirtualRegister(InterferingVReg.reg) &&
255          "Can only reassign virtual registers");
256   assert(TRI->regsOverlap(WantedPhysReg, VRM->getPhys(InterferingVReg.reg)) &&
257          "inconsistent phys reg assigment");
258
259   AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
260   while (unsigned PhysReg = Order.next()) {
261     // Don't reassign to a WantedPhysReg alias.
262     if (TRI->regsOverlap(PhysReg, WantedPhysReg))
263       continue;
264
265     if (checkUncachedInterference(InterferingVReg, PhysReg))
266       continue;
267
268     // Reassign the interfering virtual reg to this physical reg.
269     unsigned OldAssign = VRM->getPhys(InterferingVReg.reg);
270     DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
271           TRI->getName(OldAssign) << " to " << TRI->getName(PhysReg) << '\n');
272     unassign(InterferingVReg, OldAssign);
273     assign(InterferingVReg, PhysReg);
274     ++NumReassigned;
275     return true;
276   }
277   return false;
278 }
279
280 /// tryReassignOrEvict - Try to reassign a single interferences to a different
281 /// physreg, or evict a single interference with a lower spill weight.
282 /// @param  VirtReg Currently unassigned virtual register.
283 /// @param  Order   Physregs to try.
284 /// @return         Physreg to assign VirtReg, or 0.
285 unsigned RAGreedy::tryReassignOrEvict(LiveInterval &VirtReg,
286                                       AllocationOrder &Order,
287                                       SmallVectorImpl<LiveInterval*> &NewVRegs){
288   NamedRegionTimer T("Reassign", TimerGroupName, TimePassesIsEnabled);
289
290   // Keep track of the lightest single interference seen so far.
291   float BestWeight = VirtReg.weight;
292   LiveInterval *BestVirt = 0;
293   unsigned BestPhys = 0;
294
295   Order.rewind();
296   while (unsigned PhysReg = Order.next()) {
297     LiveInterval *InterferingVReg = getSingleInterference(VirtReg, PhysReg);
298     if (!InterferingVReg)
299       continue;
300     if (TargetRegisterInfo::isPhysicalRegister(InterferingVReg->reg))
301       continue;
302     if (reassignVReg(*InterferingVReg, PhysReg))
303       return PhysReg;
304
305     // Cannot reassign, is this an eviction candidate?
306     if (InterferingVReg->weight < BestWeight) {
307       BestVirt = InterferingVReg;
308       BestPhys = PhysReg;
309       BestWeight = InterferingVReg->weight;
310     }
311   }
312
313   // Nothing reassigned, can we evict a lighter single interference?
314   if (BestVirt) {
315     DEBUG(dbgs() << "evicting lighter " << *BestVirt << '\n');
316     unassign(*BestVirt, VRM->getPhys(BestVirt->reg));
317     ++NumEvicted;
318     NewVRegs.push_back(BestVirt);
319     return BestPhys;
320   }
321
322   return 0;
323 }
324
325
326 //===----------------------------------------------------------------------===//
327 //                              Region Splitting
328 //===----------------------------------------------------------------------===//
329
330 /// calcInterferenceInfo - Compute per-block outgoing and ingoing constraints
331 /// when considering interference from PhysReg. Also compute an optimistic local
332 /// cost of this interference pattern.
333 ///
334 /// The final cost of a split is the local cost + global cost of preferences
335 /// broken by SpillPlacement.
336 ///
337 float RAGreedy::calcInterferenceInfo(LiveInterval &VirtReg, unsigned PhysReg) {
338   // Reset interference dependent info.
339   SpillConstraints.resize(SA->LiveBlocks.size());
340   for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
341     SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
342     SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
343     BC.Number = BI.MBB->getNumber();
344     BC.Entry = (BI.Uses && BI.LiveIn) ?
345       SpillPlacement::PrefReg : SpillPlacement::DontCare;
346     BC.Exit = (BI.Uses && BI.LiveOut) ?
347       SpillPlacement::PrefReg : SpillPlacement::DontCare;
348     BI.OverlapEntry = BI.OverlapExit = false;
349   }
350
351   // Add interference info from each PhysReg alias.
352   for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
353     if (!query(VirtReg, *AI).checkInterference())
354       continue;
355     LiveIntervalUnion::SegmentIter IntI =
356       PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
357     if (!IntI.valid())
358       continue;
359
360     // Determine which blocks have interference live in or after the last split
361     // point.
362     for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
363       SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
364       SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
365       SlotIndex Start, Stop;
366       tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
367
368       // Skip interference-free blocks.
369       if (IntI.start() >= Stop)
370         continue;
371
372       // Is the interference live-in?
373       if (BI.LiveIn) {
374         IntI.advanceTo(Start);
375         if (!IntI.valid())
376           break;
377         if (IntI.start() <= Start)
378           BC.Entry = SpillPlacement::MustSpill;
379       }
380
381       // Is the interference overlapping the last split point?
382       if (BI.LiveOut) {
383         if (IntI.stop() < BI.LastSplitPoint)
384           IntI.advanceTo(BI.LastSplitPoint.getPrevSlot());
385         if (!IntI.valid())
386           break;
387         if (IntI.start() < Stop)
388           BC.Exit = SpillPlacement::MustSpill;
389       }
390     }
391
392     // Rewind iterator and check other interferences.
393     IntI.find(VirtReg.beginIndex());
394     for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
395       SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
396       SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
397       SlotIndex Start, Stop;
398       tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
399
400       // Skip interference-free blocks.
401       if (IntI.start() >= Stop)
402         continue;
403
404       // Handle transparent blocks with interference separately.
405       // Transparent blocks never incur any fixed cost.
406       if (BI.LiveThrough && !BI.Uses) {
407         IntI.advanceTo(Start);
408         if (!IntI.valid())
409           break;
410         if (IntI.start() >= Stop)
411           continue;
412
413         if (BC.Entry != SpillPlacement::MustSpill)
414           BC.Entry = SpillPlacement::PrefSpill;
415         if (BC.Exit != SpillPlacement::MustSpill)
416           BC.Exit = SpillPlacement::PrefSpill;
417         continue;
418       }
419
420       // Now we only have blocks with uses left.
421       // Check if the interference overlaps the uses.
422       assert(BI.Uses && "Non-transparent block without any uses");
423
424       // Check interference on entry.
425       if (BI.LiveIn && BC.Entry != SpillPlacement::MustSpill) {
426         IntI.advanceTo(Start);
427         if (!IntI.valid())
428           break;
429         // Not live in, but before the first use.
430         if (IntI.start() < BI.FirstUse)
431           BC.Entry = SpillPlacement::PrefSpill;
432       }
433
434       // Does interference overlap the uses in the entry segment
435       // [FirstUse;Kill)?
436       if (BI.LiveIn && !BI.OverlapEntry) {
437         IntI.advanceTo(BI.FirstUse);
438         if (!IntI.valid())
439           break;
440         // A live-through interval has no kill.
441         // Check [FirstUse;LastUse) instead.
442         if (IntI.start() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
443           BI.OverlapEntry = true;
444       }
445
446       // Does interference overlap the uses in the exit segment [Def;LastUse)?
447       if (BI.LiveOut && !BI.LiveThrough && !BI.OverlapExit) {
448         IntI.advanceTo(BI.Def);
449         if (!IntI.valid())
450           break;
451         if (IntI.start() < BI.LastUse)
452           BI.OverlapExit = true;
453       }
454
455       // Check interference on exit.
456       if (BI.LiveOut && BC.Exit != SpillPlacement::MustSpill) {
457         // Check interference between LastUse and Stop.
458         if (BC.Exit != SpillPlacement::PrefSpill) {
459           IntI.advanceTo(BI.LastUse);
460           if (!IntI.valid())
461             break;
462           if (IntI.start() < Stop)
463             BC.Exit = SpillPlacement::PrefSpill;
464         }
465       }
466     }
467   }
468
469   // Accumulate a local cost of this interference pattern.
470   float LocalCost = 0;
471   for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
472     SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
473     if (!BI.Uses)
474       continue;
475     SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
476     unsigned Inserts = 0;
477
478     // Do we need spill code for the entry segment?
479     if (BI.LiveIn)
480       Inserts += BI.OverlapEntry || BC.Entry != SpillPlacement::PrefReg;
481
482     // For the exit segment?
483     if (BI.LiveOut)
484       Inserts += BI.OverlapExit || BC.Exit != SpillPlacement::PrefReg;
485
486     // The local cost of spill code in this block is the block frequency times
487     // the number of spill instructions inserted.
488     if (Inserts)
489       LocalCost += Inserts * SpillPlacer->getBlockFrequency(BI.MBB);
490   }
491   DEBUG(dbgs() << "Local cost of " << PrintReg(PhysReg, TRI) << " = "
492                << LocalCost << '\n');
493   return LocalCost;
494 }
495
496 /// calcGlobalSplitCost - Return the global split cost of following the split
497 /// pattern in LiveBundles. This cost should be added to the local cost of the
498 /// interference pattern in SpillConstraints.
499 ///
500 float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
501   float GlobalCost = 0;
502   for (unsigned i = 0, e = SpillConstraints.size(); i != e; ++i) {
503     SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
504     unsigned Inserts = 0;
505     // Broken entry preference?
506     Inserts += LiveBundles[Bundles->getBundle(BC.Number, 0)] !=
507                  (BC.Entry == SpillPlacement::PrefReg);
508     // Broken exit preference?
509     Inserts += LiveBundles[Bundles->getBundle(BC.Number, 1)] !=
510                  (BC.Exit == SpillPlacement::PrefReg);
511     if (Inserts)
512       GlobalCost +=
513         Inserts * SpillPlacer->getBlockFrequency(SA->LiveBlocks[i].MBB);
514   }
515   DEBUG(dbgs() << "Global cost = " << GlobalCost << '\n');
516   return GlobalCost;
517 }
518
519 /// splitAroundRegion - Split VirtReg around the region determined by
520 /// LiveBundles. Make an effort to avoid interference from PhysReg.
521 ///
522 /// The 'register' interval is going to contain as many uses as possible while
523 /// avoiding interference. The 'stack' interval is the complement constructed by
524 /// SplitEditor. It will contain the rest.
525 ///
526 void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
527                                  const BitVector &LiveBundles,
528                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
529   DEBUG({
530     dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
531            << " with bundles";
532     for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
533       dbgs() << " EB#" << i;
534     dbgs() << ".\n";
535   });
536
537   // First compute interference ranges in the live blocks.
538   typedef std::pair<SlotIndex, SlotIndex> IndexPair;
539   SmallVector<IndexPair, 8> InterferenceRanges;
540   InterferenceRanges.resize(SA->LiveBlocks.size());
541   for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
542     if (!query(VirtReg, *AI).checkInterference())
543       continue;
544     LiveIntervalUnion::SegmentIter IntI =
545       PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
546     if (!IntI.valid())
547       continue;
548     for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
549       const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
550       IndexPair &IP = InterferenceRanges[i];
551       SlotIndex Start, Stop;
552       tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
553       // Skip interference-free blocks.
554       if (IntI.start() >= Stop)
555         continue;
556
557       // First interference in block.
558       if (BI.LiveIn) {
559         IntI.advanceTo(Start);
560         if (!IntI.valid())
561           break;
562         if (IntI.start() >= Stop)
563           continue;
564         if (!IP.first.isValid() || IntI.start() < IP.first)
565           IP.first = IntI.start();
566       }
567
568       // Last interference in block.
569       if (BI.LiveOut) {
570         IntI.advanceTo(Stop);
571         if (!IntI.valid() || IntI.start() >= Stop)
572           --IntI;
573         if (IntI.stop() <= Start)
574           continue;
575         if (!IP.second.isValid() || IntI.stop() > IP.second)
576           IP.second = IntI.stop();
577       }
578     }
579   }
580
581   SmallVector<LiveInterval*, 4> SpillRegs;
582   LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
583   SplitEditor SE(*SA, *LIS, *VRM, *DomTree, LREdit);
584
585   // Create the main cross-block interval.
586   SE.openIntv();
587
588   // First add all defs that are live out of a block.
589   for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
590     SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
591     bool RegIn  = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
592     bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
593
594     // Should the register be live out?
595     if (!BI.LiveOut || !RegOut)
596       continue;
597
598     IndexPair &IP = InterferenceRanges[i];
599     SlotIndex Start, Stop;
600     tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
601
602     DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
603                  << Bundles->getBundle(BI.MBB->getNumber(), 1)
604                  << " intf [" << IP.first << ';' << IP.second << ')');
605
606     // The interference interval should either be invalid or overlap MBB.
607     assert((!IP.first.isValid() || IP.first < Stop) && "Bad interference");
608     assert((!IP.second.isValid() || IP.second > Start) && "Bad interference");
609
610     // Check interference leaving the block.
611     if (!IP.second.isValid()) {
612       // Block is interference-free.
613       DEBUG(dbgs() << ", no interference");
614       if (!BI.Uses) {
615         assert(BI.LiveThrough && "No uses, but not live through block?");
616         // Block is live-through without interference.
617         DEBUG(dbgs() << ", no uses"
618                      << (RegIn ? ", live-through.\n" : ", stack in.\n"));
619         if (!RegIn)
620           SE.enterIntvAtEnd(*BI.MBB);
621         continue;
622       }
623       if (!BI.LiveThrough) {
624         DEBUG(dbgs() << ", not live-through.\n");
625         SE.useIntv(SE.enterIntvBefore(BI.Def), Stop);
626         continue;
627       }
628       if (!RegIn) {
629         // Block is live-through, but entry bundle is on the stack.
630         // Reload just before the first use.
631         DEBUG(dbgs() << ", not live-in, enter before first use.\n");
632         SE.useIntv(SE.enterIntvBefore(BI.FirstUse), Stop);
633         continue;
634       }
635       DEBUG(dbgs() << ", live-through.\n");
636       continue;
637     }
638
639     // Block has interference.
640     DEBUG(dbgs() << ", interference to " << IP.second);
641
642     if (!BI.LiveThrough && IP.second <= BI.Def) {
643       // The interference doesn't reach the outgoing segment.
644       DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
645       SE.useIntv(BI.Def, Stop);
646       continue;
647     }
648
649
650     if (!BI.Uses) {
651       // No uses in block, avoid interference by reloading as late as possible.
652       DEBUG(dbgs() << ", no uses.\n");
653       SlotIndex SegStart = SE.enterIntvAtEnd(*BI.MBB);
654       assert(SegStart >= IP.second && "Couldn't avoid interference");
655       continue;
656     }
657
658     if (IP.second.getBoundaryIndex() < BI.LastUse) {
659       // There are interference-free uses at the end of the block.
660       // Find the first use that can get the live-out register.
661       SmallVectorImpl<SlotIndex>::const_iterator UI =
662         std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
663                          IP.second.getBoundaryIndex());
664       assert(UI != SA->UseSlots.end() && "Couldn't find last use");
665       SlotIndex Use = *UI;
666       assert(Use <= BI.LastUse && "Couldn't find last use");
667       // Only attempt a split befroe the last split point.
668       if (Use.getBaseIndex() <= BI.LastSplitPoint) {
669         DEBUG(dbgs() << ", free use at " << Use << ".\n");
670         SlotIndex SegStart = SE.enterIntvBefore(Use);
671         assert(SegStart >= IP.second && "Couldn't avoid interference");
672         assert(SegStart < BI.LastSplitPoint && "Impossible split point");
673         SE.useIntv(SegStart, Stop);
674         continue;
675       }
676     }
677
678     // Interference is after the last use.
679     DEBUG(dbgs() << " after last use.\n");
680     SlotIndex SegStart = SE.enterIntvAtEnd(*BI.MBB);
681     assert(SegStart >= IP.second && "Couldn't avoid interference");
682   }
683
684   // Now all defs leading to live bundles are handled, do everything else.
685   for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
686     SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
687     bool RegIn  = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
688     bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
689
690     // Is the register live-in?
691     if (!BI.LiveIn || !RegIn)
692       continue;
693
694     // We have an incoming register. Check for interference.
695     IndexPair &IP = InterferenceRanges[i];
696     SlotIndex Start, Stop;
697     tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
698
699     DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
700                  << " -> BB#" << BI.MBB->getNumber());
701
702     // Check interference entering the block.
703     if (!IP.first.isValid()) {
704       // Block is interference-free.
705       DEBUG(dbgs() << ", no interference");
706       if (!BI.Uses) {
707         assert(BI.LiveThrough && "No uses, but not live through block?");
708         // Block is live-through without interference.
709         if (RegOut) {
710           DEBUG(dbgs() << ", no uses, live-through.\n");
711           SE.useIntv(Start, Stop);
712         } else {
713           DEBUG(dbgs() << ", no uses, stack-out.\n");
714           SE.leaveIntvAtTop(*BI.MBB);
715         }
716         continue;
717       }
718       if (!BI.LiveThrough) {
719         DEBUG(dbgs() << ", killed in block.\n");
720         SE.useIntv(Start, SE.leaveIntvAfter(BI.Kill));
721         continue;
722       }
723       if (!RegOut) {
724         // Block is live-through, but exit bundle is on the stack.
725         // Spill immediately after the last use.
726         if (BI.LastUse < BI.LastSplitPoint) {
727           DEBUG(dbgs() << ", uses, stack-out.\n");
728           SE.useIntv(Start, SE.leaveIntvAfter(BI.LastUse));
729           continue;
730         }
731         // The last use is after the last split point, it is probably an
732         // indirect jump.
733         DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
734                      << BI.LastSplitPoint << ", stack-out.\n");
735         SlotIndex SegEnd = SE.leaveIntvBefore(BI.LastSplitPoint);
736         SE.useIntv(Start, SegEnd);
737         // Run a double interval from the split to the last use.
738         // This makes it possible to spill the complement without affecting the
739         // indirect branch.
740         SE.overlapIntv(SegEnd, BI.LastUse);
741         continue;
742       }
743       // Register is live-through.
744       DEBUG(dbgs() << ", uses, live-through.\n");
745       SE.useIntv(Start, Stop);
746       continue;
747     }
748
749     // Block has interference.
750     DEBUG(dbgs() << ", interference from " << IP.first);
751
752     if (!BI.LiveThrough && IP.first >= BI.Kill) {
753       // The interference doesn't reach the outgoing segment.
754       DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
755       SE.useIntv(Start, BI.Kill);
756       continue;
757     }
758
759     if (!BI.Uses) {
760       // No uses in block, avoid interference by spilling as soon as possible.
761       DEBUG(dbgs() << ", no uses.\n");
762       SlotIndex SegEnd = SE.leaveIntvAtTop(*BI.MBB);
763       assert(SegEnd <= IP.first && "Couldn't avoid interference");
764       continue;
765     }
766     if (IP.first.getBaseIndex() > BI.FirstUse) {
767       // There are interference-free uses at the beginning of the block.
768       // Find the last use that can get the register.
769       SmallVectorImpl<SlotIndex>::const_iterator UI =
770         std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
771                          IP.first.getBaseIndex());
772       assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
773       SlotIndex Use = (--UI)->getBoundaryIndex();
774       DEBUG(dbgs() << ", free use at " << *UI << ".\n");
775       SlotIndex SegEnd = SE.leaveIntvAfter(Use);
776       assert(SegEnd <= IP.first && "Couldn't avoid interference");
777       SE.useIntv(Start, SegEnd);
778       continue;
779     }
780
781     // Interference is before the first use.
782     DEBUG(dbgs() << " before first use.\n");
783     SlotIndex SegEnd = SE.leaveIntvAtTop(*BI.MBB);
784     assert(SegEnd <= IP.first && "Couldn't avoid interference");
785   }
786
787   SE.closeIntv();
788
789   // FIXME: Should we be more aggressive about splitting the stack region into
790   // per-block segments? The current approach allows the stack region to
791   // separate into connected components. Some components may be allocatable.
792   SE.finish();
793   ++NumGlobalSplits;
794
795   if (VerifyEnabled) {
796     MF->verify(this, "After splitting live range around region");
797
798 #ifndef NDEBUG
799     // Make sure that at least one of the new intervals can allocate to PhysReg.
800     // That was the whole point of splitting the live range.
801     bool found = false;
802     for (LiveRangeEdit::iterator I = LREdit.begin(), E = LREdit.end(); I != E;
803          ++I)
804       if (!checkUncachedInterference(**I, PhysReg)) {
805         found = true;
806         break;
807       }
808     assert(found && "No allocatable intervals after pointless splitting");
809 #endif
810   }
811 }
812
813 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
814                                   SmallVectorImpl<LiveInterval*> &NewVRegs) {
815   BitVector LiveBundles, BestBundles;
816   float BestCost = 0;
817   unsigned BestReg = 0;
818   Order.rewind();
819   while (unsigned PhysReg = Order.next()) {
820     float Cost = calcInterferenceInfo(VirtReg, PhysReg);
821     if (BestReg && Cost >= BestCost)
822       continue;
823
824     SpillPlacer->placeSpills(SpillConstraints, LiveBundles);
825     // No live bundles, defer to splitSingleBlocks().
826     if (!LiveBundles.any())
827       continue;
828
829     Cost += calcGlobalSplitCost(LiveBundles);
830     if (!BestReg || Cost < BestCost) {
831       BestReg = PhysReg;
832       BestCost = Cost;
833       BestBundles.swap(LiveBundles);
834     }
835   }
836
837   if (!BestReg)
838     return 0;
839
840   splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
841   return 0;
842 }
843
844
845 //===----------------------------------------------------------------------===//
846 //                             Local Splitting
847 //===----------------------------------------------------------------------===//
848
849
850 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
851 /// in order to use PhysReg between two entries in SA->UseSlots.
852 ///
853 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
854 ///
855 void RAGreedy::calcGapWeights(unsigned PhysReg,
856                               SmallVectorImpl<float> &GapWeight) {
857   assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
858   const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
859   const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
860   const unsigned NumGaps = Uses.size()-1;
861
862   // Start and end points for the interference check.
863   SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
864   SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
865
866   GapWeight.assign(NumGaps, 0.0f);
867
868   // Add interference from each overlapping register.
869   for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
870     if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
871            .checkInterference())
872       continue;
873
874     // We know that VirtReg is a continuous interval from FirstUse to LastUse,
875     // so we don't need InterferenceQuery.
876     //
877     // Interference that overlaps an instruction is counted in both gaps
878     // surrounding the instruction. The exception is interference before
879     // StartIdx and after StopIdx.
880     //
881     LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
882     for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
883       // Skip the gaps before IntI.
884       while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
885         if (++Gap == NumGaps)
886           break;
887       if (Gap == NumGaps)
888         break;
889
890       // Update the gaps covered by IntI.
891       const float weight = IntI.value()->weight;
892       for (; Gap != NumGaps; ++Gap) {
893         GapWeight[Gap] = std::max(GapWeight[Gap], weight);
894         if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
895           break;
896       }
897       if (Gap == NumGaps)
898         break;
899     }
900   }
901 }
902
903 /// getPrevMappedIndex - Return the slot index of the last non-copy instruction
904 /// before MI that has a slot index. If MI is the first mapped instruction in
905 /// its block, return the block start index instead.
906 ///
907 SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
908   assert(MI && "Missing MachineInstr");
909   const MachineBasicBlock *MBB = MI->getParent();
910   MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
911   while (I != B)
912     if (!(--I)->isDebugValue() && !I->isCopy())
913       return Indexes->getInstructionIndex(I);
914   return Indexes->getMBBStartIdx(MBB);
915 }
916
917 /// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
918 /// real non-copy instruction for each instruction in SA->UseSlots.
919 ///
920 void RAGreedy::calcPrevSlots() {
921   const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
922   PrevSlot.clear();
923   PrevSlot.reserve(Uses.size());
924   for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
925     const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
926     PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
927   }
928 }
929
930 /// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
931 /// be beneficial to split before UseSlots[i].
932 ///
933 /// 0 is always a valid split point
934 unsigned RAGreedy::nextSplitPoint(unsigned i) {
935   const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
936   const unsigned Size = Uses.size();
937   assert(i != Size && "No split points after the end");
938   // Allow split before i when Uses[i] is not adjacent to the previous use.
939   while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
940     ;
941   return i;
942 }
943
944 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
945 /// basic block.
946 ///
947 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
948                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
949   assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
950   const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
951
952   // Note that it is possible to have an interval that is live-in or live-out
953   // while only covering a single block - A phi-def can use undef values from
954   // predecessors, and the block could be a single-block loop.
955   // We don't bother doing anything clever about such a case, we simply assume
956   // that the interval is continuous from FirstUse to LastUse. We should make
957   // sure that we don't do anything illegal to such an interval, though.
958
959   const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
960   if (Uses.size() <= 2)
961     return 0;
962   const unsigned NumGaps = Uses.size()-1;
963
964   DEBUG({
965     dbgs() << "tryLocalSplit: ";
966     for (unsigned i = 0, e = Uses.size(); i != e; ++i)
967       dbgs() << ' ' << SA->UseSlots[i];
968     dbgs() << '\n';
969   });
970
971   // For every use, find the previous mapped non-copy instruction.
972   // We use this to detect valid split points, and to estimate new interval
973   // sizes.
974   calcPrevSlots();
975
976   unsigned BestBefore = NumGaps;
977   unsigned BestAfter = 0;
978   float BestDiff = 0;
979
980   const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB);
981   SmallVector<float, 8> GapWeight;
982
983   Order.rewind();
984   while (unsigned PhysReg = Order.next()) {
985     // Keep track of the largest spill weight that would need to be evicted in
986     // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
987     calcGapWeights(PhysReg, GapWeight);
988
989     // Try to find the best sequence of gaps to close.
990     // The new spill weight must be larger than any gap interference.
991
992     // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
993     unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
994
995     // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
996     // It is the spill weight that needs to be evicted.
997     float MaxGap = GapWeight[0];
998     for (unsigned i = 1; i != SplitAfter; ++i)
999       MaxGap = std::max(MaxGap, GapWeight[i]);
1000
1001     for (;;) {
1002       // Live before/after split?
1003       const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1004       const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1005
1006       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1007                    << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1008                    << " i=" << MaxGap);
1009
1010       // Stop before the interval gets so big we wouldn't be making progress.
1011       if (!LiveBefore && !LiveAfter) {
1012         DEBUG(dbgs() << " all\n");
1013         break;
1014       }
1015       // Should the interval be extended or shrunk?
1016       bool Shrink = true;
1017       if (MaxGap < HUGE_VALF) {
1018         // Estimate the new spill weight.
1019         //
1020         // Each instruction reads and writes the register, except the first
1021         // instr doesn't read when !FirstLive, and the last instr doesn't write
1022         // when !LastLive.
1023         //
1024         // We will be inserting copies before and after, so the total number of
1025         // reads and writes is 2 * EstUses.
1026         //
1027         const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1028                                  2*(LiveBefore + LiveAfter);
1029
1030         // Try to guess the size of the new interval. This should be trivial,
1031         // but the slot index of an inserted copy can be a lot smaller than the
1032         // instruction it is inserted before if there are many dead indexes
1033         // between them.
1034         //
1035         // We measure the distance from the instruction before SplitBefore to
1036         // get a conservative estimate.
1037         //
1038         // The final distance can still be different if inserting copies
1039         // triggers a slot index renumbering.
1040         //
1041         const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1042                               PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1043         // Would this split be possible to allocate?
1044         // Never allocate all gaps, we wouldn't be making progress.
1045         float Diff = EstWeight - MaxGap;
1046         DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1047         if (Diff > 0) {
1048           Shrink = false;
1049           if (Diff > BestDiff) {
1050             DEBUG(dbgs() << " (best)");
1051             BestDiff = Diff;
1052             BestBefore = SplitBefore;
1053             BestAfter = SplitAfter;
1054           }
1055         }
1056       }
1057
1058       // Try to shrink.
1059       if (Shrink) {
1060         SplitBefore = nextSplitPoint(SplitBefore);
1061         if (SplitBefore < SplitAfter) {
1062           DEBUG(dbgs() << " shrink\n");
1063           // Recompute the max when necessary.
1064           if (GapWeight[SplitBefore - 1] >= MaxGap) {
1065             MaxGap = GapWeight[SplitBefore];
1066             for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1067               MaxGap = std::max(MaxGap, GapWeight[i]);
1068           }
1069           continue;
1070         }
1071         MaxGap = 0;
1072       }
1073
1074       // Try to extend the interval.
1075       if (SplitAfter >= NumGaps) {
1076         DEBUG(dbgs() << " end\n");
1077         break;
1078       }
1079
1080       DEBUG(dbgs() << " extend\n");
1081       for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1082            SplitAfter != e; ++SplitAfter)
1083         MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1084           continue;
1085     }
1086   }
1087
1088   // Didn't find any candidates?
1089   if (BestBefore == NumGaps)
1090     return 0;
1091
1092   DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1093                << '-' << Uses[BestAfter] << ", " << BestDiff
1094                << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1095
1096   SmallVector<LiveInterval*, 4> SpillRegs;
1097   LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
1098   SplitEditor SE(*SA, *LIS, *VRM, *DomTree, LREdit);
1099
1100   SE.openIntv();
1101   SlotIndex SegStart = SE.enterIntvBefore(Uses[BestBefore]);
1102   SlotIndex SegStop  = SE.leaveIntvAfter(Uses[BestAfter]);
1103   SE.useIntv(SegStart, SegStop);
1104   SE.closeIntv();
1105   SE.finish();
1106   ++NumLocalSplits;
1107
1108   return 0;
1109 }
1110
1111 //===----------------------------------------------------------------------===//
1112 //                          Live Range Splitting
1113 //===----------------------------------------------------------------------===//
1114
1115 /// trySplit - Try to split VirtReg or one of its interferences, making it
1116 /// assignable.
1117 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1118 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1119                             SmallVectorImpl<LiveInterval*>&NewVRegs) {
1120   NamedRegionTimer T("Splitter", TimerGroupName, TimePassesIsEnabled);
1121   SA->analyze(&VirtReg);
1122
1123   // Local intervals are handled separately.
1124   if (LIS->intervalIsInOneMBB(VirtReg))
1125     return tryLocalSplit(VirtReg, Order, NewVRegs);
1126
1127   // First try to split around a region spanning multiple blocks.
1128   unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1129   if (PhysReg || !NewVRegs.empty())
1130     return PhysReg;
1131
1132   // Then isolate blocks with multiple uses.
1133   SplitAnalysis::BlockPtrSet Blocks;
1134   if (SA->getMultiUseBlocks(Blocks)) {
1135     SmallVector<LiveInterval*, 4> SpillRegs;
1136     LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
1137     SplitEditor(*SA, *LIS, *VRM, *DomTree, LREdit).splitSingleBlocks(Blocks);
1138     if (VerifyEnabled)
1139       MF->verify(this, "After splitting live range around basic blocks");
1140   }
1141
1142   // Don't assign any physregs.
1143   return 0;
1144 }
1145
1146
1147 //===----------------------------------------------------------------------===//
1148 //                                Spilling
1149 //===----------------------------------------------------------------------===//
1150
1151 /// calcInterferenceWeight - Calculate the combined spill weight of
1152 /// interferences when assigning VirtReg to PhysReg.
1153 float RAGreedy::calcInterferenceWeight(LiveInterval &VirtReg, unsigned PhysReg){
1154   float Sum = 0;
1155   for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1156     LiveIntervalUnion::Query &Q = query(VirtReg, *AI);
1157     Q.collectInterferingVRegs();
1158     if (Q.seenUnspillableVReg())
1159       return HUGE_VALF;
1160     for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i)
1161       Sum += Q.interferingVRegs()[i]->weight;
1162   }
1163   return Sum;
1164 }
1165
1166 /// trySpillInterferences - Try to spill interfering registers instead of the
1167 /// current one. Only do it if the accumulated spill weight is smaller than the
1168 /// current spill weight.
1169 unsigned RAGreedy::trySpillInterferences(LiveInterval &VirtReg,
1170                                          AllocationOrder &Order,
1171                                      SmallVectorImpl<LiveInterval*> &NewVRegs) {
1172   NamedRegionTimer T("Spill Interference", TimerGroupName, TimePassesIsEnabled);
1173   unsigned BestPhys = 0;
1174   float BestWeight = 0;
1175
1176   Order.rewind();
1177   while (unsigned PhysReg = Order.next()) {
1178     float Weight = calcInterferenceWeight(VirtReg, PhysReg);
1179     if (Weight == HUGE_VALF || Weight >= VirtReg.weight)
1180       continue;
1181     if (!BestPhys || Weight < BestWeight)
1182       BestPhys = PhysReg, BestWeight = Weight;
1183   }
1184
1185   // No candidates found.
1186   if (!BestPhys)
1187     return 0;
1188
1189   // Collect all interfering registers.
1190   SmallVector<LiveInterval*, 8> Spills;
1191   for (const unsigned *AI = TRI->getOverlaps(BestPhys); *AI; ++AI) {
1192     LiveIntervalUnion::Query &Q = query(VirtReg, *AI);
1193     Spills.append(Q.interferingVRegs().begin(), Q.interferingVRegs().end());
1194     for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
1195       LiveInterval *VReg = Q.interferingVRegs()[i];
1196       unassign(*VReg, *AI);
1197     }
1198   }
1199
1200   // Spill them all.
1201   DEBUG(dbgs() << "spilling " << Spills.size() << " interferences with weight "
1202                << BestWeight << '\n');
1203   for (unsigned i = 0, e = Spills.size(); i != e; ++i)
1204     spiller().spill(Spills[i], NewVRegs, Spills);
1205   return BestPhys;
1206 }
1207
1208
1209 //===----------------------------------------------------------------------===//
1210 //                            Main Entry Point
1211 //===----------------------------------------------------------------------===//
1212
1213 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1214                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1215   // First try assigning a free register.
1216   AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1217   while (unsigned PhysReg = Order.next()) {
1218     if (!checkPhysRegInterference(VirtReg, PhysReg))
1219       return PhysReg;
1220   }
1221
1222   // Try to reassign interferences.
1223   if (unsigned PhysReg = tryReassignOrEvict(VirtReg, Order, NewVRegs))
1224     return PhysReg;
1225
1226   assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1227
1228   // Try splitting VirtReg or interferences.
1229   unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1230   if (PhysReg || !NewVRegs.empty())
1231     return PhysReg;
1232
1233   // Try to spill another interfering reg with less spill weight.
1234   PhysReg = trySpillInterferences(VirtReg, Order, NewVRegs);
1235   if (PhysReg)
1236     return PhysReg;
1237
1238   // Finally spill VirtReg itself.
1239   NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1240   SmallVector<LiveInterval*, 1> pendingSpills;
1241   spiller().spill(&VirtReg, NewVRegs, pendingSpills);
1242
1243   // The live virtual register requesting allocation was spilled, so tell
1244   // the caller not to allocate anything during this round.
1245   return 0;
1246 }
1247
1248 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1249   DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1250                << "********** Function: "
1251                << ((Value*)mf.getFunction())->getName() << '\n');
1252
1253   MF = &mf;
1254   if (VerifyEnabled)
1255     MF->verify(this, "Before greedy register allocator");
1256
1257   RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1258   Indexes = &getAnalysis<SlotIndexes>();
1259   DomTree = &getAnalysis<MachineDominatorTree>();
1260   ReservedRegs = TRI->getReservedRegs(*MF);
1261   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1262   Loops = &getAnalysis<MachineLoopInfo>();
1263   LoopRanges = &getAnalysis<MachineLoopRanges>();
1264   Bundles = &getAnalysis<EdgeBundles>();
1265   SpillPlacer = &getAnalysis<SpillPlacement>();
1266
1267   SA.reset(new SplitAnalysis(*MF, *LIS, *Loops));
1268
1269   allocatePhysRegs();
1270   addMBBLiveIns(MF);
1271   LIS->addKillFlags();
1272
1273   // Run rewriter
1274   {
1275     NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1276     std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
1277     rewriter->runOnMachineFunction(*MF, *VRM, LIS);
1278   }
1279
1280   // The pass output is in VirtRegMap. Release all the transient data.
1281   releaseMemory();
1282
1283   return true;
1284 }