Convert RAGreedy to LiveRegMatrix interference checking.
[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 "InterferenceCache.h"
18 #include "LiveDebugVariables.h"
19 #include "LiveRegMatrix.h"
20 #include "RegAllocBase.h"
21 #include "Spiller.h"
22 #include "SpillPlacement.h"
23 #include "SplitKit.h"
24 #include "VirtRegMap.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/LiveRangeEdit.h"
33 #include "llvm/CodeGen/LiveStackAnalysis.h"
34 #include "llvm/CodeGen/MachineDominators.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineLoopInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/Passes.h"
39 #include "llvm/CodeGen/RegAllocRegistry.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Support/CommandLine.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 #include <queue>
48
49 using namespace llvm;
50
51 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
52 STATISTIC(NumLocalSplits,  "Number of split local live ranges");
53 STATISTIC(NumEvicted,      "Number of interferences evicted");
54
55 static cl::opt<SplitEditor::ComplementSpillMode>
56 SplitSpillMode("split-spill-mode", cl::Hidden,
57   cl::desc("Spill mode for splitting live ranges"),
58   cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
59              clEnumValN(SplitEditor::SM_Size,  "size",  "Optimize for size"),
60              clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
61              clEnumValEnd),
62   cl::init(SplitEditor::SM_Partition));
63
64 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
65                                        createGreedyRegisterAllocator);
66
67 namespace {
68 class RAGreedy : public MachineFunctionPass,
69                  public RegAllocBase,
70                  private LiveRangeEdit::Delegate {
71
72   // context
73   MachineFunction *MF;
74
75   // analyses
76   SlotIndexes *Indexes;
77   MachineDominatorTree *DomTree;
78   MachineLoopInfo *Loops;
79   EdgeBundles *Bundles;
80   SpillPlacement *SpillPlacer;
81   LiveDebugVariables *DebugVars;
82
83   // state
84   std::auto_ptr<Spiller> SpillerInstance;
85   std::priority_queue<std::pair<unsigned, unsigned> > Queue;
86   unsigned NextCascade;
87
88   // Live ranges pass through a number of stages as we try to allocate them.
89   // Some of the stages may also create new live ranges:
90   //
91   // - Region splitting.
92   // - Per-block splitting.
93   // - Local splitting.
94   // - Spilling.
95   //
96   // Ranges produced by one of the stages skip the previous stages when they are
97   // dequeued. This improves performance because we can skip interference checks
98   // that are unlikely to give any results. It also guarantees that the live
99   // range splitting algorithm terminates, something that is otherwise hard to
100   // ensure.
101   enum LiveRangeStage {
102     /// Newly created live range that has never been queued.
103     RS_New,
104
105     /// Only attempt assignment and eviction. Then requeue as RS_Split.
106     RS_Assign,
107
108     /// Attempt live range splitting if assignment is impossible.
109     RS_Split,
110
111     /// Attempt more aggressive live range splitting that is guaranteed to make
112     /// progress.  This is used for split products that may not be making
113     /// progress.
114     RS_Split2,
115
116     /// Live range will be spilled.  No more splitting will be attempted.
117     RS_Spill,
118
119     /// There is nothing more we can do to this live range.  Abort compilation
120     /// if it can't be assigned.
121     RS_Done
122   };
123
124   static const char *const StageName[];
125
126   // RegInfo - Keep additional information about each live range.
127   struct RegInfo {
128     LiveRangeStage Stage;
129
130     // Cascade - Eviction loop prevention. See canEvictInterference().
131     unsigned Cascade;
132
133     RegInfo() : Stage(RS_New), Cascade(0) {}
134   };
135
136   IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
137
138   LiveRangeStage getStage(const LiveInterval &VirtReg) const {
139     return ExtraRegInfo[VirtReg.reg].Stage;
140   }
141
142   void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
143     ExtraRegInfo.resize(MRI->getNumVirtRegs());
144     ExtraRegInfo[VirtReg.reg].Stage = Stage;
145   }
146
147   template<typename Iterator>
148   void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
149     ExtraRegInfo.resize(MRI->getNumVirtRegs());
150     for (;Begin != End; ++Begin) {
151       unsigned Reg = (*Begin)->reg;
152       if (ExtraRegInfo[Reg].Stage == RS_New)
153         ExtraRegInfo[Reg].Stage = NewStage;
154     }
155   }
156
157   /// Cost of evicting interference.
158   struct EvictionCost {
159     unsigned BrokenHints; ///< Total number of broken hints.
160     float MaxWeight;      ///< Maximum spill weight evicted.
161
162     EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
163
164     bool operator<(const EvictionCost &O) const {
165       if (BrokenHints != O.BrokenHints)
166         return BrokenHints < O.BrokenHints;
167       return MaxWeight < O.MaxWeight;
168     }
169   };
170
171   // splitting state.
172   std::auto_ptr<SplitAnalysis> SA;
173   std::auto_ptr<SplitEditor> SE;
174
175   /// Cached per-block interference maps
176   InterferenceCache IntfCache;
177
178   /// All basic blocks where the current register has uses.
179   SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
180
181   /// Global live range splitting candidate info.
182   struct GlobalSplitCandidate {
183     // Register intended for assignment, or 0.
184     unsigned PhysReg;
185
186     // SplitKit interval index for this candidate.
187     unsigned IntvIdx;
188
189     // Interference for PhysReg.
190     InterferenceCache::Cursor Intf;
191
192     // Bundles where this candidate should be live.
193     BitVector LiveBundles;
194     SmallVector<unsigned, 8> ActiveBlocks;
195
196     void reset(InterferenceCache &Cache, unsigned Reg) {
197       PhysReg = Reg;
198       IntvIdx = 0;
199       Intf.setPhysReg(Cache, Reg);
200       LiveBundles.clear();
201       ActiveBlocks.clear();
202     }
203
204     // Set B[i] = C for every live bundle where B[i] was NoCand.
205     unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
206       unsigned Count = 0;
207       for (int i = LiveBundles.find_first(); i >= 0;
208            i = LiveBundles.find_next(i))
209         if (B[i] == NoCand) {
210           B[i] = C;
211           Count++;
212         }
213       return Count;
214     }
215   };
216
217   /// Candidate info for for each PhysReg in AllocationOrder.
218   /// This vector never shrinks, but grows to the size of the largest register
219   /// class.
220   SmallVector<GlobalSplitCandidate, 32> GlobalCand;
221
222   enum { NoCand = ~0u };
223
224   /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
225   /// NoCand which indicates the stack interval.
226   SmallVector<unsigned, 32> BundleCand;
227
228 public:
229   RAGreedy();
230
231   /// Return the pass name.
232   virtual const char* getPassName() const {
233     return "Greedy Register Allocator";
234   }
235
236   /// RAGreedy analysis usage.
237   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
238   virtual void releaseMemory();
239   virtual Spiller &spiller() { return *SpillerInstance; }
240   virtual void enqueue(LiveInterval *LI);
241   virtual LiveInterval *dequeue();
242   virtual unsigned selectOrSplit(LiveInterval&,
243                                  SmallVectorImpl<LiveInterval*>&);
244
245   /// Perform register allocation.
246   virtual bool runOnMachineFunction(MachineFunction &mf);
247
248   static char ID;
249
250 private:
251   bool LRE_CanEraseVirtReg(unsigned);
252   void LRE_WillShrinkVirtReg(unsigned);
253   void LRE_DidCloneVirtReg(unsigned, unsigned);
254
255   float calcSpillCost();
256   bool addSplitConstraints(InterferenceCache::Cursor, float&);
257   void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
258   void growRegion(GlobalSplitCandidate &Cand);
259   float calcGlobalSplitCost(GlobalSplitCandidate&);
260   bool calcCompactRegion(GlobalSplitCandidate&);
261   void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
262   void calcGapWeights(unsigned, SmallVectorImpl<float>&);
263   bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
264   bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
265   void evictInterference(LiveInterval&, unsigned,
266                          SmallVectorImpl<LiveInterval*>&);
267
268   unsigned tryAssign(LiveInterval&, AllocationOrder&,
269                      SmallVectorImpl<LiveInterval*>&);
270   unsigned tryEvict(LiveInterval&, AllocationOrder&,
271                     SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
272   unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
273                           SmallVectorImpl<LiveInterval*>&);
274   unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
275                          SmallVectorImpl<LiveInterval*>&);
276   unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
277                                SmallVectorImpl<LiveInterval*>&);
278   unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
279     SmallVectorImpl<LiveInterval*>&);
280   unsigned trySplit(LiveInterval&, AllocationOrder&,
281                     SmallVectorImpl<LiveInterval*>&);
282 };
283 } // end anonymous namespace
284
285 char RAGreedy::ID = 0;
286
287 #ifndef NDEBUG
288 const char *const RAGreedy::StageName[] = {
289     "RS_New",
290     "RS_Assign",
291     "RS_Split",
292     "RS_Split2",
293     "RS_Spill",
294     "RS_Done"
295 };
296 #endif
297
298 // Hysteresis to use when comparing floats.
299 // This helps stabilize decisions based on float comparisons.
300 const float Hysteresis = 0.98f;
301
302
303 FunctionPass* llvm::createGreedyRegisterAllocator() {
304   return new RAGreedy();
305 }
306
307 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
308   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
309   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
310   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
311   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
312   initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
313   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
314   initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
315   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
316   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
317   initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
318   initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
319   initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
320   initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
321   initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
322 }
323
324 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
325   AU.setPreservesCFG();
326   AU.addRequired<AliasAnalysis>();
327   AU.addPreserved<AliasAnalysis>();
328   AU.addRequired<LiveIntervals>();
329   AU.addPreserved<LiveIntervals>();
330   AU.addRequired<SlotIndexes>();
331   AU.addPreserved<SlotIndexes>();
332   AU.addRequired<LiveDebugVariables>();
333   AU.addPreserved<LiveDebugVariables>();
334   AU.addRequired<CalculateSpillWeights>();
335   AU.addRequired<LiveStacks>();
336   AU.addPreserved<LiveStacks>();
337   AU.addRequired<MachineDominatorTree>();
338   AU.addPreserved<MachineDominatorTree>();
339   AU.addRequired<MachineLoopInfo>();
340   AU.addPreserved<MachineLoopInfo>();
341   AU.addRequired<VirtRegMap>();
342   AU.addPreserved<VirtRegMap>();
343   AU.addRequired<LiveRegMatrix>();
344   AU.addPreserved<LiveRegMatrix>();
345   AU.addRequired<EdgeBundles>();
346   AU.addRequired<SpillPlacement>();
347   MachineFunctionPass::getAnalysisUsage(AU);
348 }
349
350
351 //===----------------------------------------------------------------------===//
352 //                     LiveRangeEdit delegate methods
353 //===----------------------------------------------------------------------===//
354
355 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
356   if (VRM->hasPhys(VirtReg)) {
357     Matrix->unassign(LIS->getInterval(VirtReg));
358     return true;
359   }
360   // Unassigned virtreg is probably in the priority queue.
361   // RegAllocBase will erase it after dequeueing.
362   return false;
363 }
364
365 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
366   if (!VRM->hasPhys(VirtReg))
367     return;
368
369   // Register is assigned, put it back on the queue for reassignment.
370   LiveInterval &LI = LIS->getInterval(VirtReg);
371   Matrix->unassign(LI);
372   enqueue(&LI);
373 }
374
375 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
376   // Cloning a register we haven't even heard about yet?  Just ignore it.
377   if (!ExtraRegInfo.inBounds(Old))
378     return;
379
380   // LRE may clone a virtual register because dead code elimination causes it to
381   // be split into connected components. The new components are much smaller
382   // than the original, so they should get a new chance at being assigned.
383   // same stage as the parent.
384   ExtraRegInfo[Old].Stage = RS_Assign;
385   ExtraRegInfo.grow(New);
386   ExtraRegInfo[New] = ExtraRegInfo[Old];
387 }
388
389 void RAGreedy::releaseMemory() {
390   SpillerInstance.reset(0);
391   ExtraRegInfo.clear();
392   GlobalCand.clear();
393   RegAllocBase::releaseMemory();
394 }
395
396 void RAGreedy::enqueue(LiveInterval *LI) {
397   // Prioritize live ranges by size, assigning larger ranges first.
398   // The queue holds (size, reg) pairs.
399   const unsigned Size = LI->getSize();
400   const unsigned Reg = LI->reg;
401   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
402          "Can only enqueue virtual registers");
403   unsigned Prio;
404
405   ExtraRegInfo.grow(Reg);
406   if (ExtraRegInfo[Reg].Stage == RS_New)
407     ExtraRegInfo[Reg].Stage = RS_Assign;
408
409   if (ExtraRegInfo[Reg].Stage == RS_Split) {
410     // Unsplit ranges that couldn't be allocated immediately are deferred until
411     // everything else has been allocated.
412     Prio = Size;
413   } else {
414     // Everything is allocated in long->short order. Long ranges that don't fit
415     // should be spilled (or split) ASAP so they don't create interference.
416     Prio = (1u << 31) + Size;
417
418     // Boost ranges that have a physical register hint.
419     if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
420       Prio |= (1u << 30);
421   }
422
423   Queue.push(std::make_pair(Prio, ~Reg));
424 }
425
426 LiveInterval *RAGreedy::dequeue() {
427   if (Queue.empty())
428     return 0;
429   LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
430   Queue.pop();
431   return LI;
432 }
433
434
435 //===----------------------------------------------------------------------===//
436 //                            Direct Assignment
437 //===----------------------------------------------------------------------===//
438
439 /// tryAssign - Try to assign VirtReg to an available register.
440 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
441                              AllocationOrder &Order,
442                              SmallVectorImpl<LiveInterval*> &NewVRegs) {
443   Order.rewind();
444   unsigned PhysReg;
445   while ((PhysReg = Order.next()))
446     if (!Matrix->checkInterference(VirtReg, PhysReg))
447       break;
448   if (!PhysReg || Order.isHint(PhysReg))
449     return PhysReg;
450
451   // PhysReg is available, but there may be a better choice.
452
453   // If we missed a simple hint, try to cheaply evict interference from the
454   // preferred register.
455   if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
456     if (Order.isHint(Hint)) {
457       DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
458       EvictionCost MaxCost(1);
459       if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
460         evictInterference(VirtReg, Hint, NewVRegs);
461         return Hint;
462       }
463     }
464
465   // Try to evict interference from a cheaper alternative.
466   unsigned Cost = TRI->getCostPerUse(PhysReg);
467
468   // Most registers have 0 additional cost.
469   if (!Cost)
470     return PhysReg;
471
472   DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
473                << '\n');
474   unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
475   return CheapReg ? CheapReg : PhysReg;
476 }
477
478
479 //===----------------------------------------------------------------------===//
480 //                         Interference eviction
481 //===----------------------------------------------------------------------===//
482
483 /// shouldEvict - determine if A should evict the assigned live range B. The
484 /// eviction policy defined by this function together with the allocation order
485 /// defined by enqueue() decides which registers ultimately end up being split
486 /// and spilled.
487 ///
488 /// Cascade numbers are used to prevent infinite loops if this function is a
489 /// cyclic relation.
490 ///
491 /// @param A          The live range to be assigned.
492 /// @param IsHint     True when A is about to be assigned to its preferred
493 ///                   register.
494 /// @param B          The live range to be evicted.
495 /// @param BreaksHint True when B is already assigned to its preferred register.
496 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
497                            LiveInterval &B, bool BreaksHint) {
498   bool CanSplit = getStage(B) < RS_Spill;
499
500   // Be fairly aggressive about following hints as long as the evictee can be
501   // split.
502   if (CanSplit && IsHint && !BreaksHint)
503     return true;
504
505   return A.weight > B.weight;
506 }
507
508 /// canEvictInterference - Return true if all interferences between VirtReg and
509 /// PhysReg can be evicted.  When OnlyCheap is set, don't do anything
510 ///
511 /// @param VirtReg Live range that is about to be assigned.
512 /// @param PhysReg Desired register for assignment.
513 /// @prarm IsHint  True when PhysReg is VirtReg's preferred register.
514 /// @param MaxCost Only look for cheaper candidates and update with new cost
515 ///                when returning true.
516 /// @returns True when interference can be evicted cheaper than MaxCost.
517 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
518                                     bool IsHint, EvictionCost &MaxCost) {
519   // It is only possible to evict virtual register interference.
520   if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
521     return false;
522
523   // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
524   // involved in an eviction before. If a cascade number was assigned, deny
525   // evicting anything with the same or a newer cascade number. This prevents
526   // infinite eviction loops.
527   //
528   // This works out so a register without a cascade number is allowed to evict
529   // anything, and it can be evicted by anything.
530   unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
531   if (!Cascade)
532     Cascade = NextCascade;
533
534   EvictionCost Cost;
535   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
536     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
537     // If there is 10 or more interferences, chances are one is heavier.
538     if (Q.collectInterferingVRegs(10) >= 10)
539       return false;
540
541     // Check if any interfering live range is heavier than MaxWeight.
542     for (unsigned i = Q.interferingVRegs().size(); i; --i) {
543       LiveInterval *Intf = Q.interferingVRegs()[i - 1];
544       assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
545              "Only expecting virtual register interference from query");
546       // Never evict spill products. They cannot split or spill.
547       if (getStage(*Intf) == RS_Done)
548         return false;
549       // Once a live range becomes small enough, it is urgent that we find a
550       // register for it. This is indicated by an infinite spill weight. These
551       // urgent live ranges get to evict almost anything.
552       //
553       // Also allow urgent evictions of unspillable ranges from a strictly
554       // larger allocation order.
555       bool Urgent = !VirtReg.isSpillable() &&
556         (Intf->isSpillable() ||
557          RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
558          RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
559       // Only evict older cascades or live ranges without a cascade.
560       unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
561       if (Cascade <= IntfCascade) {
562         if (!Urgent)
563           return false;
564         // We permit breaking cascades for urgent evictions. It should be the
565         // last resort, though, so make it really expensive.
566         Cost.BrokenHints += 10;
567       }
568       // Would this break a satisfied hint?
569       bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
570       // Update eviction cost.
571       Cost.BrokenHints += BreaksHint;
572       Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
573       // Abort if this would be too expensive.
574       if (!(Cost < MaxCost))
575         return false;
576       // Finally, apply the eviction policy for non-urgent evictions.
577       if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
578         return false;
579     }
580   }
581   MaxCost = Cost;
582   return true;
583 }
584
585 /// evictInterference - Evict any interferring registers that prevent VirtReg
586 /// from being assigned to Physreg. This assumes that canEvictInterference
587 /// returned true.
588 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
589                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
590   // Make sure that VirtReg has a cascade number, and assign that cascade
591   // number to every evicted register. These live ranges than then only be
592   // evicted by a newer cascade, preventing infinite loops.
593   unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
594   if (!Cascade)
595     Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
596
597   DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
598                << " interference: Cascade " << Cascade << '\n');
599
600   // Collect all interfering virtregs first.
601   SmallVector<LiveInterval*, 8> Intfs;
602   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
603     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
604     assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
605     ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
606     Intfs.append(IVR.begin(), IVR.end());
607   }
608
609   // Evict them second. This will invalidate the queries.
610   for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
611     LiveInterval *Intf = Intfs[i];
612     // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
613     if (!VRM->hasPhys(Intf->reg))
614       continue;
615     Matrix->unassign(*Intf);
616     assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
617             VirtReg.isSpillable() < Intf->isSpillable()) &&
618            "Cannot decrease cascade number, illegal eviction");
619     ExtraRegInfo[Intf->reg].Cascade = Cascade;
620     ++NumEvicted;
621     NewVRegs.push_back(Intf);
622   }
623 }
624
625 /// tryEvict - Try to evict all interferences for a physreg.
626 /// @param  VirtReg Currently unassigned virtual register.
627 /// @param  Order   Physregs to try.
628 /// @return         Physreg to assign VirtReg, or 0.
629 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
630                             AllocationOrder &Order,
631                             SmallVectorImpl<LiveInterval*> &NewVRegs,
632                             unsigned CostPerUseLimit) {
633   NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
634
635   // Keep track of the cheapest interference seen so far.
636   EvictionCost BestCost(~0u);
637   unsigned BestPhys = 0;
638
639   // When we are just looking for a reduced cost per use, don't break any
640   // hints, and only evict smaller spill weights.
641   if (CostPerUseLimit < ~0u) {
642     BestCost.BrokenHints = 0;
643     BestCost.MaxWeight = VirtReg.weight;
644   }
645
646   Order.rewind();
647   while (unsigned PhysReg = Order.next()) {
648     if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
649       continue;
650     // The first use of a callee-saved register in a function has cost 1.
651     // Don't start using a CSR when the CostPerUseLimit is low.
652     if (CostPerUseLimit == 1)
653      if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
654        if (!MRI->isPhysRegUsed(CSR)) {
655          DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
656                       << PrintReg(CSR, TRI) << '\n');
657          continue;
658        }
659
660     if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
661       continue;
662
663     // Best so far.
664     BestPhys = PhysReg;
665
666     // Stop if the hint can be used.
667     if (Order.isHint(PhysReg))
668       break;
669   }
670
671   if (!BestPhys)
672     return 0;
673
674   evictInterference(VirtReg, BestPhys, NewVRegs);
675   return BestPhys;
676 }
677
678
679 //===----------------------------------------------------------------------===//
680 //                              Region Splitting
681 //===----------------------------------------------------------------------===//
682
683 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
684 /// interference pattern in Physreg and its aliases. Add the constraints to
685 /// SpillPlacement and return the static cost of this split in Cost, assuming
686 /// that all preferences in SplitConstraints are met.
687 /// Return false if there are no bundles with positive bias.
688 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
689                                    float &Cost) {
690   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
691
692   // Reset interference dependent info.
693   SplitConstraints.resize(UseBlocks.size());
694   float StaticCost = 0;
695   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
696     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
697     SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
698
699     BC.Number = BI.MBB->getNumber();
700     Intf.moveToBlock(BC.Number);
701     BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
702     BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
703     BC.ChangesValue = BI.FirstDef;
704
705     if (!Intf.hasInterference())
706       continue;
707
708     // Number of spill code instructions to insert.
709     unsigned Ins = 0;
710
711     // Interference for the live-in value.
712     if (BI.LiveIn) {
713       if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
714         BC.Entry = SpillPlacement::MustSpill, ++Ins;
715       else if (Intf.first() < BI.FirstInstr)
716         BC.Entry = SpillPlacement::PrefSpill, ++Ins;
717       else if (Intf.first() < BI.LastInstr)
718         ++Ins;
719     }
720
721     // Interference for the live-out value.
722     if (BI.LiveOut) {
723       if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
724         BC.Exit = SpillPlacement::MustSpill, ++Ins;
725       else if (Intf.last() > BI.LastInstr)
726         BC.Exit = SpillPlacement::PrefSpill, ++Ins;
727       else if (Intf.last() > BI.FirstInstr)
728         ++Ins;
729     }
730
731     // Accumulate the total frequency of inserted spill code.
732     if (Ins)
733       StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
734   }
735   Cost = StaticCost;
736
737   // Add constraints for use-blocks. Note that these are the only constraints
738   // that may add a positive bias, it is downhill from here.
739   SpillPlacer->addConstraints(SplitConstraints);
740   return SpillPlacer->scanActiveBundles();
741 }
742
743
744 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
745 /// live-through blocks in Blocks.
746 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
747                                      ArrayRef<unsigned> Blocks) {
748   const unsigned GroupSize = 8;
749   SpillPlacement::BlockConstraint BCS[GroupSize];
750   unsigned TBS[GroupSize];
751   unsigned B = 0, T = 0;
752
753   for (unsigned i = 0; i != Blocks.size(); ++i) {
754     unsigned Number = Blocks[i];
755     Intf.moveToBlock(Number);
756
757     if (!Intf.hasInterference()) {
758       assert(T < GroupSize && "Array overflow");
759       TBS[T] = Number;
760       if (++T == GroupSize) {
761         SpillPlacer->addLinks(makeArrayRef(TBS, T));
762         T = 0;
763       }
764       continue;
765     }
766
767     assert(B < GroupSize && "Array overflow");
768     BCS[B].Number = Number;
769
770     // Interference for the live-in value.
771     if (Intf.first() <= Indexes->getMBBStartIdx(Number))
772       BCS[B].Entry = SpillPlacement::MustSpill;
773     else
774       BCS[B].Entry = SpillPlacement::PrefSpill;
775
776     // Interference for the live-out value.
777     if (Intf.last() >= SA->getLastSplitPoint(Number))
778       BCS[B].Exit = SpillPlacement::MustSpill;
779     else
780       BCS[B].Exit = SpillPlacement::PrefSpill;
781
782     if (++B == GroupSize) {
783       ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
784       SpillPlacer->addConstraints(Array);
785       B = 0;
786     }
787   }
788
789   ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
790   SpillPlacer->addConstraints(Array);
791   SpillPlacer->addLinks(makeArrayRef(TBS, T));
792 }
793
794 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
795   // Keep track of through blocks that have not been added to SpillPlacer.
796   BitVector Todo = SA->getThroughBlocks();
797   SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
798   unsigned AddedTo = 0;
799 #ifndef NDEBUG
800   unsigned Visited = 0;
801 #endif
802
803   for (;;) {
804     ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
805     // Find new through blocks in the periphery of PrefRegBundles.
806     for (int i = 0, e = NewBundles.size(); i != e; ++i) {
807       unsigned Bundle = NewBundles[i];
808       // Look at all blocks connected to Bundle in the full graph.
809       ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
810       for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
811            I != E; ++I) {
812         unsigned Block = *I;
813         if (!Todo.test(Block))
814           continue;
815         Todo.reset(Block);
816         // This is a new through block. Add it to SpillPlacer later.
817         ActiveBlocks.push_back(Block);
818 #ifndef NDEBUG
819         ++Visited;
820 #endif
821       }
822     }
823     // Any new blocks to add?
824     if (ActiveBlocks.size() == AddedTo)
825       break;
826
827     // Compute through constraints from the interference, or assume that all
828     // through blocks prefer spilling when forming compact regions.
829     ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
830     if (Cand.PhysReg)
831       addThroughConstraints(Cand.Intf, NewBlocks);
832     else
833       // Provide a strong negative bias on through blocks to prevent unwanted
834       // liveness on loop backedges.
835       SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
836     AddedTo = ActiveBlocks.size();
837
838     // Perhaps iterating can enable more bundles?
839     SpillPlacer->iterate();
840   }
841   DEBUG(dbgs() << ", v=" << Visited);
842 }
843
844 /// calcCompactRegion - Compute the set of edge bundles that should be live
845 /// when splitting the current live range into compact regions.  Compact
846 /// regions can be computed without looking at interference.  They are the
847 /// regions formed by removing all the live-through blocks from the live range.
848 ///
849 /// Returns false if the current live range is already compact, or if the
850 /// compact regions would form single block regions anyway.
851 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
852   // Without any through blocks, the live range is already compact.
853   if (!SA->getNumThroughBlocks())
854     return false;
855
856   // Compact regions don't correspond to any physreg.
857   Cand.reset(IntfCache, 0);
858
859   DEBUG(dbgs() << "Compact region bundles");
860
861   // Use the spill placer to determine the live bundles. GrowRegion pretends
862   // that all the through blocks have interference when PhysReg is unset.
863   SpillPlacer->prepare(Cand.LiveBundles);
864
865   // The static split cost will be zero since Cand.Intf reports no interference.
866   float Cost;
867   if (!addSplitConstraints(Cand.Intf, Cost)) {
868     DEBUG(dbgs() << ", none.\n");
869     return false;
870   }
871
872   growRegion(Cand);
873   SpillPlacer->finish();
874
875   if (!Cand.LiveBundles.any()) {
876     DEBUG(dbgs() << ", none.\n");
877     return false;
878   }
879
880   DEBUG({
881     for (int i = Cand.LiveBundles.find_first(); i>=0;
882          i = Cand.LiveBundles.find_next(i))
883     dbgs() << " EB#" << i;
884     dbgs() << ".\n";
885   });
886   return true;
887 }
888
889 /// calcSpillCost - Compute how expensive it would be to split the live range in
890 /// SA around all use blocks instead of forming bundle regions.
891 float RAGreedy::calcSpillCost() {
892   float Cost = 0;
893   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
894   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
895     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
896     unsigned Number = BI.MBB->getNumber();
897     // We normally only need one spill instruction - a load or a store.
898     Cost += SpillPlacer->getBlockFrequency(Number);
899
900     // Unless the value is redefined in the block.
901     if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
902       Cost += SpillPlacer->getBlockFrequency(Number);
903   }
904   return Cost;
905 }
906
907 /// calcGlobalSplitCost - Return the global split cost of following the split
908 /// pattern in LiveBundles. This cost should be added to the local cost of the
909 /// interference pattern in SplitConstraints.
910 ///
911 float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
912   float GlobalCost = 0;
913   const BitVector &LiveBundles = Cand.LiveBundles;
914   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
915   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
916     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
917     SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
918     bool RegIn  = LiveBundles[Bundles->getBundle(BC.Number, 0)];
919     bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
920     unsigned Ins = 0;
921
922     if (BI.LiveIn)
923       Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
924     if (BI.LiveOut)
925       Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
926     if (Ins)
927       GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
928   }
929
930   for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
931     unsigned Number = Cand.ActiveBlocks[i];
932     bool RegIn  = LiveBundles[Bundles->getBundle(Number, 0)];
933     bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
934     if (!RegIn && !RegOut)
935       continue;
936     if (RegIn && RegOut) {
937       // We need double spill code if this block has interference.
938       Cand.Intf.moveToBlock(Number);
939       if (Cand.Intf.hasInterference())
940         GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
941       continue;
942     }
943     // live-in / stack-out or stack-in live-out.
944     GlobalCost += SpillPlacer->getBlockFrequency(Number);
945   }
946   return GlobalCost;
947 }
948
949 /// splitAroundRegion - Split the current live range around the regions
950 /// determined by BundleCand and GlobalCand.
951 ///
952 /// Before calling this function, GlobalCand and BundleCand must be initialized
953 /// so each bundle is assigned to a valid candidate, or NoCand for the
954 /// stack-bound bundles.  The shared SA/SE SplitAnalysis and SplitEditor
955 /// objects must be initialized for the current live range, and intervals
956 /// created for the used candidates.
957 ///
958 /// @param LREdit    The LiveRangeEdit object handling the current split.
959 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
960 ///                  must appear in this list.
961 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
962                                  ArrayRef<unsigned> UsedCands) {
963   // These are the intervals created for new global ranges. We may create more
964   // intervals for local ranges.
965   const unsigned NumGlobalIntvs = LREdit.size();
966   DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
967   assert(NumGlobalIntvs && "No global intervals configured");
968
969   // Isolate even single instructions when dealing with a proper sub-class.
970   // That guarantees register class inflation for the stack interval because it
971   // is all copies.
972   unsigned Reg = SA->getParent().reg;
973   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
974
975   // First handle all the blocks with uses.
976   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
977   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
978     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
979     unsigned Number = BI.MBB->getNumber();
980     unsigned IntvIn = 0, IntvOut = 0;
981     SlotIndex IntfIn, IntfOut;
982     if (BI.LiveIn) {
983       unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
984       if (CandIn != NoCand) {
985         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
986         IntvIn = Cand.IntvIdx;
987         Cand.Intf.moveToBlock(Number);
988         IntfIn = Cand.Intf.first();
989       }
990     }
991     if (BI.LiveOut) {
992       unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
993       if (CandOut != NoCand) {
994         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
995         IntvOut = Cand.IntvIdx;
996         Cand.Intf.moveToBlock(Number);
997         IntfOut = Cand.Intf.last();
998       }
999     }
1000
1001     // Create separate intervals for isolated blocks with multiple uses.
1002     if (!IntvIn && !IntvOut) {
1003       DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1004       if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1005         SE->splitSingleBlock(BI);
1006       continue;
1007     }
1008
1009     if (IntvIn && IntvOut)
1010       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1011     else if (IntvIn)
1012       SE->splitRegInBlock(BI, IntvIn, IntfIn);
1013     else
1014       SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1015   }
1016
1017   // Handle live-through blocks. The relevant live-through blocks are stored in
1018   // the ActiveBlocks list with each candidate. We need to filter out
1019   // duplicates.
1020   BitVector Todo = SA->getThroughBlocks();
1021   for (unsigned c = 0; c != UsedCands.size(); ++c) {
1022     ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1023     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1024       unsigned Number = Blocks[i];
1025       if (!Todo.test(Number))
1026         continue;
1027       Todo.reset(Number);
1028
1029       unsigned IntvIn = 0, IntvOut = 0;
1030       SlotIndex IntfIn, IntfOut;
1031
1032       unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1033       if (CandIn != NoCand) {
1034         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1035         IntvIn = Cand.IntvIdx;
1036         Cand.Intf.moveToBlock(Number);
1037         IntfIn = Cand.Intf.first();
1038       }
1039
1040       unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1041       if (CandOut != NoCand) {
1042         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1043         IntvOut = Cand.IntvIdx;
1044         Cand.Intf.moveToBlock(Number);
1045         IntfOut = Cand.Intf.last();
1046       }
1047       if (!IntvIn && !IntvOut)
1048         continue;
1049       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1050     }
1051   }
1052
1053   ++NumGlobalSplits;
1054
1055   SmallVector<unsigned, 8> IntvMap;
1056   SE->finish(&IntvMap);
1057   DebugVars->splitRegister(Reg, LREdit.regs());
1058
1059   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1060   unsigned OrigBlocks = SA->getNumLiveBlocks();
1061
1062   // Sort out the new intervals created by splitting. We get four kinds:
1063   // - Remainder intervals should not be split again.
1064   // - Candidate intervals can be assigned to Cand.PhysReg.
1065   // - Block-local splits are candidates for local splitting.
1066   // - DCE leftovers should go back on the queue.
1067   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1068     LiveInterval &Reg = *LREdit.get(i);
1069
1070     // Ignore old intervals from DCE.
1071     if (getStage(Reg) != RS_New)
1072       continue;
1073
1074     // Remainder interval. Don't try splitting again, spill if it doesn't
1075     // allocate.
1076     if (IntvMap[i] == 0) {
1077       setStage(Reg, RS_Spill);
1078       continue;
1079     }
1080
1081     // Global intervals. Allow repeated splitting as long as the number of live
1082     // blocks is strictly decreasing.
1083     if (IntvMap[i] < NumGlobalIntvs) {
1084       if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1085         DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1086                      << " blocks as original.\n");
1087         // Don't allow repeated splitting as a safe guard against looping.
1088         setStage(Reg, RS_Split2);
1089       }
1090       continue;
1091     }
1092
1093     // Other intervals are treated as new. This includes local intervals created
1094     // for blocks with multiple uses, and anything created by DCE.
1095   }
1096
1097   if (VerifyEnabled)
1098     MF->verify(this, "After splitting live range around region");
1099 }
1100
1101 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1102                                   SmallVectorImpl<LiveInterval*> &NewVRegs) {
1103   unsigned NumCands = 0;
1104   unsigned BestCand = NoCand;
1105   float BestCost;
1106   SmallVector<unsigned, 8> UsedCands;
1107
1108   // Check if we can split this live range around a compact region.
1109   bool HasCompact = calcCompactRegion(GlobalCand.front());
1110   if (HasCompact) {
1111     // Yes, keep GlobalCand[0] as the compact region candidate.
1112     NumCands = 1;
1113     BestCost = HUGE_VALF;
1114   } else {
1115     // No benefit from the compact region, our fallback will be per-block
1116     // splitting. Make sure we find a solution that is cheaper than spilling.
1117     BestCost = Hysteresis * calcSpillCost();
1118     DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1119   }
1120
1121   Order.rewind();
1122   while (unsigned PhysReg = Order.next()) {
1123     // Discard bad candidates before we run out of interference cache cursors.
1124     // This will only affect register classes with a lot of registers (>32).
1125     if (NumCands == IntfCache.getMaxCursors()) {
1126       unsigned WorstCount = ~0u;
1127       unsigned Worst = 0;
1128       for (unsigned i = 0; i != NumCands; ++i) {
1129         if (i == BestCand || !GlobalCand[i].PhysReg)
1130           continue;
1131         unsigned Count = GlobalCand[i].LiveBundles.count();
1132         if (Count < WorstCount)
1133           Worst = i, WorstCount = Count;
1134       }
1135       --NumCands;
1136       GlobalCand[Worst] = GlobalCand[NumCands];
1137       if (BestCand == NumCands)
1138         BestCand = Worst;
1139     }
1140
1141     if (GlobalCand.size() <= NumCands)
1142       GlobalCand.resize(NumCands+1);
1143     GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1144     Cand.reset(IntfCache, PhysReg);
1145
1146     SpillPlacer->prepare(Cand.LiveBundles);
1147     float Cost;
1148     if (!addSplitConstraints(Cand.Intf, Cost)) {
1149       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1150       continue;
1151     }
1152     DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1153     if (Cost >= BestCost) {
1154       DEBUG({
1155         if (BestCand == NoCand)
1156           dbgs() << " worse than no bundles\n";
1157         else
1158           dbgs() << " worse than "
1159                  << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1160       });
1161       continue;
1162     }
1163     growRegion(Cand);
1164
1165     SpillPlacer->finish();
1166
1167     // No live bundles, defer to splitSingleBlocks().
1168     if (!Cand.LiveBundles.any()) {
1169       DEBUG(dbgs() << " no bundles.\n");
1170       continue;
1171     }
1172
1173     Cost += calcGlobalSplitCost(Cand);
1174     DEBUG({
1175       dbgs() << ", total = " << Cost << " with bundles";
1176       for (int i = Cand.LiveBundles.find_first(); i>=0;
1177            i = Cand.LiveBundles.find_next(i))
1178         dbgs() << " EB#" << i;
1179       dbgs() << ".\n";
1180     });
1181     if (Cost < BestCost) {
1182       BestCand = NumCands;
1183       BestCost = Hysteresis * Cost; // Prevent rounding effects.
1184     }
1185     ++NumCands;
1186   }
1187
1188   // No solutions found, fall back to single block splitting.
1189   if (!HasCompact && BestCand == NoCand)
1190     return 0;
1191
1192   // Prepare split editor.
1193   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1194   SE->reset(LREdit, SplitSpillMode);
1195
1196   // Assign all edge bundles to the preferred candidate, or NoCand.
1197   BundleCand.assign(Bundles->getNumBundles(), NoCand);
1198
1199   // Assign bundles for the best candidate region.
1200   if (BestCand != NoCand) {
1201     GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1202     if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1203       UsedCands.push_back(BestCand);
1204       Cand.IntvIdx = SE->openIntv();
1205       DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1206                    << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1207       (void)B;
1208     }
1209   }
1210
1211   // Assign bundles for the compact region.
1212   if (HasCompact) {
1213     GlobalSplitCandidate &Cand = GlobalCand.front();
1214     assert(!Cand.PhysReg && "Compact region has no physreg");
1215     if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1216       UsedCands.push_back(0);
1217       Cand.IntvIdx = SE->openIntv();
1218       DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1219                    << Cand.IntvIdx << ".\n");
1220       (void)B;
1221     }
1222   }
1223
1224   splitAroundRegion(LREdit, UsedCands);
1225   return 0;
1226 }
1227
1228
1229 //===----------------------------------------------------------------------===//
1230 //                            Per-Block Splitting
1231 //===----------------------------------------------------------------------===//
1232
1233 /// tryBlockSplit - Split a global live range around every block with uses. This
1234 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1235 /// they don't allocate.
1236 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1237                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1238   assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1239   unsigned Reg = VirtReg.reg;
1240   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1241   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1242   SE->reset(LREdit, SplitSpillMode);
1243   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1244   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1245     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1246     if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1247       SE->splitSingleBlock(BI);
1248   }
1249   // No blocks were split.
1250   if (LREdit.empty())
1251     return 0;
1252
1253   // We did split for some blocks.
1254   SmallVector<unsigned, 8> IntvMap;
1255   SE->finish(&IntvMap);
1256
1257   // Tell LiveDebugVariables about the new ranges.
1258   DebugVars->splitRegister(Reg, LREdit.regs());
1259
1260   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1261
1262   // Sort out the new intervals created by splitting. The remainder interval
1263   // goes straight to spilling, the new local ranges get to stay RS_New.
1264   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1265     LiveInterval &LI = *LREdit.get(i);
1266     if (getStage(LI) == RS_New && IntvMap[i] == 0)
1267       setStage(LI, RS_Spill);
1268   }
1269
1270   if (VerifyEnabled)
1271     MF->verify(this, "After splitting live range around basic blocks");
1272   return 0;
1273 }
1274
1275
1276 //===----------------------------------------------------------------------===//
1277 //                         Per-Instruction Splitting
1278 //===----------------------------------------------------------------------===//
1279
1280 /// tryInstructionSplit - Split a live range around individual instructions.
1281 /// This is normally not worthwhile since the spiller is doing essentially the
1282 /// same thing. However, when the live range is in a constrained register
1283 /// class, it may help to insert copies such that parts of the live range can
1284 /// be moved to a larger register class.
1285 ///
1286 /// This is similar to spilling to a larger register class.
1287 unsigned
1288 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1289                               SmallVectorImpl<LiveInterval*> &NewVRegs) {
1290   // There is no point to this if there are no larger sub-classes.
1291   if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1292     return 0;
1293
1294   // Always enable split spill mode, since we're effectively spilling to a
1295   // register.
1296   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1297   SE->reset(LREdit, SplitEditor::SM_Size);
1298
1299   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1300   if (Uses.size() <= 1)
1301     return 0;
1302
1303   DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1304
1305   // Split around every non-copy instruction.
1306   for (unsigned i = 0; i != Uses.size(); ++i) {
1307     if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1308       if (MI->isFullCopy()) {
1309         DEBUG(dbgs() << "    skip:\t" << Uses[i] << '\t' << *MI);
1310         continue;
1311       }
1312     SE->openIntv();
1313     SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1314     SlotIndex SegStop  = SE->leaveIntvAfter(Uses[i]);
1315     SE->useIntv(SegStart, SegStop);
1316   }
1317
1318   if (LREdit.empty()) {
1319     DEBUG(dbgs() << "All uses were copies.\n");
1320     return 0;
1321   }
1322
1323   SmallVector<unsigned, 8> IntvMap;
1324   SE->finish(&IntvMap);
1325   DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1326   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1327
1328   // Assign all new registers to RS_Spill. This was the last chance.
1329   setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1330   return 0;
1331 }
1332
1333
1334 //===----------------------------------------------------------------------===//
1335 //                             Local Splitting
1336 //===----------------------------------------------------------------------===//
1337
1338
1339 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1340 /// in order to use PhysReg between two entries in SA->UseSlots.
1341 ///
1342 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1343 ///
1344 void RAGreedy::calcGapWeights(unsigned PhysReg,
1345                               SmallVectorImpl<float> &GapWeight) {
1346   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1347   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1348   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1349   const unsigned NumGaps = Uses.size()-1;
1350
1351   // Start and end points for the interference check.
1352   SlotIndex StartIdx =
1353     BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1354   SlotIndex StopIdx =
1355     BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1356
1357   GapWeight.assign(NumGaps, 0.0f);
1358
1359   // Add interference from each overlapping register.
1360   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1361     if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1362           .checkInterference())
1363       continue;
1364
1365     // We know that VirtReg is a continuous interval from FirstInstr to
1366     // LastInstr, so we don't need InterferenceQuery.
1367     //
1368     // Interference that overlaps an instruction is counted in both gaps
1369     // surrounding the instruction. The exception is interference before
1370     // StartIdx and after StopIdx.
1371     //
1372     LiveIntervalUnion::SegmentIter IntI =
1373       Matrix->getLiveUnions()[*Units] .find(StartIdx);
1374     for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1375       // Skip the gaps before IntI.
1376       while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1377         if (++Gap == NumGaps)
1378           break;
1379       if (Gap == NumGaps)
1380         break;
1381
1382       // Update the gaps covered by IntI.
1383       const float weight = IntI.value()->weight;
1384       for (; Gap != NumGaps; ++Gap) {
1385         GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1386         if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1387           break;
1388       }
1389       if (Gap == NumGaps)
1390         break;
1391     }
1392   }
1393
1394   // Add fixed interference.
1395   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1396     const LiveInterval &LI = LIS->getRegUnit(*Units);
1397     LiveInterval::const_iterator I = LI.find(StartIdx);
1398     LiveInterval::const_iterator E = LI.end();
1399
1400     // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1401     for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1402       while (Uses[Gap+1].getBoundaryIndex() < I->start)
1403         if (++Gap == NumGaps)
1404           break;
1405       if (Gap == NumGaps)
1406         break;
1407
1408       for (; Gap != NumGaps; ++Gap) {
1409         GapWeight[Gap] = HUGE_VALF;
1410         if (Uses[Gap+1].getBaseIndex() >= I->end)
1411           break;
1412       }
1413       if (Gap == NumGaps)
1414         break;
1415     }
1416   }
1417 }
1418
1419 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1420 /// basic block.
1421 ///
1422 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1423                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1424   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1425   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1426
1427   // Note that it is possible to have an interval that is live-in or live-out
1428   // while only covering a single block - A phi-def can use undef values from
1429   // predecessors, and the block could be a single-block loop.
1430   // We don't bother doing anything clever about such a case, we simply assume
1431   // that the interval is continuous from FirstInstr to LastInstr. We should
1432   // make sure that we don't do anything illegal to such an interval, though.
1433
1434   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1435   if (Uses.size() <= 2)
1436     return 0;
1437   const unsigned NumGaps = Uses.size()-1;
1438
1439   DEBUG({
1440     dbgs() << "tryLocalSplit: ";
1441     for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1442       dbgs() << ' ' << Uses[i];
1443     dbgs() << '\n';
1444   });
1445
1446   // If VirtReg is live across any register mask operands, compute a list of
1447   // gaps with register masks.
1448   SmallVector<unsigned, 8> RegMaskGaps;
1449   if (Matrix->checkRegMaskInterference(VirtReg)) {
1450     // Get regmask slots for the whole block.
1451     ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1452     DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1453     // Constrain to VirtReg's live range.
1454     unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1455                                    Uses.front().getRegSlot()) - RMS.begin();
1456     unsigned re = RMS.size();
1457     for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1458       // Look for Uses[i] <= RMS <= Uses[i+1].
1459       assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1460       if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1461         continue;
1462       // Skip a regmask on the same instruction as the last use. It doesn't
1463       // overlap the live range.
1464       if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1465         break;
1466       DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1467       RegMaskGaps.push_back(i);
1468       // Advance ri to the next gap. A regmask on one of the uses counts in
1469       // both gaps.
1470       while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1471         ++ri;
1472     }
1473     DEBUG(dbgs() << '\n');
1474   }
1475
1476   // Since we allow local split results to be split again, there is a risk of
1477   // creating infinite loops. It is tempting to require that the new live
1478   // ranges have less instructions than the original. That would guarantee
1479   // convergence, but it is too strict. A live range with 3 instructions can be
1480   // split 2+3 (including the COPY), and we want to allow that.
1481   //
1482   // Instead we use these rules:
1483   //
1484   // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1485   //    noop split, of course).
1486   // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1487   //    the new ranges must have fewer instructions than before the split.
1488   // 3. New ranges with the same number of instructions are marked RS_Split2,
1489   //    smaller ranges are marked RS_New.
1490   //
1491   // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1492   // excessive splitting and infinite loops.
1493   //
1494   bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1495
1496   // Best split candidate.
1497   unsigned BestBefore = NumGaps;
1498   unsigned BestAfter = 0;
1499   float BestDiff = 0;
1500
1501   const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1502   SmallVector<float, 8> GapWeight;
1503
1504   Order.rewind();
1505   while (unsigned PhysReg = Order.next()) {
1506     // Keep track of the largest spill weight that would need to be evicted in
1507     // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1508     calcGapWeights(PhysReg, GapWeight);
1509
1510     // Remove any gaps with regmask clobbers.
1511     if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1512       for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1513         GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1514
1515     // Try to find the best sequence of gaps to close.
1516     // The new spill weight must be larger than any gap interference.
1517
1518     // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1519     unsigned SplitBefore = 0, SplitAfter = 1;
1520
1521     // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1522     // It is the spill weight that needs to be evicted.
1523     float MaxGap = GapWeight[0];
1524
1525     for (;;) {
1526       // Live before/after split?
1527       const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1528       const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1529
1530       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1531                    << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1532                    << " i=" << MaxGap);
1533
1534       // Stop before the interval gets so big we wouldn't be making progress.
1535       if (!LiveBefore && !LiveAfter) {
1536         DEBUG(dbgs() << " all\n");
1537         break;
1538       }
1539       // Should the interval be extended or shrunk?
1540       bool Shrink = true;
1541
1542       // How many gaps would the new range have?
1543       unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1544
1545       // Legally, without causing looping?
1546       bool Legal = !ProgressRequired || NewGaps < NumGaps;
1547
1548       if (Legal && MaxGap < HUGE_VALF) {
1549         // Estimate the new spill weight. Each instruction reads or writes the
1550         // register. Conservatively assume there are no read-modify-write
1551         // instructions.
1552         //
1553         // Try to guess the size of the new interval.
1554         const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1555                                  Uses[SplitBefore].distance(Uses[SplitAfter]) +
1556                                  (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1557         // Would this split be possible to allocate?
1558         // Never allocate all gaps, we wouldn't be making progress.
1559         DEBUG(dbgs() << " w=" << EstWeight);
1560         if (EstWeight * Hysteresis >= MaxGap) {
1561           Shrink = false;
1562           float Diff = EstWeight - MaxGap;
1563           if (Diff > BestDiff) {
1564             DEBUG(dbgs() << " (best)");
1565             BestDiff = Hysteresis * Diff;
1566             BestBefore = SplitBefore;
1567             BestAfter = SplitAfter;
1568           }
1569         }
1570       }
1571
1572       // Try to shrink.
1573       if (Shrink) {
1574         if (++SplitBefore < SplitAfter) {
1575           DEBUG(dbgs() << " shrink\n");
1576           // Recompute the max when necessary.
1577           if (GapWeight[SplitBefore - 1] >= MaxGap) {
1578             MaxGap = GapWeight[SplitBefore];
1579             for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1580               MaxGap = std::max(MaxGap, GapWeight[i]);
1581           }
1582           continue;
1583         }
1584         MaxGap = 0;
1585       }
1586
1587       // Try to extend the interval.
1588       if (SplitAfter >= NumGaps) {
1589         DEBUG(dbgs() << " end\n");
1590         break;
1591       }
1592
1593       DEBUG(dbgs() << " extend\n");
1594       MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1595     }
1596   }
1597
1598   // Didn't find any candidates?
1599   if (BestBefore == NumGaps)
1600     return 0;
1601
1602   DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1603                << '-' << Uses[BestAfter] << ", " << BestDiff
1604                << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1605
1606   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1607   SE->reset(LREdit);
1608
1609   SE->openIntv();
1610   SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1611   SlotIndex SegStop  = SE->leaveIntvAfter(Uses[BestAfter]);
1612   SE->useIntv(SegStart, SegStop);
1613   SmallVector<unsigned, 8> IntvMap;
1614   SE->finish(&IntvMap);
1615   DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1616
1617   // If the new range has the same number of instructions as before, mark it as
1618   // RS_Split2 so the next split will be forced to make progress. Otherwise,
1619   // leave the new intervals as RS_New so they can compete.
1620   bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1621   bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1622   unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1623   if (NewGaps >= NumGaps) {
1624     DEBUG(dbgs() << "Tagging non-progress ranges: ");
1625     assert(!ProgressRequired && "Didn't make progress when it was required.");
1626     for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1627       if (IntvMap[i] == 1) {
1628         setStage(*LREdit.get(i), RS_Split2);
1629         DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1630       }
1631     DEBUG(dbgs() << '\n');
1632   }
1633   ++NumLocalSplits;
1634
1635   return 0;
1636 }
1637
1638 //===----------------------------------------------------------------------===//
1639 //                          Live Range Splitting
1640 //===----------------------------------------------------------------------===//
1641
1642 /// trySplit - Try to split VirtReg or one of its interferences, making it
1643 /// assignable.
1644 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1645 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1646                             SmallVectorImpl<LiveInterval*>&NewVRegs) {
1647   // Ranges must be Split2 or less.
1648   if (getStage(VirtReg) >= RS_Spill)
1649     return 0;
1650
1651   // Local intervals are handled separately.
1652   if (LIS->intervalIsInOneMBB(VirtReg)) {
1653     NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1654     SA->analyze(&VirtReg);
1655     unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1656     if (PhysReg || !NewVRegs.empty())
1657       return PhysReg;
1658     return tryInstructionSplit(VirtReg, Order, NewVRegs);
1659   }
1660
1661   NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1662
1663   SA->analyze(&VirtReg);
1664
1665   // FIXME: SplitAnalysis may repair broken live ranges coming from the
1666   // coalescer. That may cause the range to become allocatable which means that
1667   // tryRegionSplit won't be making progress. This check should be replaced with
1668   // an assertion when the coalescer is fixed.
1669   if (SA->didRepairRange()) {
1670     // VirtReg has changed, so all cached queries are invalid.
1671     Matrix->invalidateVirtRegs();
1672     if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1673       return PhysReg;
1674   }
1675
1676   // First try to split around a region spanning multiple blocks. RS_Split2
1677   // ranges already made dubious progress with region splitting, so they go
1678   // straight to single block splitting.
1679   if (getStage(VirtReg) < RS_Split2) {
1680     unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1681     if (PhysReg || !NewVRegs.empty())
1682       return PhysReg;
1683   }
1684
1685   // Then isolate blocks.
1686   return tryBlockSplit(VirtReg, Order, NewVRegs);
1687 }
1688
1689
1690 //===----------------------------------------------------------------------===//
1691 //                            Main Entry Point
1692 //===----------------------------------------------------------------------===//
1693
1694 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1695                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1696   // First try assigning a free register.
1697   AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1698   if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1699     return PhysReg;
1700
1701   LiveRangeStage Stage = getStage(VirtReg);
1702   DEBUG(dbgs() << StageName[Stage]
1703                << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1704
1705   // Try to evict a less worthy live range, but only for ranges from the primary
1706   // queue. The RS_Split ranges already failed to do this, and they should not
1707   // get a second chance until they have been split.
1708   if (Stage != RS_Split)
1709     if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1710       return PhysReg;
1711
1712   assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1713
1714   // The first time we see a live range, don't try to split or spill.
1715   // Wait until the second time, when all smaller ranges have been allocated.
1716   // This gives a better picture of the interference to split around.
1717   if (Stage < RS_Split) {
1718     setStage(VirtReg, RS_Split);
1719     DEBUG(dbgs() << "wait for second round\n");
1720     NewVRegs.push_back(&VirtReg);
1721     return 0;
1722   }
1723
1724   // If we couldn't allocate a register from spilling, there is probably some
1725   // invalid inline assembly. The base class wil report it.
1726   if (Stage >= RS_Done || !VirtReg.isSpillable())
1727     return ~0u;
1728
1729   // Try splitting VirtReg or interferences.
1730   unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1731   if (PhysReg || !NewVRegs.empty())
1732     return PhysReg;
1733
1734   // Finally spill VirtReg itself.
1735   NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1736   LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1737   spiller().spill(LRE);
1738   setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1739
1740   if (VerifyEnabled)
1741     MF->verify(this, "After spilling");
1742
1743   // The live virtual register requesting allocation was spilled, so tell
1744   // the caller not to allocate anything during this round.
1745   return 0;
1746 }
1747
1748 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1749   DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1750                << "********** Function: "
1751                << ((Value*)mf.getFunction())->getName() << '\n');
1752
1753   MF = &mf;
1754   if (VerifyEnabled)
1755     MF->verify(this, "Before greedy register allocator");
1756
1757   RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1758   Matrix = &getAnalysis<LiveRegMatrix>();
1759   Indexes = &getAnalysis<SlotIndexes>();
1760   DomTree = &getAnalysis<MachineDominatorTree>();
1761   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1762   Loops = &getAnalysis<MachineLoopInfo>();
1763   Bundles = &getAnalysis<EdgeBundles>();
1764   SpillPlacer = &getAnalysis<SpillPlacement>();
1765   DebugVars = &getAnalysis<LiveDebugVariables>();
1766
1767   SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1768   SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1769   ExtraRegInfo.clear();
1770   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1771   NextCascade = 1;
1772   IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
1773   GlobalCand.resize(32);  // This will grow as needed.
1774
1775   allocatePhysRegs();
1776   releaseMemory();
1777   return true;
1778 }