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