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