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