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