Dump LIS before regalloc. MI sched changes them.
[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   BlockFrequency calcSpillCost();
255   bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
256   void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
257   void growRegion(GlobalSplitCandidate &Cand);
258   BlockFrequency 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                                    BlockFrequency &Cost) {
707   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
708
709   // Reset interference dependent info.
710   SplitConstraints.resize(UseBlocks.size());
711   BlockFrequency 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     while (Ins--)
750       StaticCost += 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   BlockFrequency 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 BlockFrequency RAGreedy::calcSpillCost() {
909   BlockFrequency 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 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
929   BlockFrequency 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     while (Ins--)
944       GlobalCost += 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 += SpillPlacer->getBlockFrequency(Number);
958         GlobalCost += SpillPlacer->getBlockFrequency(Number);
959       }
960       continue;
961     }
962     // live-in / stack-out or stack-in live-out.
963     GlobalCost += SpillPlacer->getBlockFrequency(Number);
964   }
965   return GlobalCost;
966 }
967
968 /// splitAroundRegion - Split the current live range around the regions
969 /// determined by BundleCand and GlobalCand.
970 ///
971 /// Before calling this function, GlobalCand and BundleCand must be initialized
972 /// so each bundle is assigned to a valid candidate, or NoCand for the
973 /// stack-bound bundles.  The shared SA/SE SplitAnalysis and SplitEditor
974 /// objects must be initialized for the current live range, and intervals
975 /// created for the used candidates.
976 ///
977 /// @param LREdit    The LiveRangeEdit object handling the current split.
978 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
979 ///                  must appear in this list.
980 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
981                                  ArrayRef<unsigned> UsedCands) {
982   // These are the intervals created for new global ranges. We may create more
983   // intervals for local ranges.
984   const unsigned NumGlobalIntvs = LREdit.size();
985   DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
986   assert(NumGlobalIntvs && "No global intervals configured");
987
988   // Isolate even single instructions when dealing with a proper sub-class.
989   // That guarantees register class inflation for the stack interval because it
990   // is all copies.
991   unsigned Reg = SA->getParent().reg;
992   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
993
994   // First handle all the blocks with uses.
995   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
996   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
997     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
998     unsigned Number = BI.MBB->getNumber();
999     unsigned IntvIn = 0, IntvOut = 0;
1000     SlotIndex IntfIn, IntfOut;
1001     if (BI.LiveIn) {
1002       unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1003       if (CandIn != NoCand) {
1004         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1005         IntvIn = Cand.IntvIdx;
1006         Cand.Intf.moveToBlock(Number);
1007         IntfIn = Cand.Intf.first();
1008       }
1009     }
1010     if (BI.LiveOut) {
1011       unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1012       if (CandOut != NoCand) {
1013         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1014         IntvOut = Cand.IntvIdx;
1015         Cand.Intf.moveToBlock(Number);
1016         IntfOut = Cand.Intf.last();
1017       }
1018     }
1019
1020     // Create separate intervals for isolated blocks with multiple uses.
1021     if (!IntvIn && !IntvOut) {
1022       DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1023       if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1024         SE->splitSingleBlock(BI);
1025       continue;
1026     }
1027
1028     if (IntvIn && IntvOut)
1029       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1030     else if (IntvIn)
1031       SE->splitRegInBlock(BI, IntvIn, IntfIn);
1032     else
1033       SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1034   }
1035
1036   // Handle live-through blocks. The relevant live-through blocks are stored in
1037   // the ActiveBlocks list with each candidate. We need to filter out
1038   // duplicates.
1039   BitVector Todo = SA->getThroughBlocks();
1040   for (unsigned c = 0; c != UsedCands.size(); ++c) {
1041     ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1042     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1043       unsigned Number = Blocks[i];
1044       if (!Todo.test(Number))
1045         continue;
1046       Todo.reset(Number);
1047
1048       unsigned IntvIn = 0, IntvOut = 0;
1049       SlotIndex IntfIn, IntfOut;
1050
1051       unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1052       if (CandIn != NoCand) {
1053         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1054         IntvIn = Cand.IntvIdx;
1055         Cand.Intf.moveToBlock(Number);
1056         IntfIn = Cand.Intf.first();
1057       }
1058
1059       unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1060       if (CandOut != NoCand) {
1061         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1062         IntvOut = Cand.IntvIdx;
1063         Cand.Intf.moveToBlock(Number);
1064         IntfOut = Cand.Intf.last();
1065       }
1066       if (!IntvIn && !IntvOut)
1067         continue;
1068       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1069     }
1070   }
1071
1072   ++NumGlobalSplits;
1073
1074   SmallVector<unsigned, 8> IntvMap;
1075   SE->finish(&IntvMap);
1076   DebugVars->splitRegister(Reg, LREdit.regs());
1077
1078   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1079   unsigned OrigBlocks = SA->getNumLiveBlocks();
1080
1081   // Sort out the new intervals created by splitting. We get four kinds:
1082   // - Remainder intervals should not be split again.
1083   // - Candidate intervals can be assigned to Cand.PhysReg.
1084   // - Block-local splits are candidates for local splitting.
1085   // - DCE leftovers should go back on the queue.
1086   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1087     LiveInterval &Reg = *LREdit.get(i);
1088
1089     // Ignore old intervals from DCE.
1090     if (getStage(Reg) != RS_New)
1091       continue;
1092
1093     // Remainder interval. Don't try splitting again, spill if it doesn't
1094     // allocate.
1095     if (IntvMap[i] == 0) {
1096       setStage(Reg, RS_Spill);
1097       continue;
1098     }
1099
1100     // Global intervals. Allow repeated splitting as long as the number of live
1101     // blocks is strictly decreasing.
1102     if (IntvMap[i] < NumGlobalIntvs) {
1103       if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1104         DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1105                      << " blocks as original.\n");
1106         // Don't allow repeated splitting as a safe guard against looping.
1107         setStage(Reg, RS_Split2);
1108       }
1109       continue;
1110     }
1111
1112     // Other intervals are treated as new. This includes local intervals created
1113     // for blocks with multiple uses, and anything created by DCE.
1114   }
1115
1116   if (VerifyEnabled)
1117     MF->verify(this, "After splitting live range around region");
1118 }
1119
1120 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1121                                   SmallVectorImpl<LiveInterval*> &NewVRegs) {
1122   unsigned NumCands = 0;
1123   unsigned BestCand = NoCand;
1124   BlockFrequency BestCost;
1125   SmallVector<unsigned, 8> UsedCands;
1126
1127   // Check if we can split this live range around a compact region.
1128   bool HasCompact = calcCompactRegion(GlobalCand.front());
1129   if (HasCompact) {
1130     // Yes, keep GlobalCand[0] as the compact region candidate.
1131     NumCands = 1;
1132     BestCost = BlockFrequency::getMaxFrequency();
1133   } else {
1134     // No benefit from the compact region, our fallback will be per-block
1135     // splitting. Make sure we find a solution that is cheaper than spilling.
1136     BestCost = calcSpillCost();
1137     DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1138   }
1139
1140   Order.rewind();
1141   while (unsigned PhysReg = Order.next()) {
1142     // Discard bad candidates before we run out of interference cache cursors.
1143     // This will only affect register classes with a lot of registers (>32).
1144     if (NumCands == IntfCache.getMaxCursors()) {
1145       unsigned WorstCount = ~0u;
1146       unsigned Worst = 0;
1147       for (unsigned i = 0; i != NumCands; ++i) {
1148         if (i == BestCand || !GlobalCand[i].PhysReg)
1149           continue;
1150         unsigned Count = GlobalCand[i].LiveBundles.count();
1151         if (Count < WorstCount)
1152           Worst = i, WorstCount = Count;
1153       }
1154       --NumCands;
1155       GlobalCand[Worst] = GlobalCand[NumCands];
1156       if (BestCand == NumCands)
1157         BestCand = Worst;
1158     }
1159
1160     if (GlobalCand.size() <= NumCands)
1161       GlobalCand.resize(NumCands+1);
1162     GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1163     Cand.reset(IntfCache, PhysReg);
1164
1165     SpillPlacer->prepare(Cand.LiveBundles);
1166     BlockFrequency Cost;
1167     if (!addSplitConstraints(Cand.Intf, Cost)) {
1168       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1169       continue;
1170     }
1171     DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1172     if (Cost >= BestCost) {
1173       DEBUG({
1174         if (BestCand == NoCand)
1175           dbgs() << " worse than no bundles\n";
1176         else
1177           dbgs() << " worse than "
1178                  << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1179       });
1180       continue;
1181     }
1182     growRegion(Cand);
1183
1184     SpillPlacer->finish();
1185
1186     // No live bundles, defer to splitSingleBlocks().
1187     if (!Cand.LiveBundles.any()) {
1188       DEBUG(dbgs() << " no bundles.\n");
1189       continue;
1190     }
1191
1192     Cost += calcGlobalSplitCost(Cand);
1193     DEBUG({
1194       dbgs() << ", total = " << Cost << " with bundles";
1195       for (int i = Cand.LiveBundles.find_first(); i>=0;
1196            i = Cand.LiveBundles.find_next(i))
1197         dbgs() << " EB#" << i;
1198       dbgs() << ".\n";
1199     });
1200     if (Cost < BestCost) {
1201       BestCand = NumCands;
1202       BestCost = Cost;
1203     }
1204     ++NumCands;
1205   }
1206
1207   // No solutions found, fall back to single block splitting.
1208   if (!HasCompact && BestCand == NoCand)
1209     return 0;
1210
1211   // Prepare split editor.
1212   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1213   SE->reset(LREdit, SplitSpillMode);
1214
1215   // Assign all edge bundles to the preferred candidate, or NoCand.
1216   BundleCand.assign(Bundles->getNumBundles(), NoCand);
1217
1218   // Assign bundles for the best candidate region.
1219   if (BestCand != NoCand) {
1220     GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1221     if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1222       UsedCands.push_back(BestCand);
1223       Cand.IntvIdx = SE->openIntv();
1224       DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1225                    << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1226       (void)B;
1227     }
1228   }
1229
1230   // Assign bundles for the compact region.
1231   if (HasCompact) {
1232     GlobalSplitCandidate &Cand = GlobalCand.front();
1233     assert(!Cand.PhysReg && "Compact region has no physreg");
1234     if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1235       UsedCands.push_back(0);
1236       Cand.IntvIdx = SE->openIntv();
1237       DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1238                    << Cand.IntvIdx << ".\n");
1239       (void)B;
1240     }
1241   }
1242
1243   splitAroundRegion(LREdit, UsedCands);
1244   return 0;
1245 }
1246
1247
1248 //===----------------------------------------------------------------------===//
1249 //                            Per-Block Splitting
1250 //===----------------------------------------------------------------------===//
1251
1252 /// tryBlockSplit - Split a global live range around every block with uses. This
1253 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1254 /// they don't allocate.
1255 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1256                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1257   assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1258   unsigned Reg = VirtReg.reg;
1259   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1260   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1261   SE->reset(LREdit, SplitSpillMode);
1262   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1263   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1264     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1265     if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1266       SE->splitSingleBlock(BI);
1267   }
1268   // No blocks were split.
1269   if (LREdit.empty())
1270     return 0;
1271
1272   // We did split for some blocks.
1273   SmallVector<unsigned, 8> IntvMap;
1274   SE->finish(&IntvMap);
1275
1276   // Tell LiveDebugVariables about the new ranges.
1277   DebugVars->splitRegister(Reg, LREdit.regs());
1278
1279   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1280
1281   // Sort out the new intervals created by splitting. The remainder interval
1282   // goes straight to spilling, the new local ranges get to stay RS_New.
1283   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1284     LiveInterval &LI = *LREdit.get(i);
1285     if (getStage(LI) == RS_New && IntvMap[i] == 0)
1286       setStage(LI, RS_Spill);
1287   }
1288
1289   if (VerifyEnabled)
1290     MF->verify(this, "After splitting live range around basic blocks");
1291   return 0;
1292 }
1293
1294
1295 //===----------------------------------------------------------------------===//
1296 //                         Per-Instruction Splitting
1297 //===----------------------------------------------------------------------===//
1298
1299 /// tryInstructionSplit - Split a live range around individual instructions.
1300 /// This is normally not worthwhile since the spiller is doing essentially the
1301 /// same thing. However, when the live range is in a constrained register
1302 /// class, it may help to insert copies such that parts of the live range can
1303 /// be moved to a larger register class.
1304 ///
1305 /// This is similar to spilling to a larger register class.
1306 unsigned
1307 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1308                               SmallVectorImpl<LiveInterval*> &NewVRegs) {
1309   // There is no point to this if there are no larger sub-classes.
1310   if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1311     return 0;
1312
1313   // Always enable split spill mode, since we're effectively spilling to a
1314   // register.
1315   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1316   SE->reset(LREdit, SplitEditor::SM_Size);
1317
1318   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1319   if (Uses.size() <= 1)
1320     return 0;
1321
1322   DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1323
1324   // Split around every non-copy instruction.
1325   for (unsigned i = 0; i != Uses.size(); ++i) {
1326     if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1327       if (MI->isFullCopy()) {
1328         DEBUG(dbgs() << "    skip:\t" << Uses[i] << '\t' << *MI);
1329         continue;
1330       }
1331     SE->openIntv();
1332     SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1333     SlotIndex SegStop  = SE->leaveIntvAfter(Uses[i]);
1334     SE->useIntv(SegStart, SegStop);
1335   }
1336
1337   if (LREdit.empty()) {
1338     DEBUG(dbgs() << "All uses were copies.\n");
1339     return 0;
1340   }
1341
1342   SmallVector<unsigned, 8> IntvMap;
1343   SE->finish(&IntvMap);
1344   DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1345   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1346
1347   // Assign all new registers to RS_Spill. This was the last chance.
1348   setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1349   return 0;
1350 }
1351
1352
1353 //===----------------------------------------------------------------------===//
1354 //                             Local Splitting
1355 //===----------------------------------------------------------------------===//
1356
1357
1358 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1359 /// in order to use PhysReg between two entries in SA->UseSlots.
1360 ///
1361 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1362 ///
1363 void RAGreedy::calcGapWeights(unsigned PhysReg,
1364                               SmallVectorImpl<float> &GapWeight) {
1365   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1366   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1367   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1368   const unsigned NumGaps = Uses.size()-1;
1369
1370   // Start and end points for the interference check.
1371   SlotIndex StartIdx =
1372     BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1373   SlotIndex StopIdx =
1374     BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1375
1376   GapWeight.assign(NumGaps, 0.0f);
1377
1378   // Add interference from each overlapping register.
1379   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1380     if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1381           .checkInterference())
1382       continue;
1383
1384     // We know that VirtReg is a continuous interval from FirstInstr to
1385     // LastInstr, so we don't need InterferenceQuery.
1386     //
1387     // Interference that overlaps an instruction is counted in both gaps
1388     // surrounding the instruction. The exception is interference before
1389     // StartIdx and after StopIdx.
1390     //
1391     LiveIntervalUnion::SegmentIter IntI =
1392       Matrix->getLiveUnions()[*Units] .find(StartIdx);
1393     for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1394       // Skip the gaps before IntI.
1395       while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1396         if (++Gap == NumGaps)
1397           break;
1398       if (Gap == NumGaps)
1399         break;
1400
1401       // Update the gaps covered by IntI.
1402       const float weight = IntI.value()->weight;
1403       for (; Gap != NumGaps; ++Gap) {
1404         GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1405         if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1406           break;
1407       }
1408       if (Gap == NumGaps)
1409         break;
1410     }
1411   }
1412
1413   // Add fixed interference.
1414   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1415     const LiveInterval &LI = LIS->getRegUnit(*Units);
1416     LiveInterval::const_iterator I = LI.find(StartIdx);
1417     LiveInterval::const_iterator E = LI.end();
1418
1419     // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1420     for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1421       while (Uses[Gap+1].getBoundaryIndex() < I->start)
1422         if (++Gap == NumGaps)
1423           break;
1424       if (Gap == NumGaps)
1425         break;
1426
1427       for (; Gap != NumGaps; ++Gap) {
1428         GapWeight[Gap] = HUGE_VALF;
1429         if (Uses[Gap+1].getBaseIndex() >= I->end)
1430           break;
1431       }
1432       if (Gap == NumGaps)
1433         break;
1434     }
1435   }
1436 }
1437
1438 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1439 /// basic block.
1440 ///
1441 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1442                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1443   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1444   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1445
1446   // Note that it is possible to have an interval that is live-in or live-out
1447   // while only covering a single block - A phi-def can use undef values from
1448   // predecessors, and the block could be a single-block loop.
1449   // We don't bother doing anything clever about such a case, we simply assume
1450   // that the interval is continuous from FirstInstr to LastInstr. We should
1451   // make sure that we don't do anything illegal to such an interval, though.
1452
1453   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1454   if (Uses.size() <= 2)
1455     return 0;
1456   const unsigned NumGaps = Uses.size()-1;
1457
1458   DEBUG({
1459     dbgs() << "tryLocalSplit: ";
1460     for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1461       dbgs() << ' ' << Uses[i];
1462     dbgs() << '\n';
1463   });
1464
1465   // If VirtReg is live across any register mask operands, compute a list of
1466   // gaps with register masks.
1467   SmallVector<unsigned, 8> RegMaskGaps;
1468   if (Matrix->checkRegMaskInterference(VirtReg)) {
1469     // Get regmask slots for the whole block.
1470     ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1471     DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1472     // Constrain to VirtReg's live range.
1473     unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1474                                    Uses.front().getRegSlot()) - RMS.begin();
1475     unsigned re = RMS.size();
1476     for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1477       // Look for Uses[i] <= RMS <= Uses[i+1].
1478       assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1479       if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1480         continue;
1481       // Skip a regmask on the same instruction as the last use. It doesn't
1482       // overlap the live range.
1483       if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1484         break;
1485       DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1486       RegMaskGaps.push_back(i);
1487       // Advance ri to the next gap. A regmask on one of the uses counts in
1488       // both gaps.
1489       while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1490         ++ri;
1491     }
1492     DEBUG(dbgs() << '\n');
1493   }
1494
1495   // Since we allow local split results to be split again, there is a risk of
1496   // creating infinite loops. It is tempting to require that the new live
1497   // ranges have less instructions than the original. That would guarantee
1498   // convergence, but it is too strict. A live range with 3 instructions can be
1499   // split 2+3 (including the COPY), and we want to allow that.
1500   //
1501   // Instead we use these rules:
1502   //
1503   // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1504   //    noop split, of course).
1505   // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1506   //    the new ranges must have fewer instructions than before the split.
1507   // 3. New ranges with the same number of instructions are marked RS_Split2,
1508   //    smaller ranges are marked RS_New.
1509   //
1510   // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1511   // excessive splitting and infinite loops.
1512   //
1513   bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1514
1515   // Best split candidate.
1516   unsigned BestBefore = NumGaps;
1517   unsigned BestAfter = 0;
1518   float BestDiff = 0;
1519
1520   const float blockFreq =
1521     SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1522     (1.0f / BlockFrequency::getEntryFrequency());
1523   SmallVector<float, 8> GapWeight;
1524
1525   Order.rewind();
1526   while (unsigned PhysReg = Order.next()) {
1527     // Keep track of the largest spill weight that would need to be evicted in
1528     // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1529     calcGapWeights(PhysReg, GapWeight);
1530
1531     // Remove any gaps with regmask clobbers.
1532     if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1533       for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1534         GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1535
1536     // Try to find the best sequence of gaps to close.
1537     // The new spill weight must be larger than any gap interference.
1538
1539     // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1540     unsigned SplitBefore = 0, SplitAfter = 1;
1541
1542     // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1543     // It is the spill weight that needs to be evicted.
1544     float MaxGap = GapWeight[0];
1545
1546     for (;;) {
1547       // Live before/after split?
1548       const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1549       const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1550
1551       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1552                    << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1553                    << " i=" << MaxGap);
1554
1555       // Stop before the interval gets so big we wouldn't be making progress.
1556       if (!LiveBefore && !LiveAfter) {
1557         DEBUG(dbgs() << " all\n");
1558         break;
1559       }
1560       // Should the interval be extended or shrunk?
1561       bool Shrink = true;
1562
1563       // How many gaps would the new range have?
1564       unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1565
1566       // Legally, without causing looping?
1567       bool Legal = !ProgressRequired || NewGaps < NumGaps;
1568
1569       if (Legal && MaxGap < HUGE_VALF) {
1570         // Estimate the new spill weight. Each instruction reads or writes the
1571         // register. Conservatively assume there are no read-modify-write
1572         // instructions.
1573         //
1574         // Try to guess the size of the new interval.
1575         const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1576                                  Uses[SplitBefore].distance(Uses[SplitAfter]) +
1577                                  (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1578         // Would this split be possible to allocate?
1579         // Never allocate all gaps, we wouldn't be making progress.
1580         DEBUG(dbgs() << " w=" << EstWeight);
1581         if (EstWeight * Hysteresis >= MaxGap) {
1582           Shrink = false;
1583           float Diff = EstWeight - MaxGap;
1584           if (Diff > BestDiff) {
1585             DEBUG(dbgs() << " (best)");
1586             BestDiff = Hysteresis * Diff;
1587             BestBefore = SplitBefore;
1588             BestAfter = SplitAfter;
1589           }
1590         }
1591       }
1592
1593       // Try to shrink.
1594       if (Shrink) {
1595         if (++SplitBefore < SplitAfter) {
1596           DEBUG(dbgs() << " shrink\n");
1597           // Recompute the max when necessary.
1598           if (GapWeight[SplitBefore - 1] >= MaxGap) {
1599             MaxGap = GapWeight[SplitBefore];
1600             for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1601               MaxGap = std::max(MaxGap, GapWeight[i]);
1602           }
1603           continue;
1604         }
1605         MaxGap = 0;
1606       }
1607
1608       // Try to extend the interval.
1609       if (SplitAfter >= NumGaps) {
1610         DEBUG(dbgs() << " end\n");
1611         break;
1612       }
1613
1614       DEBUG(dbgs() << " extend\n");
1615       MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1616     }
1617   }
1618
1619   // Didn't find any candidates?
1620   if (BestBefore == NumGaps)
1621     return 0;
1622
1623   DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1624                << '-' << Uses[BestAfter] << ", " << BestDiff
1625                << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1626
1627   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1628   SE->reset(LREdit);
1629
1630   SE->openIntv();
1631   SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1632   SlotIndex SegStop  = SE->leaveIntvAfter(Uses[BestAfter]);
1633   SE->useIntv(SegStart, SegStop);
1634   SmallVector<unsigned, 8> IntvMap;
1635   SE->finish(&IntvMap);
1636   DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1637
1638   // If the new range has the same number of instructions as before, mark it as
1639   // RS_Split2 so the next split will be forced to make progress. Otherwise,
1640   // leave the new intervals as RS_New so they can compete.
1641   bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1642   bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1643   unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1644   if (NewGaps >= NumGaps) {
1645     DEBUG(dbgs() << "Tagging non-progress ranges: ");
1646     assert(!ProgressRequired && "Didn't make progress when it was required.");
1647     for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1648       if (IntvMap[i] == 1) {
1649         setStage(*LREdit.get(i), RS_Split2);
1650         DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1651       }
1652     DEBUG(dbgs() << '\n');
1653   }
1654   ++NumLocalSplits;
1655
1656   return 0;
1657 }
1658
1659 //===----------------------------------------------------------------------===//
1660 //                          Live Range Splitting
1661 //===----------------------------------------------------------------------===//
1662
1663 /// trySplit - Try to split VirtReg or one of its interferences, making it
1664 /// assignable.
1665 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1666 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1667                             SmallVectorImpl<LiveInterval*>&NewVRegs) {
1668   // Ranges must be Split2 or less.
1669   if (getStage(VirtReg) >= RS_Spill)
1670     return 0;
1671
1672   // Local intervals are handled separately.
1673   if (LIS->intervalIsInOneMBB(VirtReg)) {
1674     NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1675     SA->analyze(&VirtReg);
1676     unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1677     if (PhysReg || !NewVRegs.empty())
1678       return PhysReg;
1679     return tryInstructionSplit(VirtReg, Order, NewVRegs);
1680   }
1681
1682   NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1683
1684   SA->analyze(&VirtReg);
1685
1686   // FIXME: SplitAnalysis may repair broken live ranges coming from the
1687   // coalescer. That may cause the range to become allocatable which means that
1688   // tryRegionSplit won't be making progress. This check should be replaced with
1689   // an assertion when the coalescer is fixed.
1690   if (SA->didRepairRange()) {
1691     // VirtReg has changed, so all cached queries are invalid.
1692     Matrix->invalidateVirtRegs();
1693     if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1694       return PhysReg;
1695   }
1696
1697   // First try to split around a region spanning multiple blocks. RS_Split2
1698   // ranges already made dubious progress with region splitting, so they go
1699   // straight to single block splitting.
1700   if (getStage(VirtReg) < RS_Split2) {
1701     unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1702     if (PhysReg || !NewVRegs.empty())
1703       return PhysReg;
1704   }
1705
1706   // Then isolate blocks.
1707   return tryBlockSplit(VirtReg, Order, NewVRegs);
1708 }
1709
1710
1711 //===----------------------------------------------------------------------===//
1712 //                            Main Entry Point
1713 //===----------------------------------------------------------------------===//
1714
1715 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1716                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1717   // First try assigning a free register.
1718   AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1719   if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1720     return PhysReg;
1721
1722   LiveRangeStage Stage = getStage(VirtReg);
1723   DEBUG(dbgs() << StageName[Stage]
1724                << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1725
1726   // Try to evict a less worthy live range, but only for ranges from the primary
1727   // queue. The RS_Split ranges already failed to do this, and they should not
1728   // get a second chance until they have been split.
1729   if (Stage != RS_Split)
1730     if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1731       return PhysReg;
1732
1733   assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1734
1735   // The first time we see a live range, don't try to split or spill.
1736   // Wait until the second time, when all smaller ranges have been allocated.
1737   // This gives a better picture of the interference to split around.
1738   if (Stage < RS_Split) {
1739     setStage(VirtReg, RS_Split);
1740     DEBUG(dbgs() << "wait for second round\n");
1741     NewVRegs.push_back(&VirtReg);
1742     return 0;
1743   }
1744
1745   // If we couldn't allocate a register from spilling, there is probably some
1746   // invalid inline assembly. The base class wil report it.
1747   if (Stage >= RS_Done || !VirtReg.isSpillable())
1748     return ~0u;
1749
1750   // Try splitting VirtReg or interferences.
1751   unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1752   if (PhysReg || !NewVRegs.empty())
1753     return PhysReg;
1754
1755   // Finally spill VirtReg itself.
1756   NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1757   LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1758   spiller().spill(LRE);
1759   setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1760
1761   if (VerifyEnabled)
1762     MF->verify(this, "After spilling");
1763
1764   // The live virtual register requesting allocation was spilled, so tell
1765   // the caller not to allocate anything during this round.
1766   return 0;
1767 }
1768
1769 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1770   DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1771                << "********** Function: " << mf.getName() << '\n');
1772
1773   MF = &mf;
1774   if (VerifyEnabled)
1775     MF->verify(this, "Before greedy register allocator");
1776
1777   RegAllocBase::init(getAnalysis<VirtRegMap>(),
1778                      getAnalysis<LiveIntervals>(),
1779                      getAnalysis<LiveRegMatrix>());
1780   Indexes = &getAnalysis<SlotIndexes>();
1781   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1782   DomTree = &getAnalysis<MachineDominatorTree>();
1783   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1784   Loops = &getAnalysis<MachineLoopInfo>();
1785   Bundles = &getAnalysis<EdgeBundles>();
1786   SpillPlacer = &getAnalysis<SpillPlacement>();
1787   DebugVars = &getAnalysis<LiveDebugVariables>();
1788
1789   DEBUG(LIS->dump());
1790
1791   SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1792   SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
1793   ExtraRegInfo.clear();
1794   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1795   NextCascade = 1;
1796   IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
1797   GlobalCand.resize(32);  // This will grow as needed.
1798
1799   allocatePhysRegs();
1800   releaseMemory();
1801   return true;
1802 }