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