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