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