[RegAllocGreedy][Last Chance Recoloring] Change the name of the exhaustive search...
[oota-llvm.git] / lib / CodeGen / RegAllocGreedy.cpp
1 //===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the RAGreedy function pass for register allocation in
11 // optimized builds.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "regalloc"
16 #include "llvm/CodeGen/Passes.h"
17 #include "AllocationOrder.h"
18 #include "InterferenceCache.h"
19 #include "LiveDebugVariables.h"
20 #include "RegAllocBase.h"
21 #include "SpillPlacement.h"
22 #include "Spiller.h"
23 #include "SplitKit.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/CodeGen/CalcSpillWeights.h"
27 #include "llvm/CodeGen/EdgeBundles.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveRangeEdit.h"
30 #include "llvm/CodeGen/LiveRegMatrix.h"
31 #include "llvm/CodeGen/LiveStackAnalysis.h"
32 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
33 #include "llvm/CodeGen/MachineDominators.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/RegAllocRegistry.h"
38 #include "llvm/CodeGen/RegisterClassInfo.h"
39 #include "llvm/CodeGen/VirtRegMap.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/PassAnalysisSupport.h"
42 #include "llvm/Support/BranchProbability.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <queue>
49
50 using namespace llvm;
51
52 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
53 STATISTIC(NumLocalSplits,  "Number of split local live ranges");
54 STATISTIC(NumEvicted,      "Number of interferences evicted");
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 cl::opt<unsigned>
66 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
67                              cl::desc("Last chance recoloring max depth"),
68                              cl::init(5));
69
70 static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
71     "lcr-max-interf", cl::Hidden,
72     cl::desc("Last chance recoloring maximum number of considered"
73              " interference at a time"),
74     cl::init(8));
75
76 static cl::opt<bool>
77 ExhaustiveSearch("exhaustive-register-search", cl::NotHidden,
78                  cl::desc("Exhaustive Search for registers bypassing the depth "
79                           "and interference cutoffs of last chance recoloring"));
80
81 // FIXME: Find a good default for this flag and remove the flag.
82 static cl::opt<unsigned>
83 CSRFirstTimeCost("regalloc-csr-first-time-cost",
84               cl::desc("Cost for first time use of callee-saved register."),
85               cl::init(0), cl::Hidden);
86
87 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
88                                        createGreedyRegisterAllocator);
89
90 namespace {
91 class RAGreedy : public MachineFunctionPass,
92                  public RegAllocBase,
93                  private LiveRangeEdit::Delegate {
94   // Convenient shortcuts.
95   typedef std::priority_queue<std::pair<unsigned, unsigned> > PQueue;
96   typedef SmallPtrSet<LiveInterval *, 4> SmallLISet;
97   typedef SmallSet<unsigned, 16> SmallVirtRegSet;
98
99   // context
100   MachineFunction *MF;
101
102   // Shortcuts to some useful interface.
103   const TargetInstrInfo *TII;
104   const TargetRegisterInfo *TRI;
105   RegisterClassInfo RCI;
106
107   // analyses
108   SlotIndexes *Indexes;
109   MachineBlockFrequencyInfo *MBFI;
110   MachineDominatorTree *DomTree;
111   MachineLoopInfo *Loops;
112   EdgeBundles *Bundles;
113   SpillPlacement *SpillPlacer;
114   LiveDebugVariables *DebugVars;
115
116   // state
117   std::unique_ptr<Spiller> SpillerInstance;
118   PQueue Queue;
119   unsigned NextCascade;
120
121   // Live ranges pass through a number of stages as we try to allocate them.
122   // Some of the stages may also create new live ranges:
123   //
124   // - Region splitting.
125   // - Per-block splitting.
126   // - Local splitting.
127   // - Spilling.
128   //
129   // Ranges produced by one of the stages skip the previous stages when they are
130   // dequeued. This improves performance because we can skip interference checks
131   // that are unlikely to give any results. It also guarantees that the live
132   // range splitting algorithm terminates, something that is otherwise hard to
133   // ensure.
134   enum LiveRangeStage {
135     /// Newly created live range that has never been queued.
136     RS_New,
137
138     /// Only attempt assignment and eviction. Then requeue as RS_Split.
139     RS_Assign,
140
141     /// Attempt live range splitting if assignment is impossible.
142     RS_Split,
143
144     /// Attempt more aggressive live range splitting that is guaranteed to make
145     /// progress.  This is used for split products that may not be making
146     /// progress.
147     RS_Split2,
148
149     /// Live range will be spilled.  No more splitting will be attempted.
150     RS_Spill,
151
152     /// There is nothing more we can do to this live range.  Abort compilation
153     /// if it can't be assigned.
154     RS_Done
155   };
156
157   // Enum CutOffStage to keep a track whether the register allocation failed
158   // because of the cutoffs encountered in last chance recoloring.
159   // Note: This is used as bitmask. New value should be next power of 2.
160   enum CutOffStage {
161     // No cutoffs encountered
162     CO_None = 0,
163
164     // lcr-max-depth cutoff encountered
165     CO_Depth = 1,
166
167     // lcr-max-interf cutoff encountered
168     CO_Interf = 2
169   };
170
171   uint8_t CutOffInfo;
172
173 #ifndef NDEBUG
174   static const char *const StageName[];
175 #endif
176
177   // RegInfo - Keep additional information about each live range.
178   struct RegInfo {
179     LiveRangeStage Stage;
180
181     // Cascade - Eviction loop prevention. See canEvictInterference().
182     unsigned Cascade;
183
184     RegInfo() : Stage(RS_New), Cascade(0) {}
185   };
186
187   IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
188
189   LiveRangeStage getStage(const LiveInterval &VirtReg) const {
190     return ExtraRegInfo[VirtReg.reg].Stage;
191   }
192
193   void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
194     ExtraRegInfo.resize(MRI->getNumVirtRegs());
195     ExtraRegInfo[VirtReg.reg].Stage = Stage;
196   }
197
198   template<typename Iterator>
199   void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
200     ExtraRegInfo.resize(MRI->getNumVirtRegs());
201     for (;Begin != End; ++Begin) {
202       unsigned Reg = *Begin;
203       if (ExtraRegInfo[Reg].Stage == RS_New)
204         ExtraRegInfo[Reg].Stage = NewStage;
205     }
206   }
207
208   /// Cost of evicting interference.
209   struct EvictionCost {
210     unsigned BrokenHints; ///< Total number of broken hints.
211     float MaxWeight;      ///< Maximum spill weight evicted.
212
213     EvictionCost(): BrokenHints(0), MaxWeight(0) {}
214
215     bool isMax() const { return BrokenHints == ~0u; }
216
217     void setMax() { BrokenHints = ~0u; }
218
219     void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
220
221     bool operator<(const EvictionCost &O) const {
222       return std::tie(BrokenHints, MaxWeight) <
223              std::tie(O.BrokenHints, O.MaxWeight);
224     }
225   };
226
227   // splitting state.
228   std::unique_ptr<SplitAnalysis> SA;
229   std::unique_ptr<SplitEditor> SE;
230
231   /// Cached per-block interference maps
232   InterferenceCache IntfCache;
233
234   /// All basic blocks where the current register has uses.
235   SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
236
237   /// Global live range splitting candidate info.
238   struct GlobalSplitCandidate {
239     // Register intended for assignment, or 0.
240     unsigned PhysReg;
241
242     // SplitKit interval index for this candidate.
243     unsigned IntvIdx;
244
245     // Interference for PhysReg.
246     InterferenceCache::Cursor Intf;
247
248     // Bundles where this candidate should be live.
249     BitVector LiveBundles;
250     SmallVector<unsigned, 8> ActiveBlocks;
251
252     void reset(InterferenceCache &Cache, unsigned Reg) {
253       PhysReg = Reg;
254       IntvIdx = 0;
255       Intf.setPhysReg(Cache, Reg);
256       LiveBundles.clear();
257       ActiveBlocks.clear();
258     }
259
260     // Set B[i] = C for every live bundle where B[i] was NoCand.
261     unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
262       unsigned Count = 0;
263       for (int i = LiveBundles.find_first(); i >= 0;
264            i = LiveBundles.find_next(i))
265         if (B[i] == NoCand) {
266           B[i] = C;
267           Count++;
268         }
269       return Count;
270     }
271   };
272
273   /// Candidate info for each PhysReg in AllocationOrder.
274   /// This vector never shrinks, but grows to the size of the largest register
275   /// class.
276   SmallVector<GlobalSplitCandidate, 32> GlobalCand;
277
278   enum : unsigned { NoCand = ~0u };
279
280   /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
281   /// NoCand which indicates the stack interval.
282   SmallVector<unsigned, 32> BundleCand;
283
284   /// Callee-save register cost, calculated once per machine function.
285   BlockFrequency CSRCost;
286
287 public:
288   RAGreedy();
289
290   /// Return the pass name.
291   const char* getPassName() const override {
292     return "Greedy Register Allocator";
293   }
294
295   /// RAGreedy analysis usage.
296   void getAnalysisUsage(AnalysisUsage &AU) const override;
297   void releaseMemory() override;
298   Spiller &spiller() override { return *SpillerInstance; }
299   void enqueue(LiveInterval *LI) override;
300   LiveInterval *dequeue() override;
301   unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
302
303   /// Perform register allocation.
304   bool runOnMachineFunction(MachineFunction &mf) override;
305
306   static char ID;
307
308 private:
309   unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
310                              SmallVirtRegSet &, unsigned = 0);
311
312   bool LRE_CanEraseVirtReg(unsigned) override;
313   void LRE_WillShrinkVirtReg(unsigned) override;
314   void LRE_DidCloneVirtReg(unsigned, unsigned) override;
315   void enqueue(PQueue &CurQueue, LiveInterval *LI);
316   LiveInterval *dequeue(PQueue &CurQueue);
317
318   BlockFrequency calcSpillCost();
319   bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
320   void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
321   void growRegion(GlobalSplitCandidate &Cand);
322   BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
323   bool calcCompactRegion(GlobalSplitCandidate&);
324   void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
325   void calcGapWeights(unsigned, SmallVectorImpl<float>&);
326   unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
327   bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
328   bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
329   void evictInterference(LiveInterval&, unsigned,
330                          SmallVectorImpl<unsigned>&);
331   bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
332                                   SmallLISet &RecoloringCandidates,
333                                   const SmallVirtRegSet &FixedRegisters);
334
335   unsigned tryAssign(LiveInterval&, AllocationOrder&,
336                      SmallVectorImpl<unsigned>&);
337   unsigned tryEvict(LiveInterval&, AllocationOrder&,
338                     SmallVectorImpl<unsigned>&, unsigned = ~0u);
339   unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
340                           SmallVectorImpl<unsigned>&);
341   /// Calculate cost of region splitting.
342   unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
343                                     AllocationOrder &Order,
344                                     BlockFrequency &BestCost,
345                                     unsigned &NumCands, bool IgnoreCSR);
346   /// Perform region splitting.
347   unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
348                          bool HasCompact,
349                          SmallVectorImpl<unsigned> &NewVRegs);
350   /// Check other options before using a callee-saved register for the first
351   /// time.
352   unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
353                                  unsigned PhysReg, unsigned &CostPerUseLimit,
354                                  SmallVectorImpl<unsigned> &NewVRegs);
355   void initializeCSRCost();
356   unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
357                          SmallVectorImpl<unsigned>&);
358   unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
359                                SmallVectorImpl<unsigned>&);
360   unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
361     SmallVectorImpl<unsigned>&);
362   unsigned trySplit(LiveInterval&, AllocationOrder&,
363                     SmallVectorImpl<unsigned>&);
364   unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
365                                    SmallVectorImpl<unsigned> &,
366                                    SmallVirtRegSet &, unsigned);
367   bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
368                                SmallVirtRegSet &, unsigned);
369 };
370 } // end anonymous namespace
371
372 char RAGreedy::ID = 0;
373
374 #ifndef NDEBUG
375 const char *const RAGreedy::StageName[] = {
376     "RS_New",
377     "RS_Assign",
378     "RS_Split",
379     "RS_Split2",
380     "RS_Spill",
381     "RS_Done"
382 };
383 #endif
384
385 // Hysteresis to use when comparing floats.
386 // This helps stabilize decisions based on float comparisons.
387 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
388
389
390 FunctionPass* llvm::createGreedyRegisterAllocator() {
391   return new RAGreedy();
392 }
393
394 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
395   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
396   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
397   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
398   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
399   initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
400   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
401   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
402   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
403   initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
404   initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
405   initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
406   initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
407   initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
408 }
409
410 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
411   AU.setPreservesCFG();
412   AU.addRequired<MachineBlockFrequencyInfo>();
413   AU.addPreserved<MachineBlockFrequencyInfo>();
414   AU.addRequired<AliasAnalysis>();
415   AU.addPreserved<AliasAnalysis>();
416   AU.addRequired<LiveIntervals>();
417   AU.addPreserved<LiveIntervals>();
418   AU.addRequired<SlotIndexes>();
419   AU.addPreserved<SlotIndexes>();
420   AU.addRequired<LiveDebugVariables>();
421   AU.addPreserved<LiveDebugVariables>();
422   AU.addRequired<LiveStacks>();
423   AU.addPreserved<LiveStacks>();
424   AU.addRequired<MachineDominatorTree>();
425   AU.addPreserved<MachineDominatorTree>();
426   AU.addRequired<MachineLoopInfo>();
427   AU.addPreserved<MachineLoopInfo>();
428   AU.addRequired<VirtRegMap>();
429   AU.addPreserved<VirtRegMap>();
430   AU.addRequired<LiveRegMatrix>();
431   AU.addPreserved<LiveRegMatrix>();
432   AU.addRequired<EdgeBundles>();
433   AU.addRequired<SpillPlacement>();
434   MachineFunctionPass::getAnalysisUsage(AU);
435 }
436
437
438 //===----------------------------------------------------------------------===//
439 //                     LiveRangeEdit delegate methods
440 //===----------------------------------------------------------------------===//
441
442 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
443   if (VRM->hasPhys(VirtReg)) {
444     Matrix->unassign(LIS->getInterval(VirtReg));
445     return true;
446   }
447   // Unassigned virtreg is probably in the priority queue.
448   // RegAllocBase will erase it after dequeueing.
449   return false;
450 }
451
452 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
453   if (!VRM->hasPhys(VirtReg))
454     return;
455
456   // Register is assigned, put it back on the queue for reassignment.
457   LiveInterval &LI = LIS->getInterval(VirtReg);
458   Matrix->unassign(LI);
459   enqueue(&LI);
460 }
461
462 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
463   // Cloning a register we haven't even heard about yet?  Just ignore it.
464   if (!ExtraRegInfo.inBounds(Old))
465     return;
466
467   // LRE may clone a virtual register because dead code elimination causes it to
468   // be split into connected components. The new components are much smaller
469   // than the original, so they should get a new chance at being assigned.
470   // same stage as the parent.
471   ExtraRegInfo[Old].Stage = RS_Assign;
472   ExtraRegInfo.grow(New);
473   ExtraRegInfo[New] = ExtraRegInfo[Old];
474 }
475
476 void RAGreedy::releaseMemory() {
477   SpillerInstance.reset(0);
478   ExtraRegInfo.clear();
479   GlobalCand.clear();
480 }
481
482 void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
483
484 void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
485   // Prioritize live ranges by size, assigning larger ranges first.
486   // The queue holds (size, reg) pairs.
487   const unsigned Size = LI->getSize();
488   const unsigned Reg = LI->reg;
489   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
490          "Can only enqueue virtual registers");
491   unsigned Prio;
492
493   ExtraRegInfo.grow(Reg);
494   if (ExtraRegInfo[Reg].Stage == RS_New)
495     ExtraRegInfo[Reg].Stage = RS_Assign;
496
497   if (ExtraRegInfo[Reg].Stage == RS_Split) {
498     // Unsplit ranges that couldn't be allocated immediately are deferred until
499     // everything else has been allocated.
500     Prio = Size;
501   } else {
502     // Giant live ranges fall back to the global assignment heuristic, which
503     // prevents excessive spilling in pathological cases.
504     bool ReverseLocal = TRI->reverseLocalAssignment();
505     bool ForceGlobal = !ReverseLocal && TRI->mayOverrideLocalAssignment() &&
506       (Size / SlotIndex::InstrDist) > (2 * MRI->getRegClass(Reg)->getNumRegs());
507
508     if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
509         LIS->intervalIsInOneMBB(*LI)) {
510       // Allocate original local ranges in linear instruction order. Since they
511       // are singly defined, this produces optimal coloring in the absence of
512       // global interference and other constraints.
513       if (!ReverseLocal)
514         Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
515       else {
516         // Allocating bottom up may allow many short LRGs to be assigned first
517         // to one of the cheap registers. This could be much faster for very
518         // large blocks on targets with many physical registers.
519         Prio = Indexes->getZeroIndex().getInstrDistance(LI->beginIndex());
520       }
521     }
522     else {
523       // Allocate global and split ranges in long->short order. Long ranges that
524       // don't fit should be spilled (or split) ASAP so they don't create
525       // interference.  Mark a bit to prioritize global above local ranges.
526       Prio = (1u << 29) + Size;
527     }
528     // Mark a higher bit to prioritize global and local above RS_Split.
529     Prio |= (1u << 31);
530
531     // Boost ranges that have a physical register hint.
532     if (VRM->hasKnownPreference(Reg))
533       Prio |= (1u << 30);
534   }
535   // The virtual register number is a tie breaker for same-sized ranges.
536   // Give lower vreg numbers higher priority to assign them first.
537   CurQueue.push(std::make_pair(Prio, ~Reg));
538 }
539
540 LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
541
542 LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
543   if (CurQueue.empty())
544     return 0;
545   LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
546   CurQueue.pop();
547   return LI;
548 }
549
550
551 //===----------------------------------------------------------------------===//
552 //                            Direct Assignment
553 //===----------------------------------------------------------------------===//
554
555 /// tryAssign - Try to assign VirtReg to an available register.
556 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
557                              AllocationOrder &Order,
558                              SmallVectorImpl<unsigned> &NewVRegs) {
559   Order.rewind();
560   unsigned PhysReg;
561   while ((PhysReg = Order.next()))
562     if (!Matrix->checkInterference(VirtReg, PhysReg))
563       break;
564   if (!PhysReg || Order.isHint())
565     return PhysReg;
566
567   // PhysReg is available, but there may be a better choice.
568
569   // If we missed a simple hint, try to cheaply evict interference from the
570   // preferred register.
571   if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
572     if (Order.isHint(Hint)) {
573       DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
574       EvictionCost MaxCost;
575       MaxCost.setBrokenHints(1);
576       if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
577         evictInterference(VirtReg, Hint, NewVRegs);
578         return Hint;
579       }
580     }
581
582   // Try to evict interference from a cheaper alternative.
583   unsigned Cost = TRI->getCostPerUse(PhysReg);
584
585   // Most registers have 0 additional cost.
586   if (!Cost)
587     return PhysReg;
588
589   DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
590                << '\n');
591   unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
592   return CheapReg ? CheapReg : PhysReg;
593 }
594
595
596 //===----------------------------------------------------------------------===//
597 //                         Interference eviction
598 //===----------------------------------------------------------------------===//
599
600 unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
601   AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
602   unsigned PhysReg;
603   while ((PhysReg = Order.next())) {
604     if (PhysReg == PrevReg)
605       continue;
606
607     MCRegUnitIterator Units(PhysReg, TRI);
608     for (; Units.isValid(); ++Units) {
609       // Instantiate a "subquery", not to be confused with the Queries array.
610       LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
611       if (subQ.checkInterference())
612         break;
613     }
614     // If no units have interference, break out with the current PhysReg.
615     if (!Units.isValid())
616       break;
617   }
618   if (PhysReg)
619     DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
620           << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
621           << '\n');
622   return PhysReg;
623 }
624
625 /// shouldEvict - determine if A should evict the assigned live range B. The
626 /// eviction policy defined by this function together with the allocation order
627 /// defined by enqueue() decides which registers ultimately end up being split
628 /// and spilled.
629 ///
630 /// Cascade numbers are used to prevent infinite loops if this function is a
631 /// cyclic relation.
632 ///
633 /// @param A          The live range to be assigned.
634 /// @param IsHint     True when A is about to be assigned to its preferred
635 ///                   register.
636 /// @param B          The live range to be evicted.
637 /// @param BreaksHint True when B is already assigned to its preferred register.
638 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
639                            LiveInterval &B, bool BreaksHint) {
640   bool CanSplit = getStage(B) < RS_Spill;
641
642   // Be fairly aggressive about following hints as long as the evictee can be
643   // split.
644   if (CanSplit && IsHint && !BreaksHint)
645     return true;
646
647   if (A.weight > B.weight) {
648     DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
649     return true;
650   }
651   return false;
652 }
653
654 /// canEvictInterference - Return true if all interferences between VirtReg and
655 /// PhysReg can be evicted.
656 ///
657 /// @param VirtReg Live range that is about to be assigned.
658 /// @param PhysReg Desired register for assignment.
659 /// @param IsHint  True when PhysReg is VirtReg's preferred register.
660 /// @param MaxCost Only look for cheaper candidates and update with new cost
661 ///                when returning true.
662 /// @returns True when interference can be evicted cheaper than MaxCost.
663 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
664                                     bool IsHint, EvictionCost &MaxCost) {
665   // It is only possible to evict virtual register interference.
666   if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
667     return false;
668
669   bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
670
671   // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
672   // involved in an eviction before. If a cascade number was assigned, deny
673   // evicting anything with the same or a newer cascade number. This prevents
674   // infinite eviction loops.
675   //
676   // This works out so a register without a cascade number is allowed to evict
677   // anything, and it can be evicted by anything.
678   unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
679   if (!Cascade)
680     Cascade = NextCascade;
681
682   EvictionCost Cost;
683   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
684     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
685     // If there is 10 or more interferences, chances are one is heavier.
686     if (Q.collectInterferingVRegs(10) >= 10)
687       return false;
688
689     // Check if any interfering live range is heavier than MaxWeight.
690     for (unsigned i = Q.interferingVRegs().size(); i; --i) {
691       LiveInterval *Intf = Q.interferingVRegs()[i - 1];
692       assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
693              "Only expecting virtual register interference from query");
694       // Never evict spill products. They cannot split or spill.
695       if (getStage(*Intf) == RS_Done)
696         return false;
697       // Once a live range becomes small enough, it is urgent that we find a
698       // register for it. This is indicated by an infinite spill weight. These
699       // urgent live ranges get to evict almost anything.
700       //
701       // Also allow urgent evictions of unspillable ranges from a strictly
702       // larger allocation order.
703       bool Urgent = !VirtReg.isSpillable() &&
704         (Intf->isSpillable() ||
705          RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
706          RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
707       // Only evict older cascades or live ranges without a cascade.
708       unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
709       if (Cascade <= IntfCascade) {
710         if (!Urgent)
711           return false;
712         // We permit breaking cascades for urgent evictions. It should be the
713         // last resort, though, so make it really expensive.
714         Cost.BrokenHints += 10;
715       }
716       // Would this break a satisfied hint?
717       bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
718       // Update eviction cost.
719       Cost.BrokenHints += BreaksHint;
720       Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
721       // Abort if this would be too expensive.
722       if (!(Cost < MaxCost))
723         return false;
724       if (Urgent)
725         continue;
726       // Apply the eviction policy for non-urgent evictions.
727       if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
728         return false;
729       // If !MaxCost.isMax(), then we're just looking for a cheap register.
730       // Evicting another local live range in this case could lead to suboptimal
731       // coloring.
732       if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
733           !canReassign(*Intf, PhysReg)) {
734         return false;
735       }
736     }
737   }
738   MaxCost = Cost;
739   return true;
740 }
741
742 /// evictInterference - Evict any interferring registers that prevent VirtReg
743 /// from being assigned to Physreg. This assumes that canEvictInterference
744 /// returned true.
745 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
746                                  SmallVectorImpl<unsigned> &NewVRegs) {
747   // Make sure that VirtReg has a cascade number, and assign that cascade
748   // number to every evicted register. These live ranges than then only be
749   // evicted by a newer cascade, preventing infinite loops.
750   unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
751   if (!Cascade)
752     Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
753
754   DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
755                << " interference: Cascade " << Cascade << '\n');
756
757   // Collect all interfering virtregs first.
758   SmallVector<LiveInterval*, 8> Intfs;
759   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
760     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
761     assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
762     ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
763     Intfs.append(IVR.begin(), IVR.end());
764   }
765
766   // Evict them second. This will invalidate the queries.
767   for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
768     LiveInterval *Intf = Intfs[i];
769     // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
770     if (!VRM->hasPhys(Intf->reg))
771       continue;
772     Matrix->unassign(*Intf);
773     assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
774             VirtReg.isSpillable() < Intf->isSpillable()) &&
775            "Cannot decrease cascade number, illegal eviction");
776     ExtraRegInfo[Intf->reg].Cascade = Cascade;
777     ++NumEvicted;
778     NewVRegs.push_back(Intf->reg);
779   }
780 }
781
782 /// tryEvict - Try to evict all interferences for a physreg.
783 /// @param  VirtReg Currently unassigned virtual register.
784 /// @param  Order   Physregs to try.
785 /// @return         Physreg to assign VirtReg, or 0.
786 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
787                             AllocationOrder &Order,
788                             SmallVectorImpl<unsigned> &NewVRegs,
789                             unsigned CostPerUseLimit) {
790   NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
791
792   // Keep track of the cheapest interference seen so far.
793   EvictionCost BestCost;
794   BestCost.setMax();
795   unsigned BestPhys = 0;
796   unsigned OrderLimit = Order.getOrder().size();
797
798   // When we are just looking for a reduced cost per use, don't break any
799   // hints, and only evict smaller spill weights.
800   if (CostPerUseLimit < ~0u) {
801     BestCost.BrokenHints = 0;
802     BestCost.MaxWeight = VirtReg.weight;
803
804     // Check of any registers in RC are below CostPerUseLimit.
805     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
806     unsigned MinCost = RegClassInfo.getMinCost(RC);
807     if (MinCost >= CostPerUseLimit) {
808       DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
809                    << ", no cheaper registers to be found.\n");
810       return 0;
811     }
812
813     // It is normal for register classes to have a long tail of registers with
814     // the same cost. We don't need to look at them if they're too expensive.
815     if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
816       OrderLimit = RegClassInfo.getLastCostChange(RC);
817       DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
818     }
819   }
820
821   Order.rewind();
822   while (unsigned PhysReg = Order.next(OrderLimit)) {
823     if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
824       continue;
825     // The first use of a callee-saved register in a function has cost 1.
826     // Don't start using a CSR when the CostPerUseLimit is low.
827     if (CostPerUseLimit == 1)
828      if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
829        if (!MRI->isPhysRegUsed(CSR)) {
830          DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
831                       << PrintReg(CSR, TRI) << '\n');
832          continue;
833        }
834
835     if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
836       continue;
837
838     // Best so far.
839     BestPhys = PhysReg;
840
841     // Stop if the hint can be used.
842     if (Order.isHint())
843       break;
844   }
845
846   if (!BestPhys)
847     return 0;
848
849   evictInterference(VirtReg, BestPhys, NewVRegs);
850   return BestPhys;
851 }
852
853
854 //===----------------------------------------------------------------------===//
855 //                              Region Splitting
856 //===----------------------------------------------------------------------===//
857
858 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
859 /// interference pattern in Physreg and its aliases. Add the constraints to
860 /// SpillPlacement and return the static cost of this split in Cost, assuming
861 /// that all preferences in SplitConstraints are met.
862 /// Return false if there are no bundles with positive bias.
863 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
864                                    BlockFrequency &Cost) {
865   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
866
867   // Reset interference dependent info.
868   SplitConstraints.resize(UseBlocks.size());
869   BlockFrequency StaticCost = 0;
870   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
871     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
872     SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
873
874     BC.Number = BI.MBB->getNumber();
875     Intf.moveToBlock(BC.Number);
876     BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
877     BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
878     BC.ChangesValue = BI.FirstDef.isValid();
879
880     if (!Intf.hasInterference())
881       continue;
882
883     // Number of spill code instructions to insert.
884     unsigned Ins = 0;
885
886     // Interference for the live-in value.
887     if (BI.LiveIn) {
888       if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
889         BC.Entry = SpillPlacement::MustSpill, ++Ins;
890       else if (Intf.first() < BI.FirstInstr)
891         BC.Entry = SpillPlacement::PrefSpill, ++Ins;
892       else if (Intf.first() < BI.LastInstr)
893         ++Ins;
894     }
895
896     // Interference for the live-out value.
897     if (BI.LiveOut) {
898       if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
899         BC.Exit = SpillPlacement::MustSpill, ++Ins;
900       else if (Intf.last() > BI.LastInstr)
901         BC.Exit = SpillPlacement::PrefSpill, ++Ins;
902       else if (Intf.last() > BI.FirstInstr)
903         ++Ins;
904     }
905
906     // Accumulate the total frequency of inserted spill code.
907     while (Ins--)
908       StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
909   }
910   Cost = StaticCost;
911
912   // Add constraints for use-blocks. Note that these are the only constraints
913   // that may add a positive bias, it is downhill from here.
914   SpillPlacer->addConstraints(SplitConstraints);
915   return SpillPlacer->scanActiveBundles();
916 }
917
918
919 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
920 /// live-through blocks in Blocks.
921 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
922                                      ArrayRef<unsigned> Blocks) {
923   const unsigned GroupSize = 8;
924   SpillPlacement::BlockConstraint BCS[GroupSize];
925   unsigned TBS[GroupSize];
926   unsigned B = 0, T = 0;
927
928   for (unsigned i = 0; i != Blocks.size(); ++i) {
929     unsigned Number = Blocks[i];
930     Intf.moveToBlock(Number);
931
932     if (!Intf.hasInterference()) {
933       assert(T < GroupSize && "Array overflow");
934       TBS[T] = Number;
935       if (++T == GroupSize) {
936         SpillPlacer->addLinks(makeArrayRef(TBS, T));
937         T = 0;
938       }
939       continue;
940     }
941
942     assert(B < GroupSize && "Array overflow");
943     BCS[B].Number = Number;
944
945     // Interference for the live-in value.
946     if (Intf.first() <= Indexes->getMBBStartIdx(Number))
947       BCS[B].Entry = SpillPlacement::MustSpill;
948     else
949       BCS[B].Entry = SpillPlacement::PrefSpill;
950
951     // Interference for the live-out value.
952     if (Intf.last() >= SA->getLastSplitPoint(Number))
953       BCS[B].Exit = SpillPlacement::MustSpill;
954     else
955       BCS[B].Exit = SpillPlacement::PrefSpill;
956
957     if (++B == GroupSize) {
958       ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
959       SpillPlacer->addConstraints(Array);
960       B = 0;
961     }
962   }
963
964   ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
965   SpillPlacer->addConstraints(Array);
966   SpillPlacer->addLinks(makeArrayRef(TBS, T));
967 }
968
969 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
970   // Keep track of through blocks that have not been added to SpillPlacer.
971   BitVector Todo = SA->getThroughBlocks();
972   SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
973   unsigned AddedTo = 0;
974 #ifndef NDEBUG
975   unsigned Visited = 0;
976 #endif
977
978   for (;;) {
979     ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
980     // Find new through blocks in the periphery of PrefRegBundles.
981     for (int i = 0, e = NewBundles.size(); i != e; ++i) {
982       unsigned Bundle = NewBundles[i];
983       // Look at all blocks connected to Bundle in the full graph.
984       ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
985       for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
986            I != E; ++I) {
987         unsigned Block = *I;
988         if (!Todo.test(Block))
989           continue;
990         Todo.reset(Block);
991         // This is a new through block. Add it to SpillPlacer later.
992         ActiveBlocks.push_back(Block);
993 #ifndef NDEBUG
994         ++Visited;
995 #endif
996       }
997     }
998     // Any new blocks to add?
999     if (ActiveBlocks.size() == AddedTo)
1000       break;
1001
1002     // Compute through constraints from the interference, or assume that all
1003     // through blocks prefer spilling when forming compact regions.
1004     ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
1005     if (Cand.PhysReg)
1006       addThroughConstraints(Cand.Intf, NewBlocks);
1007     else
1008       // Provide a strong negative bias on through blocks to prevent unwanted
1009       // liveness on loop backedges.
1010       SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
1011     AddedTo = ActiveBlocks.size();
1012
1013     // Perhaps iterating can enable more bundles?
1014     SpillPlacer->iterate();
1015   }
1016   DEBUG(dbgs() << ", v=" << Visited);
1017 }
1018
1019 /// calcCompactRegion - Compute the set of edge bundles that should be live
1020 /// when splitting the current live range into compact regions.  Compact
1021 /// regions can be computed without looking at interference.  They are the
1022 /// regions formed by removing all the live-through blocks from the live range.
1023 ///
1024 /// Returns false if the current live range is already compact, or if the
1025 /// compact regions would form single block regions anyway.
1026 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1027   // Without any through blocks, the live range is already compact.
1028   if (!SA->getNumThroughBlocks())
1029     return false;
1030
1031   // Compact regions don't correspond to any physreg.
1032   Cand.reset(IntfCache, 0);
1033
1034   DEBUG(dbgs() << "Compact region bundles");
1035
1036   // Use the spill placer to determine the live bundles. GrowRegion pretends
1037   // that all the through blocks have interference when PhysReg is unset.
1038   SpillPlacer->prepare(Cand.LiveBundles);
1039
1040   // The static split cost will be zero since Cand.Intf reports no interference.
1041   BlockFrequency Cost;
1042   if (!addSplitConstraints(Cand.Intf, Cost)) {
1043     DEBUG(dbgs() << ", none.\n");
1044     return false;
1045   }
1046
1047   growRegion(Cand);
1048   SpillPlacer->finish();
1049
1050   if (!Cand.LiveBundles.any()) {
1051     DEBUG(dbgs() << ", none.\n");
1052     return false;
1053   }
1054
1055   DEBUG({
1056     for (int i = Cand.LiveBundles.find_first(); i>=0;
1057          i = Cand.LiveBundles.find_next(i))
1058     dbgs() << " EB#" << i;
1059     dbgs() << ".\n";
1060   });
1061   return true;
1062 }
1063
1064 /// calcSpillCost - Compute how expensive it would be to split the live range in
1065 /// SA around all use blocks instead of forming bundle regions.
1066 BlockFrequency RAGreedy::calcSpillCost() {
1067   BlockFrequency Cost = 0;
1068   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1069   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1070     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1071     unsigned Number = BI.MBB->getNumber();
1072     // We normally only need one spill instruction - a load or a store.
1073     Cost += SpillPlacer->getBlockFrequency(Number);
1074
1075     // Unless the value is redefined in the block.
1076     if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1077       Cost += SpillPlacer->getBlockFrequency(Number);
1078   }
1079   return Cost;
1080 }
1081
1082 /// calcGlobalSplitCost - Return the global split cost of following the split
1083 /// pattern in LiveBundles. This cost should be added to the local cost of the
1084 /// interference pattern in SplitConstraints.
1085 ///
1086 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1087   BlockFrequency GlobalCost = 0;
1088   const BitVector &LiveBundles = Cand.LiveBundles;
1089   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1090   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1091     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1092     SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
1093     bool RegIn  = LiveBundles[Bundles->getBundle(BC.Number, 0)];
1094     bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
1095     unsigned Ins = 0;
1096
1097     if (BI.LiveIn)
1098       Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1099     if (BI.LiveOut)
1100       Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
1101     while (Ins--)
1102       GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1103   }
1104
1105   for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1106     unsigned Number = Cand.ActiveBlocks[i];
1107     bool RegIn  = LiveBundles[Bundles->getBundle(Number, 0)];
1108     bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
1109     if (!RegIn && !RegOut)
1110       continue;
1111     if (RegIn && RegOut) {
1112       // We need double spill code if this block has interference.
1113       Cand.Intf.moveToBlock(Number);
1114       if (Cand.Intf.hasInterference()) {
1115         GlobalCost += SpillPlacer->getBlockFrequency(Number);
1116         GlobalCost += SpillPlacer->getBlockFrequency(Number);
1117       }
1118       continue;
1119     }
1120     // live-in / stack-out or stack-in live-out.
1121     GlobalCost += SpillPlacer->getBlockFrequency(Number);
1122   }
1123   return GlobalCost;
1124 }
1125
1126 /// splitAroundRegion - Split the current live range around the regions
1127 /// determined by BundleCand and GlobalCand.
1128 ///
1129 /// Before calling this function, GlobalCand and BundleCand must be initialized
1130 /// so each bundle is assigned to a valid candidate, or NoCand for the
1131 /// stack-bound bundles.  The shared SA/SE SplitAnalysis and SplitEditor
1132 /// objects must be initialized for the current live range, and intervals
1133 /// created for the used candidates.
1134 ///
1135 /// @param LREdit    The LiveRangeEdit object handling the current split.
1136 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1137 ///                  must appear in this list.
1138 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1139                                  ArrayRef<unsigned> UsedCands) {
1140   // These are the intervals created for new global ranges. We may create more
1141   // intervals for local ranges.
1142   const unsigned NumGlobalIntvs = LREdit.size();
1143   DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1144   assert(NumGlobalIntvs && "No global intervals configured");
1145
1146   // Isolate even single instructions when dealing with a proper sub-class.
1147   // That guarantees register class inflation for the stack interval because it
1148   // is all copies.
1149   unsigned Reg = SA->getParent().reg;
1150   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1151
1152   // First handle all the blocks with uses.
1153   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1154   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1155     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1156     unsigned Number = BI.MBB->getNumber();
1157     unsigned IntvIn = 0, IntvOut = 0;
1158     SlotIndex IntfIn, IntfOut;
1159     if (BI.LiveIn) {
1160       unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1161       if (CandIn != NoCand) {
1162         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1163         IntvIn = Cand.IntvIdx;
1164         Cand.Intf.moveToBlock(Number);
1165         IntfIn = Cand.Intf.first();
1166       }
1167     }
1168     if (BI.LiveOut) {
1169       unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1170       if (CandOut != NoCand) {
1171         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1172         IntvOut = Cand.IntvIdx;
1173         Cand.Intf.moveToBlock(Number);
1174         IntfOut = Cand.Intf.last();
1175       }
1176     }
1177
1178     // Create separate intervals for isolated blocks with multiple uses.
1179     if (!IntvIn && !IntvOut) {
1180       DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1181       if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1182         SE->splitSingleBlock(BI);
1183       continue;
1184     }
1185
1186     if (IntvIn && IntvOut)
1187       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1188     else if (IntvIn)
1189       SE->splitRegInBlock(BI, IntvIn, IntfIn);
1190     else
1191       SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1192   }
1193
1194   // Handle live-through blocks. The relevant live-through blocks are stored in
1195   // the ActiveBlocks list with each candidate. We need to filter out
1196   // duplicates.
1197   BitVector Todo = SA->getThroughBlocks();
1198   for (unsigned c = 0; c != UsedCands.size(); ++c) {
1199     ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1200     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1201       unsigned Number = Blocks[i];
1202       if (!Todo.test(Number))
1203         continue;
1204       Todo.reset(Number);
1205
1206       unsigned IntvIn = 0, IntvOut = 0;
1207       SlotIndex IntfIn, IntfOut;
1208
1209       unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1210       if (CandIn != NoCand) {
1211         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1212         IntvIn = Cand.IntvIdx;
1213         Cand.Intf.moveToBlock(Number);
1214         IntfIn = Cand.Intf.first();
1215       }
1216
1217       unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1218       if (CandOut != NoCand) {
1219         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1220         IntvOut = Cand.IntvIdx;
1221         Cand.Intf.moveToBlock(Number);
1222         IntfOut = Cand.Intf.last();
1223       }
1224       if (!IntvIn && !IntvOut)
1225         continue;
1226       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1227     }
1228   }
1229
1230   ++NumGlobalSplits;
1231
1232   SmallVector<unsigned, 8> IntvMap;
1233   SE->finish(&IntvMap);
1234   DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1235
1236   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1237   unsigned OrigBlocks = SA->getNumLiveBlocks();
1238
1239   // Sort out the new intervals created by splitting. We get four kinds:
1240   // - Remainder intervals should not be split again.
1241   // - Candidate intervals can be assigned to Cand.PhysReg.
1242   // - Block-local splits are candidates for local splitting.
1243   // - DCE leftovers should go back on the queue.
1244   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1245     LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
1246
1247     // Ignore old intervals from DCE.
1248     if (getStage(Reg) != RS_New)
1249       continue;
1250
1251     // Remainder interval. Don't try splitting again, spill if it doesn't
1252     // allocate.
1253     if (IntvMap[i] == 0) {
1254       setStage(Reg, RS_Spill);
1255       continue;
1256     }
1257
1258     // Global intervals. Allow repeated splitting as long as the number of live
1259     // blocks is strictly decreasing.
1260     if (IntvMap[i] < NumGlobalIntvs) {
1261       if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1262         DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1263                      << " blocks as original.\n");
1264         // Don't allow repeated splitting as a safe guard against looping.
1265         setStage(Reg, RS_Split2);
1266       }
1267       continue;
1268     }
1269
1270     // Other intervals are treated as new. This includes local intervals created
1271     // for blocks with multiple uses, and anything created by DCE.
1272   }
1273
1274   if (VerifyEnabled)
1275     MF->verify(this, "After splitting live range around region");
1276 }
1277
1278 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1279                                   SmallVectorImpl<unsigned> &NewVRegs) {
1280   unsigned NumCands = 0;
1281   BlockFrequency BestCost;
1282
1283   // Check if we can split this live range around a compact region.
1284   bool HasCompact = calcCompactRegion(GlobalCand.front());
1285   if (HasCompact) {
1286     // Yes, keep GlobalCand[0] as the compact region candidate.
1287     NumCands = 1;
1288     BestCost = BlockFrequency::getMaxFrequency();
1289   } else {
1290     // No benefit from the compact region, our fallback will be per-block
1291     // splitting. Make sure we find a solution that is cheaper than spilling.
1292     BestCost = calcSpillCost();
1293     DEBUG(dbgs() << "Cost of isolating all blocks = ";
1294                  MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
1295   }
1296
1297   unsigned BestCand =
1298       calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1299                                false/*IgnoreCSR*/);
1300
1301   // No solutions found, fall back to single block splitting.
1302   if (!HasCompact && BestCand == NoCand)
1303     return 0;
1304
1305   return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1306 }
1307
1308 unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1309                                             AllocationOrder &Order,
1310                                             BlockFrequency &BestCost,
1311                                             unsigned &NumCands,
1312                                             bool IgnoreCSR) {
1313   unsigned BestCand = NoCand;
1314   Order.rewind();
1315   while (unsigned PhysReg = Order.next()) {
1316    if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
1317      if (IgnoreCSR && !MRI->isPhysRegUsed(CSR))
1318        continue;
1319
1320     // Discard bad candidates before we run out of interference cache cursors.
1321     // This will only affect register classes with a lot of registers (>32).
1322     if (NumCands == IntfCache.getMaxCursors()) {
1323       unsigned WorstCount = ~0u;
1324       unsigned Worst = 0;
1325       for (unsigned i = 0; i != NumCands; ++i) {
1326         if (i == BestCand || !GlobalCand[i].PhysReg)
1327           continue;
1328         unsigned Count = GlobalCand[i].LiveBundles.count();
1329         if (Count < WorstCount)
1330           Worst = i, WorstCount = Count;
1331       }
1332       --NumCands;
1333       GlobalCand[Worst] = GlobalCand[NumCands];
1334       if (BestCand == NumCands)
1335         BestCand = Worst;
1336     }
1337
1338     if (GlobalCand.size() <= NumCands)
1339       GlobalCand.resize(NumCands+1);
1340     GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1341     Cand.reset(IntfCache, PhysReg);
1342
1343     SpillPlacer->prepare(Cand.LiveBundles);
1344     BlockFrequency Cost;
1345     if (!addSplitConstraints(Cand.Intf, Cost)) {
1346       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1347       continue;
1348     }
1349     DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1350                  MBFI->printBlockFreq(dbgs(), Cost));
1351     if (Cost >= BestCost) {
1352       DEBUG({
1353         if (BestCand == NoCand)
1354           dbgs() << " worse than no bundles\n";
1355         else
1356           dbgs() << " worse than "
1357                  << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1358       });
1359       continue;
1360     }
1361     growRegion(Cand);
1362
1363     SpillPlacer->finish();
1364
1365     // No live bundles, defer to splitSingleBlocks().
1366     if (!Cand.LiveBundles.any()) {
1367       DEBUG(dbgs() << " no bundles.\n");
1368       continue;
1369     }
1370
1371     Cost += calcGlobalSplitCost(Cand);
1372     DEBUG({
1373       dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1374                                 << " with bundles";
1375       for (int i = Cand.LiveBundles.find_first(); i>=0;
1376            i = Cand.LiveBundles.find_next(i))
1377         dbgs() << " EB#" << i;
1378       dbgs() << ".\n";
1379     });
1380     if (Cost < BestCost) {
1381       BestCand = NumCands;
1382       BestCost = Cost;
1383     }
1384     ++NumCands;
1385   }
1386   return BestCand;
1387 }
1388
1389 unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1390                                  bool HasCompact,
1391                                  SmallVectorImpl<unsigned> &NewVRegs) {
1392   SmallVector<unsigned, 8> UsedCands;
1393   // Prepare split editor.
1394   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1395   SE->reset(LREdit, SplitSpillMode);
1396
1397   // Assign all edge bundles to the preferred candidate, or NoCand.
1398   BundleCand.assign(Bundles->getNumBundles(), NoCand);
1399
1400   // Assign bundles for the best candidate region.
1401   if (BestCand != NoCand) {
1402     GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1403     if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1404       UsedCands.push_back(BestCand);
1405       Cand.IntvIdx = SE->openIntv();
1406       DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1407                    << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1408       (void)B;
1409     }
1410   }
1411
1412   // Assign bundles for the compact region.
1413   if (HasCompact) {
1414     GlobalSplitCandidate &Cand = GlobalCand.front();
1415     assert(!Cand.PhysReg && "Compact region has no physreg");
1416     if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1417       UsedCands.push_back(0);
1418       Cand.IntvIdx = SE->openIntv();
1419       DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1420                    << Cand.IntvIdx << ".\n");
1421       (void)B;
1422     }
1423   }
1424
1425   splitAroundRegion(LREdit, UsedCands);
1426   return 0;
1427 }
1428
1429
1430 //===----------------------------------------------------------------------===//
1431 //                            Per-Block Splitting
1432 //===----------------------------------------------------------------------===//
1433
1434 /// tryBlockSplit - Split a global live range around every block with uses. This
1435 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1436 /// they don't allocate.
1437 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1438                                  SmallVectorImpl<unsigned> &NewVRegs) {
1439   assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1440   unsigned Reg = VirtReg.reg;
1441   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1442   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1443   SE->reset(LREdit, SplitSpillMode);
1444   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1445   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1446     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1447     if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1448       SE->splitSingleBlock(BI);
1449   }
1450   // No blocks were split.
1451   if (LREdit.empty())
1452     return 0;
1453
1454   // We did split for some blocks.
1455   SmallVector<unsigned, 8> IntvMap;
1456   SE->finish(&IntvMap);
1457
1458   // Tell LiveDebugVariables about the new ranges.
1459   DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1460
1461   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1462
1463   // Sort out the new intervals created by splitting. The remainder interval
1464   // goes straight to spilling, the new local ranges get to stay RS_New.
1465   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1466     LiveInterval &LI = LIS->getInterval(LREdit.get(i));
1467     if (getStage(LI) == RS_New && IntvMap[i] == 0)
1468       setStage(LI, RS_Spill);
1469   }
1470
1471   if (VerifyEnabled)
1472     MF->verify(this, "After splitting live range around basic blocks");
1473   return 0;
1474 }
1475
1476
1477 //===----------------------------------------------------------------------===//
1478 //                         Per-Instruction Splitting
1479 //===----------------------------------------------------------------------===//
1480
1481 /// Get the number of allocatable registers that match the constraints of \p Reg
1482 /// on \p MI and that are also in \p SuperRC.
1483 static unsigned getNumAllocatableRegsForConstraints(
1484     const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1485     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1486     const RegisterClassInfo &RCI) {
1487   assert(SuperRC && "Invalid register class");
1488
1489   const TargetRegisterClass *ConstrainedRC =
1490       MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1491                                              /* ExploreBundle */ true);
1492   if (!ConstrainedRC)
1493     return 0;
1494   return RCI.getNumAllocatableRegs(ConstrainedRC);
1495 }
1496
1497 /// tryInstructionSplit - Split a live range around individual instructions.
1498 /// This is normally not worthwhile since the spiller is doing essentially the
1499 /// same thing. However, when the live range is in a constrained register
1500 /// class, it may help to insert copies such that parts of the live range can
1501 /// be moved to a larger register class.
1502 ///
1503 /// This is similar to spilling to a larger register class.
1504 unsigned
1505 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1506                               SmallVectorImpl<unsigned> &NewVRegs) {
1507   const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
1508   // There is no point to this if there are no larger sub-classes.
1509   if (!RegClassInfo.isProperSubClass(CurRC))
1510     return 0;
1511
1512   // Always enable split spill mode, since we're effectively spilling to a
1513   // register.
1514   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1515   SE->reset(LREdit, SplitEditor::SM_Size);
1516
1517   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1518   if (Uses.size() <= 1)
1519     return 0;
1520
1521   DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1522
1523   const TargetRegisterClass *SuperRC = TRI->getLargestLegalSuperClass(CurRC);
1524   unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1525   // Split around every non-copy instruction if this split will relax
1526   // the constraints on the virtual register.
1527   // Otherwise, splitting just inserts uncoalescable copies that do not help
1528   // the allocation.
1529   for (unsigned i = 0; i != Uses.size(); ++i) {
1530     if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1531       if (MI->isFullCopy() ||
1532           SuperRCNumAllocatableRegs ==
1533               getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1534                                                   TRI, RCI)) {
1535         DEBUG(dbgs() << "    skip:\t" << Uses[i] << '\t' << *MI);
1536         continue;
1537       }
1538     SE->openIntv();
1539     SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1540     SlotIndex SegStop  = SE->leaveIntvAfter(Uses[i]);
1541     SE->useIntv(SegStart, SegStop);
1542   }
1543
1544   if (LREdit.empty()) {
1545     DEBUG(dbgs() << "All uses were copies.\n");
1546     return 0;
1547   }
1548
1549   SmallVector<unsigned, 8> IntvMap;
1550   SE->finish(&IntvMap);
1551   DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
1552   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1553
1554   // Assign all new registers to RS_Spill. This was the last chance.
1555   setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1556   return 0;
1557 }
1558
1559
1560 //===----------------------------------------------------------------------===//
1561 //                             Local Splitting
1562 //===----------------------------------------------------------------------===//
1563
1564
1565 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1566 /// in order to use PhysReg between two entries in SA->UseSlots.
1567 ///
1568 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1569 ///
1570 void RAGreedy::calcGapWeights(unsigned PhysReg,
1571                               SmallVectorImpl<float> &GapWeight) {
1572   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1573   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1574   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1575   const unsigned NumGaps = Uses.size()-1;
1576
1577   // Start and end points for the interference check.
1578   SlotIndex StartIdx =
1579     BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1580   SlotIndex StopIdx =
1581     BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1582
1583   GapWeight.assign(NumGaps, 0.0f);
1584
1585   // Add interference from each overlapping register.
1586   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1587     if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1588           .checkInterference())
1589       continue;
1590
1591     // We know that VirtReg is a continuous interval from FirstInstr to
1592     // LastInstr, so we don't need InterferenceQuery.
1593     //
1594     // Interference that overlaps an instruction is counted in both gaps
1595     // surrounding the instruction. The exception is interference before
1596     // StartIdx and after StopIdx.
1597     //
1598     LiveIntervalUnion::SegmentIter IntI =
1599       Matrix->getLiveUnions()[*Units] .find(StartIdx);
1600     for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1601       // Skip the gaps before IntI.
1602       while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1603         if (++Gap == NumGaps)
1604           break;
1605       if (Gap == NumGaps)
1606         break;
1607
1608       // Update the gaps covered by IntI.
1609       const float weight = IntI.value()->weight;
1610       for (; Gap != NumGaps; ++Gap) {
1611         GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1612         if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1613           break;
1614       }
1615       if (Gap == NumGaps)
1616         break;
1617     }
1618   }
1619
1620   // Add fixed interference.
1621   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1622     const LiveRange &LR = LIS->getRegUnit(*Units);
1623     LiveRange::const_iterator I = LR.find(StartIdx);
1624     LiveRange::const_iterator E = LR.end();
1625
1626     // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1627     for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1628       while (Uses[Gap+1].getBoundaryIndex() < I->start)
1629         if (++Gap == NumGaps)
1630           break;
1631       if (Gap == NumGaps)
1632         break;
1633
1634       for (; Gap != NumGaps; ++Gap) {
1635         GapWeight[Gap] = llvm::huge_valf;
1636         if (Uses[Gap+1].getBaseIndex() >= I->end)
1637           break;
1638       }
1639       if (Gap == NumGaps)
1640         break;
1641     }
1642   }
1643 }
1644
1645 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1646 /// basic block.
1647 ///
1648 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1649                                  SmallVectorImpl<unsigned> &NewVRegs) {
1650   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1651   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1652
1653   // Note that it is possible to have an interval that is live-in or live-out
1654   // while only covering a single block - A phi-def can use undef values from
1655   // predecessors, and the block could be a single-block loop.
1656   // We don't bother doing anything clever about such a case, we simply assume
1657   // that the interval is continuous from FirstInstr to LastInstr. We should
1658   // make sure that we don't do anything illegal to such an interval, though.
1659
1660   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1661   if (Uses.size() <= 2)
1662     return 0;
1663   const unsigned NumGaps = Uses.size()-1;
1664
1665   DEBUG({
1666     dbgs() << "tryLocalSplit: ";
1667     for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1668       dbgs() << ' ' << Uses[i];
1669     dbgs() << '\n';
1670   });
1671
1672   // If VirtReg is live across any register mask operands, compute a list of
1673   // gaps with register masks.
1674   SmallVector<unsigned, 8> RegMaskGaps;
1675   if (Matrix->checkRegMaskInterference(VirtReg)) {
1676     // Get regmask slots for the whole block.
1677     ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1678     DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1679     // Constrain to VirtReg's live range.
1680     unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1681                                    Uses.front().getRegSlot()) - RMS.begin();
1682     unsigned re = RMS.size();
1683     for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1684       // Look for Uses[i] <= RMS <= Uses[i+1].
1685       assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1686       if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1687         continue;
1688       // Skip a regmask on the same instruction as the last use. It doesn't
1689       // overlap the live range.
1690       if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1691         break;
1692       DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1693       RegMaskGaps.push_back(i);
1694       // Advance ri to the next gap. A regmask on one of the uses counts in
1695       // both gaps.
1696       while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1697         ++ri;
1698     }
1699     DEBUG(dbgs() << '\n');
1700   }
1701
1702   // Since we allow local split results to be split again, there is a risk of
1703   // creating infinite loops. It is tempting to require that the new live
1704   // ranges have less instructions than the original. That would guarantee
1705   // convergence, but it is too strict. A live range with 3 instructions can be
1706   // split 2+3 (including the COPY), and we want to allow that.
1707   //
1708   // Instead we use these rules:
1709   //
1710   // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1711   //    noop split, of course).
1712   // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1713   //    the new ranges must have fewer instructions than before the split.
1714   // 3. New ranges with the same number of instructions are marked RS_Split2,
1715   //    smaller ranges are marked RS_New.
1716   //
1717   // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1718   // excessive splitting and infinite loops.
1719   //
1720   bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1721
1722   // Best split candidate.
1723   unsigned BestBefore = NumGaps;
1724   unsigned BestAfter = 0;
1725   float BestDiff = 0;
1726
1727   const float blockFreq =
1728     SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1729     (1.0f / MBFI->getEntryFreq());
1730   SmallVector<float, 8> GapWeight;
1731
1732   Order.rewind();
1733   while (unsigned PhysReg = Order.next()) {
1734     // Keep track of the largest spill weight that would need to be evicted in
1735     // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1736     calcGapWeights(PhysReg, GapWeight);
1737
1738     // Remove any gaps with regmask clobbers.
1739     if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1740       for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1741         GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
1742
1743     // Try to find the best sequence of gaps to close.
1744     // The new spill weight must be larger than any gap interference.
1745
1746     // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1747     unsigned SplitBefore = 0, SplitAfter = 1;
1748
1749     // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1750     // It is the spill weight that needs to be evicted.
1751     float MaxGap = GapWeight[0];
1752
1753     for (;;) {
1754       // Live before/after split?
1755       const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1756       const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1757
1758       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1759                    << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1760                    << " i=" << MaxGap);
1761
1762       // Stop before the interval gets so big we wouldn't be making progress.
1763       if (!LiveBefore && !LiveAfter) {
1764         DEBUG(dbgs() << " all\n");
1765         break;
1766       }
1767       // Should the interval be extended or shrunk?
1768       bool Shrink = true;
1769
1770       // How many gaps would the new range have?
1771       unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1772
1773       // Legally, without causing looping?
1774       bool Legal = !ProgressRequired || NewGaps < NumGaps;
1775
1776       if (Legal && MaxGap < llvm::huge_valf) {
1777         // Estimate the new spill weight. Each instruction reads or writes the
1778         // register. Conservatively assume there are no read-modify-write
1779         // instructions.
1780         //
1781         // Try to guess the size of the new interval.
1782         const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1783                                  Uses[SplitBefore].distance(Uses[SplitAfter]) +
1784                                  (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1785         // Would this split be possible to allocate?
1786         // Never allocate all gaps, we wouldn't be making progress.
1787         DEBUG(dbgs() << " w=" << EstWeight);
1788         if (EstWeight * Hysteresis >= MaxGap) {
1789           Shrink = false;
1790           float Diff = EstWeight - MaxGap;
1791           if (Diff > BestDiff) {
1792             DEBUG(dbgs() << " (best)");
1793             BestDiff = Hysteresis * Diff;
1794             BestBefore = SplitBefore;
1795             BestAfter = SplitAfter;
1796           }
1797         }
1798       }
1799
1800       // Try to shrink.
1801       if (Shrink) {
1802         if (++SplitBefore < SplitAfter) {
1803           DEBUG(dbgs() << " shrink\n");
1804           // Recompute the max when necessary.
1805           if (GapWeight[SplitBefore - 1] >= MaxGap) {
1806             MaxGap = GapWeight[SplitBefore];
1807             for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1808               MaxGap = std::max(MaxGap, GapWeight[i]);
1809           }
1810           continue;
1811         }
1812         MaxGap = 0;
1813       }
1814
1815       // Try to extend the interval.
1816       if (SplitAfter >= NumGaps) {
1817         DEBUG(dbgs() << " end\n");
1818         break;
1819       }
1820
1821       DEBUG(dbgs() << " extend\n");
1822       MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1823     }
1824   }
1825
1826   // Didn't find any candidates?
1827   if (BestBefore == NumGaps)
1828     return 0;
1829
1830   DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1831                << '-' << Uses[BestAfter] << ", " << BestDiff
1832                << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1833
1834   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1835   SE->reset(LREdit);
1836
1837   SE->openIntv();
1838   SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1839   SlotIndex SegStop  = SE->leaveIntvAfter(Uses[BestAfter]);
1840   SE->useIntv(SegStart, SegStop);
1841   SmallVector<unsigned, 8> IntvMap;
1842   SE->finish(&IntvMap);
1843   DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
1844
1845   // If the new range has the same number of instructions as before, mark it as
1846   // RS_Split2 so the next split will be forced to make progress. Otherwise,
1847   // leave the new intervals as RS_New so they can compete.
1848   bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1849   bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1850   unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1851   if (NewGaps >= NumGaps) {
1852     DEBUG(dbgs() << "Tagging non-progress ranges: ");
1853     assert(!ProgressRequired && "Didn't make progress when it was required.");
1854     for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1855       if (IntvMap[i] == 1) {
1856         setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1857         DEBUG(dbgs() << PrintReg(LREdit.get(i)));
1858       }
1859     DEBUG(dbgs() << '\n');
1860   }
1861   ++NumLocalSplits;
1862
1863   return 0;
1864 }
1865
1866 //===----------------------------------------------------------------------===//
1867 //                          Live Range Splitting
1868 //===----------------------------------------------------------------------===//
1869
1870 /// trySplit - Try to split VirtReg or one of its interferences, making it
1871 /// assignable.
1872 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1873 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1874                             SmallVectorImpl<unsigned>&NewVRegs) {
1875   // Ranges must be Split2 or less.
1876   if (getStage(VirtReg) >= RS_Spill)
1877     return 0;
1878
1879   // Local intervals are handled separately.
1880   if (LIS->intervalIsInOneMBB(VirtReg)) {
1881     NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1882     SA->analyze(&VirtReg);
1883     unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1884     if (PhysReg || !NewVRegs.empty())
1885       return PhysReg;
1886     return tryInstructionSplit(VirtReg, Order, NewVRegs);
1887   }
1888
1889   NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1890
1891   SA->analyze(&VirtReg);
1892
1893   // FIXME: SplitAnalysis may repair broken live ranges coming from the
1894   // coalescer. That may cause the range to become allocatable which means that
1895   // tryRegionSplit won't be making progress. This check should be replaced with
1896   // an assertion when the coalescer is fixed.
1897   if (SA->didRepairRange()) {
1898     // VirtReg has changed, so all cached queries are invalid.
1899     Matrix->invalidateVirtRegs();
1900     if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1901       return PhysReg;
1902   }
1903
1904   // First try to split around a region spanning multiple blocks. RS_Split2
1905   // ranges already made dubious progress with region splitting, so they go
1906   // straight to single block splitting.
1907   if (getStage(VirtReg) < RS_Split2) {
1908     unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1909     if (PhysReg || !NewVRegs.empty())
1910       return PhysReg;
1911   }
1912
1913   // Then isolate blocks.
1914   return tryBlockSplit(VirtReg, Order, NewVRegs);
1915 }
1916
1917 //===----------------------------------------------------------------------===//
1918 //                          Last Chance Recoloring
1919 //===----------------------------------------------------------------------===//
1920
1921 /// mayRecolorAllInterferences - Check if the virtual registers that
1922 /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
1923 /// recolored to free \p PhysReg.
1924 /// When true is returned, \p RecoloringCandidates has been augmented with all
1925 /// the live intervals that need to be recolored in order to free \p PhysReg
1926 /// for \p VirtReg.
1927 /// \p FixedRegisters contains all the virtual registers that cannot be
1928 /// recolored.
1929 bool
1930 RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
1931                                      SmallLISet &RecoloringCandidates,
1932                                      const SmallVirtRegSet &FixedRegisters) {
1933   const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
1934
1935   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1936     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1937     // If there is LastChanceRecoloringMaxInterference or more interferences,
1938     // chances are one would not be recolorable.
1939     if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
1940         LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
1941       DEBUG(dbgs() << "Early abort: too many interferences.\n");
1942       CutOffInfo |= CO_Interf;
1943       return false;
1944     }
1945     for (unsigned i = Q.interferingVRegs().size(); i; --i) {
1946       LiveInterval *Intf = Q.interferingVRegs()[i - 1];
1947       // If Intf is done and sit on the same register class as VirtReg,
1948       // it would not be recolorable as it is in the same state as VirtReg.
1949       if ((getStage(*Intf) == RS_Done &&
1950            MRI->getRegClass(Intf->reg) == CurRC) ||
1951           FixedRegisters.count(Intf->reg)) {
1952         DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
1953         return false;
1954       }
1955       RecoloringCandidates.insert(Intf);
1956     }
1957   }
1958   return true;
1959 }
1960
1961 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
1962 /// its interferences.
1963 /// Last chance recoloring chooses a color for \p VirtReg and recolors every
1964 /// virtual register that was using it. The recoloring process may recursively
1965 /// use the last chance recoloring. Therefore, when a virtual register has been
1966 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
1967 /// be last-chance-recolored again during this recoloring "session".
1968 /// E.g.,
1969 /// Let
1970 /// vA can use {R1, R2    }
1971 /// vB can use {    R2, R3}
1972 /// vC can use {R1        }
1973 /// Where vA, vB, and vC cannot be split anymore (they are reloads for
1974 /// instance) and they all interfere.
1975 ///
1976 /// vA is assigned R1
1977 /// vB is assigned R2
1978 /// vC tries to evict vA but vA is already done.
1979 /// Regular register allocation fails.
1980 ///
1981 /// Last chance recoloring kicks in:
1982 /// vC does as if vA was evicted => vC uses R1.
1983 /// vC is marked as fixed.
1984 /// vA needs to find a color.
1985 /// None are available.
1986 /// vA cannot evict vC: vC is a fixed virtual register now.
1987 /// vA does as if vB was evicted => vA uses R2.
1988 /// vB needs to find a color.
1989 /// R3 is available.
1990 /// Recoloring => vC = R1, vA = R2, vB = R3
1991 ///
1992 /// \p Order defines the preferred allocation order for \p VirtReg.
1993 /// \p NewRegs will contain any new virtual register that have been created
1994 /// (split, spill) during the process and that must be assigned.
1995 /// \p FixedRegisters contains all the virtual registers that cannot be
1996 /// recolored.
1997 /// \p Depth gives the current depth of the last chance recoloring.
1998 /// \return a physical register that can be used for VirtReg or ~0u if none
1999 /// exists.
2000 unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2001                                            AllocationOrder &Order,
2002                                            SmallVectorImpl<unsigned> &NewVRegs,
2003                                            SmallVirtRegSet &FixedRegisters,
2004                                            unsigned Depth) {
2005   DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2006   // Ranges must be Done.
2007   assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
2008          "Last chance recoloring should really be last chance");
2009   // Set the max depth to LastChanceRecoloringMaxDepth.
2010   // We may want to reconsider that if we end up with a too large search space
2011   // for target with hundreds of registers.
2012   // Indeed, in that case we may want to cut the search space earlier.
2013   if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
2014     DEBUG(dbgs() << "Abort because max depth has been reached.\n");
2015     CutOffInfo |= CO_Depth;
2016     return ~0u;
2017   }
2018
2019   // Set of Live intervals that will need to be recolored.
2020   SmallLISet RecoloringCandidates;
2021   // Record the original mapping virtual register to physical register in case
2022   // the recoloring fails.
2023   DenseMap<unsigned, unsigned> VirtRegToPhysReg;
2024   // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2025   // this recoloring "session".
2026   FixedRegisters.insert(VirtReg.reg);
2027
2028   Order.rewind();
2029   while (unsigned PhysReg = Order.next()) {
2030     DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2031                  << PrintReg(PhysReg, TRI) << '\n');
2032     RecoloringCandidates.clear();
2033     VirtRegToPhysReg.clear();
2034
2035     // It is only possible to recolor virtual register interference.
2036     if (Matrix->checkInterference(VirtReg, PhysReg) >
2037         LiveRegMatrix::IK_VirtReg) {
2038       DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
2039
2040       continue;
2041     }
2042
2043     // Early give up on this PhysReg if it is obvious we cannot recolor all
2044     // the interferences.
2045     if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2046                                     FixedRegisters)) {
2047       DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
2048       continue;
2049     }
2050
2051     // RecoloringCandidates contains all the virtual registers that interfer
2052     // with VirtReg on PhysReg (or one of its aliases).
2053     // Enqueue them for recoloring and perform the actual recoloring.
2054     PQueue RecoloringQueue;
2055     for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2056                               EndIt = RecoloringCandidates.end();
2057          It != EndIt; ++It) {
2058       unsigned ItVirtReg = (*It)->reg;
2059       enqueue(RecoloringQueue, *It);
2060       assert(VRM->hasPhys(ItVirtReg) &&
2061              "Interferences are supposed to be with allocated vairables");
2062
2063       // Record the current allocation.
2064       VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2065       // unset the related struct.
2066       Matrix->unassign(**It);
2067     }
2068
2069     // Do as if VirtReg was assigned to PhysReg so that the underlying
2070     // recoloring has the right information about the interferes and
2071     // available colors.
2072     Matrix->assign(VirtReg, PhysReg);
2073
2074     // Save the current recoloring state.
2075     // If we cannot recolor all the interferences, we will have to start again
2076     // at this point for the next physical register.
2077     SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2078     if (tryRecoloringCandidates(RecoloringQueue, NewVRegs, FixedRegisters,
2079                                 Depth)) {
2080       // Do not mess up with the global assignment process.
2081       // I.e., VirtReg must be unassigned.
2082       Matrix->unassign(VirtReg);
2083       return PhysReg;
2084     }
2085
2086     DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2087                  << PrintReg(PhysReg, TRI) << '\n');
2088
2089     // The recoloring attempt failed, undo the changes.
2090     FixedRegisters = SaveFixedRegisters;
2091     Matrix->unassign(VirtReg);
2092
2093     for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2094                               EndIt = RecoloringCandidates.end();
2095          It != EndIt; ++It) {
2096       unsigned ItVirtReg = (*It)->reg;
2097       if (VRM->hasPhys(ItVirtReg))
2098         Matrix->unassign(**It);
2099       Matrix->assign(**It, VirtRegToPhysReg[ItVirtReg]);
2100     }
2101   }
2102
2103   // Last chance recoloring did not worked either, give up.
2104   return ~0u;
2105 }
2106
2107 /// tryRecoloringCandidates - Try to assign a new color to every register
2108 /// in \RecoloringQueue.
2109 /// \p NewRegs will contain any new virtual register created during the
2110 /// recoloring process.
2111 /// \p FixedRegisters[in/out] contains all the registers that have been
2112 /// recolored.
2113 /// \return true if all virtual registers in RecoloringQueue were successfully
2114 /// recolored, false otherwise.
2115 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2116                                        SmallVectorImpl<unsigned> &NewVRegs,
2117                                        SmallVirtRegSet &FixedRegisters,
2118                                        unsigned Depth) {
2119   while (!RecoloringQueue.empty()) {
2120     LiveInterval *LI = dequeue(RecoloringQueue);
2121     DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2122     unsigned PhysReg;
2123     PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2124     if (PhysReg == ~0u || !PhysReg)
2125       return false;
2126     DEBUG(dbgs() << "Recoloring of " << *LI
2127                  << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
2128     Matrix->assign(*LI, PhysReg);
2129     FixedRegisters.insert(LI->reg);
2130   }
2131   return true;
2132 }
2133
2134 //===----------------------------------------------------------------------===//
2135 //                            Main Entry Point
2136 //===----------------------------------------------------------------------===//
2137
2138 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
2139                                  SmallVectorImpl<unsigned> &NewVRegs) {
2140   CutOffInfo = CO_None;
2141   LLVMContext &Ctx = MF->getFunction()->getContext();
2142   SmallVirtRegSet FixedRegisters;
2143   unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2144   if (Reg == ~0U && (CutOffInfo != CO_None)) {
2145     uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2146     if (CutOffEncountered == CO_Depth)
2147       Ctx.emitError("register allocation failed: maximum depth for recoloring "
2148                     "reached. Use -fexhaustive-register-search to skip "
2149                     "cutoffs");
2150     else if (CutOffEncountered == CO_Interf)
2151       Ctx.emitError("register allocation failed: maximum interference for "
2152                     "recoloring reached. Use -fexhaustive-register-search "
2153                     "to skip cutoffs");
2154     else if (CutOffEncountered == (CO_Depth | CO_Interf))
2155       Ctx.emitError("register allocation failed: maximum interference and "
2156                     "depth for recoloring reached. Use "
2157                     "-fexhaustive-register-search to skip cutoffs");
2158   }
2159   return Reg;
2160 }
2161
2162 /// Using a CSR for the first time has a cost because it causes push|pop
2163 /// to be added to prologue|epilogue. Splitting a cold section of the live
2164 /// range can have lower cost than using the CSR for the first time;
2165 /// Spilling a live range in the cold path can have lower cost than using
2166 /// the CSR for the first time. Returns the physical register if we decide
2167 /// to use the CSR; otherwise return 0.
2168 unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2169                                          AllocationOrder &Order,
2170                                          unsigned PhysReg,
2171                                          unsigned &CostPerUseLimit,
2172                                          SmallVectorImpl<unsigned> &NewVRegs) {
2173   if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2174     // We choose spill over using the CSR for the first time if the spill cost
2175     // is lower than CSRCost.
2176     SA->analyze(&VirtReg);
2177     if (calcSpillCost() >= CSRCost)
2178       return PhysReg;
2179
2180     // We are going to spill, set CostPerUseLimit to 1 to make sure that
2181     // we will not use a callee-saved register in tryEvict.
2182     CostPerUseLimit = 1;
2183     return 0;
2184   }
2185   if (getStage(VirtReg) < RS_Split) {
2186     // We choose pre-splitting over using the CSR for the first time if
2187     // the cost of splitting is lower than CSRCost.
2188     SA->analyze(&VirtReg);
2189     unsigned NumCands = 0;
2190     BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2191     unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2192                                                  NumCands, true /*IgnoreCSR*/);
2193     if (BestCand == NoCand)
2194       // Use the CSR if we can't find a region split below CSRCost.
2195       return PhysReg;
2196
2197     // Perform the actual pre-splitting.
2198     doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2199     return 0;
2200   }
2201   return PhysReg;
2202 }
2203
2204 void RAGreedy::initializeCSRCost() {
2205   // We use the larger one out of the command-line option and the value report
2206   // by TRI.
2207   CSRCost = BlockFrequency(
2208       std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2209   if (!CSRCost.getFrequency())
2210     return;
2211
2212   // Raw cost is relative to Entry == 2^14; scale it appropriately.
2213   uint64_t ActualEntry = MBFI->getEntryFreq();
2214   if (!ActualEntry) {
2215     CSRCost = 0;
2216     return;
2217   }
2218   uint64_t FixedEntry = 1 << 14;
2219   if (ActualEntry < FixedEntry)
2220     CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2221   else if (ActualEntry <= UINT32_MAX)
2222     // Invert the fraction and divide.
2223     CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2224   else
2225     // Can't use BranchProbability in general, since it takes 32-bit numbers.
2226     CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2227 }
2228
2229 unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2230                                      SmallVectorImpl<unsigned> &NewVRegs,
2231                                      SmallVirtRegSet &FixedRegisters,
2232                                      unsigned Depth) {
2233   unsigned CostPerUseLimit = ~0u;
2234   // First try assigning a free register.
2235   AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
2236   if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
2237     // We check other options if we are using a CSR for the first time.
2238     bool CSRFirstUse = false;
2239     if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
2240       if (!MRI->isPhysRegUsed(CSR))
2241         CSRFirstUse = true;
2242
2243     // When NewVRegs is not empty, we may have made decisions such as evicting
2244     // a virtual register, go with the earlier decisions and use the physical
2245     // register.
2246     if (CSRCost.getFrequency() && CSRFirstUse && NewVRegs.empty()) {
2247       unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2248                                               CostPerUseLimit, NewVRegs);
2249       if (CSRReg || !NewVRegs.empty())
2250         // Return now if we decide to use a CSR or create new vregs due to
2251         // pre-splitting.
2252         return CSRReg;
2253     } else
2254       return PhysReg;
2255   }
2256
2257   LiveRangeStage Stage = getStage(VirtReg);
2258   DEBUG(dbgs() << StageName[Stage]
2259                << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
2260
2261   // Try to evict a less worthy live range, but only for ranges from the primary
2262   // queue. The RS_Split ranges already failed to do this, and they should not
2263   // get a second chance until they have been split.
2264   if (Stage != RS_Split)
2265     if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit))
2266       return PhysReg;
2267
2268   assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
2269
2270   // The first time we see a live range, don't try to split or spill.
2271   // Wait until the second time, when all smaller ranges have been allocated.
2272   // This gives a better picture of the interference to split around.
2273   if (Stage < RS_Split) {
2274     setStage(VirtReg, RS_Split);
2275     DEBUG(dbgs() << "wait for second round\n");
2276     NewVRegs.push_back(VirtReg.reg);
2277     return 0;
2278   }
2279
2280   // If we couldn't allocate a register from spilling, there is probably some
2281   // invalid inline assembly. The base class wil report it.
2282   if (Stage >= RS_Done || !VirtReg.isSpillable())
2283     return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2284                                    Depth);
2285
2286   // Try splitting VirtReg or interferences.
2287   unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
2288   if (PhysReg || !NewVRegs.empty())
2289     return PhysReg;
2290
2291   // Finally spill VirtReg itself.
2292   NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
2293   LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
2294   spiller().spill(LRE);
2295   setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
2296
2297   if (VerifyEnabled)
2298     MF->verify(this, "After spilling");
2299
2300   // The live virtual register requesting allocation was spilled, so tell
2301   // the caller not to allocate anything during this round.
2302   return 0;
2303 }
2304
2305 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2306   DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
2307                << "********** Function: " << mf.getName() << '\n');
2308
2309   MF = &mf;
2310   TRI = MF->getTarget().getRegisterInfo();
2311   TII = MF->getTarget().getInstrInfo();
2312   RCI.runOnMachineFunction(mf);
2313   if (VerifyEnabled)
2314     MF->verify(this, "Before greedy register allocator");
2315
2316   RegAllocBase::init(getAnalysis<VirtRegMap>(),
2317                      getAnalysis<LiveIntervals>(),
2318                      getAnalysis<LiveRegMatrix>());
2319   Indexes = &getAnalysis<SlotIndexes>();
2320   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2321   DomTree = &getAnalysis<MachineDominatorTree>();
2322   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
2323   Loops = &getAnalysis<MachineLoopInfo>();
2324   Bundles = &getAnalysis<EdgeBundles>();
2325   SpillPlacer = &getAnalysis<SpillPlacement>();
2326   DebugVars = &getAnalysis<LiveDebugVariables>();
2327
2328   initializeCSRCost();
2329
2330   calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
2331
2332   DEBUG(LIS->dump());
2333
2334   SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
2335   SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
2336   ExtraRegInfo.clear();
2337   ExtraRegInfo.resize(MRI->getNumVirtRegs());
2338   NextCascade = 1;
2339   IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
2340   GlobalCand.resize(32);  // This will grow as needed.
2341
2342   allocatePhysRegs();
2343   releaseMemory();
2344   return true;
2345 }