blob: 723553ad53f05741ac4e2e696e7e835569955345 [file] [log] [blame]
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001//===-- 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"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000016#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000017#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000018#include "LiveDebugVariables.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000019#include "LiveRangeEdit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000020#include "RegAllocBase.h"
21#include "Spiller.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000022#include "SpillPlacement.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000024#include "VirtRegMap.h"
Rafael Espindolafdf16ca2011-06-26 21:41:06 +000025#include "RegisterCoalescer.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000026#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000027#include "llvm/Analysis/AliasAnalysis.h"
28#include "llvm/Function.h"
29#include "llvm/PassAnalysisSupport.h"
30#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000031#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000032#include "llvm/CodeGen/LiveIntervalAnalysis.h"
33#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000034#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000036#include "llvm/CodeGen/MachineLoopInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/CodeGen/Passes.h"
39#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000040#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000044#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000045
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000046#include <queue>
47
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000048using namespace llvm;
49
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000050STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000052STATISTIC(NumEvicted, "Number of interferences evicted");
53
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000054static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
55 createGreedyRegisterAllocator);
56
57namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000058class RAGreedy : public MachineFunctionPass,
59 public RegAllocBase,
60 private LiveRangeEdit::Delegate {
61
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000062 // context
63 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000064
65 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000066 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000067 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000068 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000069 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000070 EdgeBundles *Bundles;
71 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000072 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000073
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000074 // state
75 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000076 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000077 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000078
79 // Live ranges pass through a number of stages as we try to allocate them.
80 // Some of the stages may also create new live ranges:
81 //
82 // - Region splitting.
83 // - Per-block splitting.
84 // - Local splitting.
85 // - Spilling.
86 //
87 // Ranges produced by one of the stages skip the previous stages when they are
88 // dequeued. This improves performance because we can skip interference checks
89 // that are unlikely to give any results. It also guarantees that the live
90 // range splitting algorithm terminates, something that is otherwise hard to
91 // ensure.
92 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +000093 /// Newly created live range that has never been queued.
94 RS_New,
95
96 /// Only attempt assignment and eviction. Then requeue as RS_Split.
97 RS_Assign,
98
99 /// Attempt live range splitting if assignment is impossible.
100 RS_Split,
101
102 /// Live range will be spilled. No more splitting will be attempted.
103 RS_Spill,
104
105 /// There is nothing more we can do to this live range. Abort compilation
106 /// if it can't be assigned.
107 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000108 };
109
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000110 static const char *const StageName[];
111
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000112 // RegInfo - Keep additional information about each live range.
113 struct RegInfo {
114 LiveRangeStage Stage;
115
116 // Cascade - Eviction loop prevention. See canEvictInterference().
117 unsigned Cascade;
118
119 RegInfo() : Stage(RS_New), Cascade(0) {}
120 };
121
122 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000123
124 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000125 return ExtraRegInfo[VirtReg.reg].Stage;
126 }
127
128 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
129 ExtraRegInfo.resize(MRI->getNumVirtRegs());
130 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000131 }
132
133 template<typename Iterator>
134 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000135 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000136 for (;Begin != End; ++Begin) {
137 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000138 if (ExtraRegInfo[Reg].Stage == RS_New)
139 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000140 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000141 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000142
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000143 /// Cost of evicting interference.
144 struct EvictionCost {
145 unsigned BrokenHints; ///< Total number of broken hints.
146 float MaxWeight; ///< Maximum spill weight evicted.
147
148 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
149
150 bool operator<(const EvictionCost &O) const {
151 if (BrokenHints != O.BrokenHints)
152 return BrokenHints < O.BrokenHints;
153 return MaxWeight < O.MaxWeight;
154 }
155 };
156
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000157 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000158 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000159 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000160
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000161 /// Cached per-block interference maps
162 InterferenceCache IntfCache;
163
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000164 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000165 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000166
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000167 /// Global live range splitting candidate info.
168 struct GlobalSplitCandidate {
169 unsigned PhysReg;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000170 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000171 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000172 SmallVector<unsigned, 8> ActiveBlocks;
173
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000174 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000175 PhysReg = Reg;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000176 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000177 LiveBundles.clear();
178 ActiveBlocks.clear();
179 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000180 };
181
182 /// Candidate info for for each PhysReg in AllocationOrder.
183 /// This vector never shrinks, but grows to the size of the largest register
184 /// class.
185 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
186
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000187public:
188 RAGreedy();
189
190 /// Return the pass name.
191 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000192 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000193 }
194
195 /// RAGreedy analysis usage.
196 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000197 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000198 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000199 virtual void enqueue(LiveInterval *LI);
200 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000201 virtual unsigned selectOrSplit(LiveInterval&,
202 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000203
204 /// Perform register allocation.
205 virtual bool runOnMachineFunction(MachineFunction &mf);
206
207 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000208
209private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000210 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000211 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000212 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000213 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000214
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000215 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000216 bool addSplitConstraints(InterferenceCache::Cursor, float&);
217 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000218 void growRegion(GlobalSplitCandidate &Cand);
219 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000220 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000221 void splitAroundRegion(LiveInterval&, GlobalSplitCandidate&,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000222 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000223 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000224 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
225 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
226 void evictInterference(LiveInterval&, unsigned,
227 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000228
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000229 unsigned tryAssign(LiveInterval&, AllocationOrder&,
230 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000231 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000232 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000233 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
234 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000235 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
236 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000237 unsigned trySplit(LiveInterval&, AllocationOrder&,
238 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000239};
240} // end anonymous namespace
241
242char RAGreedy::ID = 0;
243
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000244#ifndef NDEBUG
245const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000246 "RS_New",
247 "RS_Assign",
248 "RS_Split",
249 "RS_Spill",
250 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000251};
252#endif
253
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000254// Hysteresis to use when comparing floats.
255// This helps stabilize decisions based on float comparisons.
256const float Hysteresis = 0.98f;
257
258
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000259FunctionPass* llvm::createGreedyRegisterAllocator() {
260 return new RAGreedy();
261}
262
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000263RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000264 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000265 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000266 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
267 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
268 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000269 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000270 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
271 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
272 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
273 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
274 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000275 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
276 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000277}
278
279void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
280 AU.setPreservesCFG();
281 AU.addRequired<AliasAnalysis>();
282 AU.addPreserved<AliasAnalysis>();
283 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000284 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000285 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000286 AU.addRequired<LiveDebugVariables>();
287 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000288 if (StrongPHIElim)
289 AU.addRequiredID(StrongPHIEliminationID);
290 AU.addRequiredTransitive<RegisterCoalescer>();
291 AU.addRequired<CalculateSpillWeights>();
292 AU.addRequired<LiveStacks>();
293 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000294 AU.addRequired<MachineDominatorTree>();
295 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000296 AU.addRequired<MachineLoopInfo>();
297 AU.addPreserved<MachineLoopInfo>();
298 AU.addRequired<VirtRegMap>();
299 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000300 AU.addRequired<EdgeBundles>();
301 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000302 MachineFunctionPass::getAnalysisUsage(AU);
303}
304
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000305
306//===----------------------------------------------------------------------===//
307// LiveRangeEdit delegate methods
308//===----------------------------------------------------------------------===//
309
310void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
311 // LRE itself will remove from SlotIndexes and parent basic block.
312 VRM->RemoveMachineInstrFromMaps(MI);
313}
314
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000315bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
316 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
317 unassign(LIS->getInterval(VirtReg), PhysReg);
318 return true;
319 }
320 // Unassigned virtreg is probably in the priority queue.
321 // RegAllocBase will erase it after dequeueing.
322 return false;
323}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000324
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000325void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
326 unsigned PhysReg = VRM->getPhys(VirtReg);
327 if (!PhysReg)
328 return;
329
330 // Register is assigned, put it back on the queue for reassignment.
331 LiveInterval &LI = LIS->getInterval(VirtReg);
332 unassign(LI, PhysReg);
333 enqueue(&LI);
334}
335
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000336void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
337 // LRE may clone a virtual register because dead code elimination causes it to
338 // be split into connected components. Ensure that the new register gets the
339 // same stage as the parent.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000340 ExtraRegInfo.grow(New);
341 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000342}
343
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000344void RAGreedy::releaseMemory() {
345 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000346 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000347 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000348 RegAllocBase::releaseMemory();
349}
350
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000351void RAGreedy::enqueue(LiveInterval *LI) {
352 // Prioritize live ranges by size, assigning larger ranges first.
353 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000354 const unsigned Size = LI->getSize();
355 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000356 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
357 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000358 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000359
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000360 ExtraRegInfo.grow(Reg);
361 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000362 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000363
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000364 if (ExtraRegInfo[Reg].Stage == RS_Split)
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000365 // Unsplit ranges that couldn't be allocated immediately are deferred until
366 // everything else has been allocated. Long ranges are allocated last so
367 // they are split against realistic interference.
368 Prio = (1u << 31) - Size;
369 else {
370 // Everything else is allocated in long->short order. Long ranges that don't
371 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000372 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000373
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000374 // Boost ranges that have a physical register hint.
375 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
376 Prio |= (1u << 30);
377 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000378
379 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000380}
381
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000382LiveInterval *RAGreedy::dequeue() {
383 if (Queue.empty())
384 return 0;
385 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
386 Queue.pop();
387 return LI;
388}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000389
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000390
391//===----------------------------------------------------------------------===//
392// Direct Assignment
393//===----------------------------------------------------------------------===//
394
395/// tryAssign - Try to assign VirtReg to an available register.
396unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
397 AllocationOrder &Order,
398 SmallVectorImpl<LiveInterval*> &NewVRegs) {
399 Order.rewind();
400 unsigned PhysReg;
401 while ((PhysReg = Order.next()))
402 if (!checkPhysRegInterference(VirtReg, PhysReg))
403 break;
404 if (!PhysReg || Order.isHint(PhysReg))
405 return PhysReg;
406
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000407 // PhysReg is available, but there may be a better choice.
408
409 // If we missed a simple hint, try to cheaply evict interference from the
410 // preferred register.
411 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
412 if (Order.isHint(Hint)) {
413 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
414 EvictionCost MaxCost(1);
415 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
416 evictInterference(VirtReg, Hint, NewVRegs);
417 return Hint;
418 }
419 }
420
421 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000422 unsigned Cost = TRI->getCostPerUse(PhysReg);
423
424 // Most registers have 0 additional cost.
425 if (!Cost)
426 return PhysReg;
427
428 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
429 << '\n');
430 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
431 return CheapReg ? CheapReg : PhysReg;
432}
433
434
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000435//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000436// Interference eviction
437//===----------------------------------------------------------------------===//
438
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000439/// shouldEvict - determine if A should evict the assigned live range B. The
440/// eviction policy defined by this function together with the allocation order
441/// defined by enqueue() decides which registers ultimately end up being split
442/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000443///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000444/// Cascade numbers are used to prevent infinite loops if this function is a
445/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000446///
447/// @param A The live range to be assigned.
448/// @param IsHint True when A is about to be assigned to its preferred
449/// register.
450/// @param B The live range to be evicted.
451/// @param BreaksHint True when B is already assigned to its preferred register.
452bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
453 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000454 bool CanSplit = getStage(B) <= RS_Split;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000455
456 // Be fairly aggressive about following hints as long as the evictee can be
457 // split.
458 if (CanSplit && IsHint && !BreaksHint)
459 return true;
460
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000461 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000462}
463
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000464/// canEvictInterference - Return true if all interferences between VirtReg and
465/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
466///
467/// @param VirtReg Live range that is about to be assigned.
468/// @param PhysReg Desired register for assignment.
469/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
470/// @param MaxCost Only look for cheaper candidates and update with new cost
471/// when returning true.
472/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000473bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000474 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000475 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
476 // involved in an eviction before. If a cascade number was assigned, deny
477 // evicting anything with the same or a newer cascade number. This prevents
478 // infinite eviction loops.
479 //
480 // This works out so a register without a cascade number is allowed to evict
481 // anything, and it can be evicted by anything.
482 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
483 if (!Cascade)
484 Cascade = NextCascade;
485
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000486 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000487 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
488 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000489 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000490 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000491 return false;
492
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000493 // Check if any interfering live range is heavier than MaxWeight.
494 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
495 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000496 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
497 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000498 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000499 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000500 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000501 // Once a live range becomes small enough, it is urgent that we find a
502 // register for it. This is indicated by an infinite spill weight. These
503 // urgent live ranges get to evict almost anything.
504 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
505 // Only evict older cascades or live ranges without a cascade.
506 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
507 if (Cascade <= IntfCascade) {
508 if (!Urgent)
509 return false;
510 // We permit breaking cascades for urgent evictions. It should be the
511 // last resort, though, so make it really expensive.
512 Cost.BrokenHints += 10;
513 }
514 // Would this break a satisfied hint?
515 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
516 // Update eviction cost.
517 Cost.BrokenHints += BreaksHint;
518 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
519 // Abort if this would be too expensive.
520 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000521 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000522 // Finally, apply the eviction policy for non-urgent evictions.
523 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000524 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000525 }
526 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000527 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000528 return true;
529}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000530
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000531/// evictInterference - Evict any interferring registers that prevent VirtReg
532/// from being assigned to Physreg. This assumes that canEvictInterference
533/// returned true.
534void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
535 SmallVectorImpl<LiveInterval*> &NewVRegs) {
536 // Make sure that VirtReg has a cascade number, and assign that cascade
537 // number to every evicted register. These live ranges than then only be
538 // evicted by a newer cascade, preventing infinite loops.
539 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
540 if (!Cascade)
541 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
542
543 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
544 << " interference: Cascade " << Cascade << '\n');
545 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
546 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
547 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
548 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
549 LiveInterval *Intf = Q.interferingVRegs()[i];
550 unassign(*Intf, VRM->getPhys(Intf->reg));
551 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
552 VirtReg.isSpillable() < Intf->isSpillable()) &&
553 "Cannot decrease cascade number, illegal eviction");
554 ExtraRegInfo[Intf->reg].Cascade = Cascade;
555 ++NumEvicted;
556 NewVRegs.push_back(Intf);
557 }
558 }
559}
560
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000561/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000562/// @param VirtReg Currently unassigned virtual register.
563/// @param Order Physregs to try.
564/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000565unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
566 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000567 SmallVectorImpl<LiveInterval*> &NewVRegs,
568 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000569 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
570
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000571 // Keep track of the cheapest interference seen so far.
572 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000573 unsigned BestPhys = 0;
574
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000575 // When we are just looking for a reduced cost per use, don't break any
576 // hints, and only evict smaller spill weights.
577 if (CostPerUseLimit < ~0u) {
578 BestCost.BrokenHints = 0;
579 BestCost.MaxWeight = VirtReg.weight;
580 }
581
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000582 Order.rewind();
583 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000584 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
585 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000586 // The first use of a callee-saved register in a function has cost 1.
587 // Don't start using a CSR when the CostPerUseLimit is low.
588 if (CostPerUseLimit == 1)
589 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
590 if (!MRI->isPhysRegUsed(CSR)) {
591 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
592 << PrintReg(CSR, TRI) << '\n');
593 continue;
594 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000595
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000596 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000597 continue;
598
599 // Best so far.
600 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000601
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000602 // Stop if the hint can be used.
603 if (Order.isHint(PhysReg))
604 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000605 }
606
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000607 if (!BestPhys)
608 return 0;
609
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000610 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000611 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000612}
613
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000614
615//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000616// Region Splitting
617//===----------------------------------------------------------------------===//
618
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000619/// addSplitConstraints - Fill out the SplitConstraints vector based on the
620/// interference pattern in Physreg and its aliases. Add the constraints to
621/// SpillPlacement and return the static cost of this split in Cost, assuming
622/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000623/// Return false if there are no bundles with positive bias.
624bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
625 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000626 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000627
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000628 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000629 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000630 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000631 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
632 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000633 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000634
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000635 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000636 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000637 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
638 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000639
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000640 if (!Intf.hasInterference())
641 continue;
642
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000643 // Number of spill code instructions to insert.
644 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000645
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000646 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000647 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000648 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000649 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000650 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000651 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000652 else if (Intf.first() < BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000653 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000654 }
655
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000656 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000657 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000658 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000659 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000660 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000661 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000662 else if (Intf.last() > BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000663 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000664 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000665
666 // Accumulate the total frequency of inserted spill code.
667 if (Ins)
668 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000669 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000670 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000671
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000672 // Add constraints for use-blocks. Note that these are the only constraints
673 // that may add a positive bias, it is downhill from here.
674 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000675 return SpillPlacer->scanActiveBundles();
676}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000677
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000678
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000679/// addThroughConstraints - Add constraints and links to SpillPlacer from the
680/// live-through blocks in Blocks.
681void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
682 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000683 const unsigned GroupSize = 8;
684 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000685 unsigned TBS[GroupSize];
686 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000687
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000688 for (unsigned i = 0; i != Blocks.size(); ++i) {
689 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000690 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000691
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000692 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000693 assert(T < GroupSize && "Array overflow");
694 TBS[T] = Number;
695 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000696 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000697 T = 0;
698 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000699 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000700 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000701
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000702 assert(B < GroupSize && "Array overflow");
703 BCS[B].Number = Number;
704
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000705 // Interference for the live-in value.
706 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
707 BCS[B].Entry = SpillPlacement::MustSpill;
708 else
709 BCS[B].Entry = SpillPlacement::PrefSpill;
710
711 // Interference for the live-out value.
712 if (Intf.last() >= SA->getLastSplitPoint(Number))
713 BCS[B].Exit = SpillPlacement::MustSpill;
714 else
715 BCS[B].Exit = SpillPlacement::PrefSpill;
716
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000717 if (++B == GroupSize) {
718 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
719 SpillPlacer->addConstraints(Array);
720 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000721 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000722 }
723
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000724 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
725 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000726 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000727}
728
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000729void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000730 // Keep track of through blocks that have not been added to SpillPlacer.
731 BitVector Todo = SA->getThroughBlocks();
732 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
733 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000734#ifndef NDEBUG
735 unsigned Visited = 0;
736#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000737
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000738 for (;;) {
739 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000740 // Find new through blocks in the periphery of PrefRegBundles.
741 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
742 unsigned Bundle = NewBundles[i];
743 // Look at all blocks connected to Bundle in the full graph.
744 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
745 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
746 I != E; ++I) {
747 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000748 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000749 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000750 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000751 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000752 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000753#ifndef NDEBUG
754 ++Visited;
755#endif
756 }
757 }
758 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000759 if (ActiveBlocks.size() == AddedTo)
760 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000761
762 // Compute through constraints from the interference, or assume that all
763 // through blocks prefer spilling when forming compact regions.
764 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
765 if (Cand.PhysReg)
766 addThroughConstraints(Cand.Intf, NewBlocks);
767 else
768 SpillPlacer->addPrefSpill(NewBlocks);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000769 AddedTo = ActiveBlocks.size();
770
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000771 // Perhaps iterating can enable more bundles?
772 SpillPlacer->iterate();
773 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000774 DEBUG(dbgs() << ", v=" << Visited);
775}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000776
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000777/// calcCompactRegion - Compute the set of edge bundles that should be live
778/// when splitting the current live range into compact regions. Compact
779/// regions can be computed without looking at interference. They are the
780/// regions formed by removing all the live-through blocks from the live range.
781///
782/// Returns false if the current live range is already compact, or if the
783/// compact regions would form single block regions anyway.
784bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
785 // Without any through blocks, the live range is already compact.
786 if (!SA->getNumThroughBlocks())
787 return false;
788
789 // Compact regions don't correspond to any physreg.
790 Cand.reset(IntfCache, 0);
791
792 DEBUG(dbgs() << "Compact region bundles");
793
794 // Use the spill placer to determine the live bundles. GrowRegion pretends
795 // that all the through blocks have interference when PhysReg is unset.
796 SpillPlacer->prepare(Cand.LiveBundles);
797
798 // The static split cost will be zero since Cand.Intf reports no interference.
799 float Cost;
800 if (!addSplitConstraints(Cand.Intf, Cost)) {
801 DEBUG(dbgs() << ", none.\n");
802 return false;
803 }
804
805 growRegion(Cand);
806 SpillPlacer->finish();
807
808 if (!Cand.LiveBundles.any()) {
809 DEBUG(dbgs() << ", none.\n");
810 return false;
811 }
812
813 DEBUG({
814 for (int i = Cand.LiveBundles.find_first(); i>=0;
815 i = Cand.LiveBundles.find_next(i))
816 dbgs() << " EB#" << i;
817 dbgs() << ".\n";
818 });
819 return true;
820}
821
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000822/// calcSpillCost - Compute how expensive it would be to split the live range in
823/// SA around all use blocks instead of forming bundle regions.
824float RAGreedy::calcSpillCost() {
825 float Cost = 0;
826 const LiveInterval &LI = SA->getParent();
827 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
828 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
829 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
830 unsigned Number = BI.MBB->getNumber();
831 // We normally only need one spill instruction - a load or a store.
832 Cost += SpillPlacer->getBlockFrequency(Number);
833
834 // Unless the value is redefined in the block.
835 if (BI.LiveIn && BI.LiveOut) {
836 SlotIndex Start, Stop;
837 tie(Start, Stop) = Indexes->getMBBRange(Number);
838 LiveInterval::const_iterator I = LI.find(Start);
839 assert(I != LI.end() && "Expected live-in value");
840 // Is there a different live-out value? If so, we need an extra spill
841 // instruction.
842 if (I->end < Stop)
843 Cost += SpillPlacer->getBlockFrequency(Number);
844 }
845 }
846 return Cost;
847}
848
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000849/// calcGlobalSplitCost - Return the global split cost of following the split
850/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000851/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000852///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000853float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000854 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000855 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000856 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
857 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
858 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000859 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000860 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
861 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
862 unsigned Ins = 0;
863
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000864 if (BI.LiveIn)
865 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
866 if (BI.LiveOut)
867 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000868 if (Ins)
869 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000870 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000871
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000872 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
873 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000874 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
875 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000876 if (!RegIn && !RegOut)
877 continue;
878 if (RegIn && RegOut) {
879 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000880 Cand.Intf.moveToBlock(Number);
881 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000882 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
883 continue;
884 }
885 // live-in / stack-out or stack-in live-out.
886 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000887 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000888 return GlobalCost;
889}
890
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000891/// splitAroundRegion - Split VirtReg around the region determined by
892/// LiveBundles. Make an effort to avoid interference from PhysReg.
893///
894/// The 'register' interval is going to contain as many uses as possible while
895/// avoiding interference. The 'stack' interval is the complement constructed by
896/// SplitEditor. It will contain the rest.
897///
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000898void RAGreedy::splitAroundRegion(LiveInterval &VirtReg,
899 GlobalSplitCandidate &Cand,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000900 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000901 const BitVector &LiveBundles = Cand.LiveBundles;
902
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000903 DEBUG({
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000904 dbgs() << "Splitting around region for " << PrintReg(Cand.PhysReg, TRI)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000905 << " with bundles";
906 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
907 dbgs() << " EB#" << i;
908 dbgs() << ".\n";
909 });
910
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000911 InterferenceCache::Cursor &Intf = Cand.Intf;
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000912 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000913 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000914
915 // Create the main cross-block interval.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000916 const unsigned MainIntv = SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000917
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000918 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000919 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
920 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
921 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000922 bool RegIn = BI.LiveIn &&
923 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
924 bool RegOut = BI.LiveOut &&
925 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000926
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000927 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000928 if (!RegIn && !RegOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000929 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000930 if (!BI.isOneInstr()) {
931 SE->splitSingleBlock(BI);
932 SE->selectIntv(MainIntv);
933 }
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000934 continue;
935 }
936
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000937 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000938
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000939 if (RegIn && RegOut)
940 SE->splitLiveThroughBlock(BI.MBB->getNumber(),
941 MainIntv, Intf.first(),
942 MainIntv, Intf.last());
943 else if (RegIn)
944 SE->splitRegInBlock(BI, MainIntv, Intf.first());
945 else
946 SE->splitRegOutBlock(BI, MainIntv, Intf.last());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000947 }
948
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000949 // Handle live-through blocks.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000950 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
951 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000952 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
953 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000954 if (!RegIn && !RegOut)
955 continue;
956 Intf.moveToBlock(Number);
957 SE->splitLiveThroughBlock(Number, RegIn ? MainIntv : 0, Intf.first(),
958 RegOut ? MainIntv : 0, Intf.last());
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000959 }
960
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000961 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000962
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000963 SmallVector<unsigned, 8> IntvMap;
964 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000965 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
966
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000967 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +0000968 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000969
970 // Sort out the new intervals created by splitting. We get four kinds:
971 // - Remainder intervals should not be split again.
972 // - Candidate intervals can be assigned to Cand.PhysReg.
973 // - Block-local splits are candidates for local splitting.
974 // - DCE leftovers should go back on the queue.
975 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000976 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000977
978 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000979 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000980 continue;
981
982 // Remainder interval. Don't try splitting again, spill if it doesn't
983 // allocate.
984 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000985 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000986 continue;
987 }
988
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000989 // Main interval. Allow repeated splitting as long as the number of live
990 // blocks is strictly decreasing.
991 if (IntvMap[i] == MainIntv) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000992 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000993 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
994 << " blocks as original.\n");
995 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000996 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000997 }
998 continue;
999 }
1000
1001 // Other intervals are treated as new. This includes local intervals created
1002 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001003 }
1004
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001005 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001006 MF->verify(this, "After splitting live range around region");
1007}
1008
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001009unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1010 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001011 float BestCost = Hysteresis * calcSpillCost();
1012 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001013 const unsigned NoCand = ~0u;
1014 unsigned BestCand = NoCand;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001015 unsigned NumCands = 0;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001016
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001017 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001018 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001019 // Discard bad candidates before we run out of interference cache cursors.
1020 // This will only affect register classes with a lot of registers (>32).
1021 if (NumCands == IntfCache.getMaxCursors()) {
1022 unsigned WorstCount = ~0u;
1023 unsigned Worst = 0;
1024 for (unsigned i = 0; i != NumCands; ++i) {
1025 if (i == BestCand)
1026 continue;
1027 unsigned Count = GlobalCand[i].LiveBundles.count();
1028 if (Count < WorstCount)
1029 Worst = i, WorstCount = Count;
1030 }
1031 --NumCands;
1032 GlobalCand[Worst] = GlobalCand[NumCands];
1033 }
1034
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001035 if (GlobalCand.size() <= NumCands)
1036 GlobalCand.resize(NumCands+1);
1037 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1038 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001039
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001040 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001041 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001042 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001043 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001044 continue;
1045 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001046 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001047 if (Cost >= BestCost) {
1048 DEBUG({
1049 if (BestCand == NoCand)
1050 dbgs() << " worse than no bundles\n";
1051 else
1052 dbgs() << " worse than "
1053 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1054 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001055 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001056 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001057 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001058
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001059 SpillPlacer->finish();
1060
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001061 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001062 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001063 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001064 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001065 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001066
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001067 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001068 DEBUG({
1069 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001070 for (int i = Cand.LiveBundles.find_first(); i>=0;
1071 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001072 dbgs() << " EB#" << i;
1073 dbgs() << ".\n";
1074 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001075 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001076 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001077 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001078 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001079 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001080 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001081
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001082 if (BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001083 return 0;
1084
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001085 splitAroundRegion(VirtReg, GlobalCand[BestCand], NewVRegs);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001086 return 0;
1087}
1088
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001089
1090//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001091// Local Splitting
1092//===----------------------------------------------------------------------===//
1093
1094
1095/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1096/// in order to use PhysReg between two entries in SA->UseSlots.
1097///
1098/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1099///
1100void RAGreedy::calcGapWeights(unsigned PhysReg,
1101 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001102 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1103 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001104 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1105 const unsigned NumGaps = Uses.size()-1;
1106
1107 // Start and end points for the interference check.
1108 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
1109 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
1110
1111 GapWeight.assign(NumGaps, 0.0f);
1112
1113 // Add interference from each overlapping register.
1114 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1115 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1116 .checkInterference())
1117 continue;
1118
1119 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
1120 // so we don't need InterferenceQuery.
1121 //
1122 // Interference that overlaps an instruction is counted in both gaps
1123 // surrounding the instruction. The exception is interference before
1124 // StartIdx and after StopIdx.
1125 //
1126 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1127 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1128 // Skip the gaps before IntI.
1129 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1130 if (++Gap == NumGaps)
1131 break;
1132 if (Gap == NumGaps)
1133 break;
1134
1135 // Update the gaps covered by IntI.
1136 const float weight = IntI.value()->weight;
1137 for (; Gap != NumGaps; ++Gap) {
1138 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1139 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1140 break;
1141 }
1142 if (Gap == NumGaps)
1143 break;
1144 }
1145 }
1146}
1147
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001148/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1149/// basic block.
1150///
1151unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1152 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001153 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1154 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001155
1156 // Note that it is possible to have an interval that is live-in or live-out
1157 // while only covering a single block - A phi-def can use undef values from
1158 // predecessors, and the block could be a single-block loop.
1159 // We don't bother doing anything clever about such a case, we simply assume
1160 // that the interval is continuous from FirstUse to LastUse. We should make
1161 // sure that we don't do anything illegal to such an interval, though.
1162
1163 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1164 if (Uses.size() <= 2)
1165 return 0;
1166 const unsigned NumGaps = Uses.size()-1;
1167
1168 DEBUG({
1169 dbgs() << "tryLocalSplit: ";
1170 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1171 dbgs() << ' ' << SA->UseSlots[i];
1172 dbgs() << '\n';
1173 });
1174
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001175 // Since we allow local split results to be split again, there is a risk of
1176 // creating infinite loops. It is tempting to require that the new live
1177 // ranges have less instructions than the original. That would guarantee
1178 // convergence, but it is too strict. A live range with 3 instructions can be
1179 // split 2+3 (including the COPY), and we want to allow that.
1180 //
1181 // Instead we use these rules:
1182 //
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001183 // 1. Allow any split for ranges with getStage() < RS_Spill. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001184 // noop split, of course).
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001185 // 2. Require progress be made for ranges with getStage() >= RS_Spill. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001186 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001187 // 3. New ranges with the same number of instructions are marked RS_Spill,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001188 // smaller ranges are marked RS_New.
1189 //
1190 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1191 // excessive splitting and infinite loops.
1192 //
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001193 bool ProgressRequired = getStage(VirtReg) >= RS_Spill;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001194
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001195 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001196 unsigned BestBefore = NumGaps;
1197 unsigned BestAfter = 0;
1198 float BestDiff = 0;
1199
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001200 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001201 SmallVector<float, 8> GapWeight;
1202
1203 Order.rewind();
1204 while (unsigned PhysReg = Order.next()) {
1205 // Keep track of the largest spill weight that would need to be evicted in
1206 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1207 calcGapWeights(PhysReg, GapWeight);
1208
1209 // Try to find the best sequence of gaps to close.
1210 // The new spill weight must be larger than any gap interference.
1211
1212 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001213 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001214
1215 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1216 // It is the spill weight that needs to be evicted.
1217 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001218
1219 for (;;) {
1220 // Live before/after split?
1221 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1222 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1223
1224 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1225 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1226 << " i=" << MaxGap);
1227
1228 // Stop before the interval gets so big we wouldn't be making progress.
1229 if (!LiveBefore && !LiveAfter) {
1230 DEBUG(dbgs() << " all\n");
1231 break;
1232 }
1233 // Should the interval be extended or shrunk?
1234 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001235
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001236 // How many gaps would the new range have?
1237 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1238
1239 // Legally, without causing looping?
1240 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1241
1242 if (Legal && MaxGap < HUGE_VALF) {
1243 // Estimate the new spill weight. Each instruction reads or writes the
1244 // register. Conservatively assume there are no read-modify-write
1245 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001246 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001247 // Try to guess the size of the new interval.
1248 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1249 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1250 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001251 // Would this split be possible to allocate?
1252 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001253 DEBUG(dbgs() << " w=" << EstWeight);
1254 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001255 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001256 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001257 if (Diff > BestDiff) {
1258 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001259 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001260 BestBefore = SplitBefore;
1261 BestAfter = SplitAfter;
1262 }
1263 }
1264 }
1265
1266 // Try to shrink.
1267 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001268 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001269 DEBUG(dbgs() << " shrink\n");
1270 // Recompute the max when necessary.
1271 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1272 MaxGap = GapWeight[SplitBefore];
1273 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1274 MaxGap = std::max(MaxGap, GapWeight[i]);
1275 }
1276 continue;
1277 }
1278 MaxGap = 0;
1279 }
1280
1281 // Try to extend the interval.
1282 if (SplitAfter >= NumGaps) {
1283 DEBUG(dbgs() << " end\n");
1284 break;
1285 }
1286
1287 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001288 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001289 }
1290 }
1291
1292 // Didn't find any candidates?
1293 if (BestBefore == NumGaps)
1294 return 0;
1295
1296 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1297 << '-' << Uses[BestAfter] << ", " << BestDiff
1298 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1299
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001300 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001301 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001302
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001303 SE->openIntv();
1304 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1305 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1306 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001307 SmallVector<unsigned, 8> IntvMap;
1308 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001309 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001310
1311 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001312 // RS_Spill so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001313 // leave the new intervals as RS_New so they can compete.
1314 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1315 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1316 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1317 if (NewGaps >= NumGaps) {
1318 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1319 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001320 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1321 if (IntvMap[i] == 1) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001322 setStage(*LREdit.get(i), RS_Spill);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001323 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1324 }
1325 DEBUG(dbgs() << '\n');
1326 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001327 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001328
1329 return 0;
1330}
1331
1332//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001333// Live Range Splitting
1334//===----------------------------------------------------------------------===//
1335
1336/// trySplit - Try to split VirtReg or one of its interferences, making it
1337/// assignable.
1338/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1339unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1340 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001341 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001342 if (LIS->intervalIsInOneMBB(VirtReg)) {
1343 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001344 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001345 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001346 }
1347
1348 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001349
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001350 // Don't iterate global splitting.
1351 // Move straight to spilling if this range was produced by a global split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001352 if (getStage(VirtReg) >= RS_Spill)
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001353 return 0;
1354
1355 SA->analyze(&VirtReg);
1356
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001357 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1358 // coalescer. That may cause the range to become allocatable which means that
1359 // tryRegionSplit won't be making progress. This check should be replaced with
1360 // an assertion when the coalescer is fixed.
1361 if (SA->didRepairRange()) {
1362 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001363 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001364 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1365 return PhysReg;
1366 }
1367
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001368 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001369 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1370 if (PhysReg || !NewVRegs.empty())
1371 return PhysReg;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001372
1373 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001374 SplitAnalysis::BlockPtrSet Blocks;
1375 if (SA->getMultiUseBlocks(Blocks)) {
1376 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1377 SE->reset(LREdit);
1378 SE->splitSingleBlocks(Blocks);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001379 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001380 if (VerifyEnabled)
1381 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001382 }
1383
1384 // Don't assign any physregs.
1385 return 0;
1386}
1387
1388
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001389//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001390// Main Entry Point
1391//===----------------------------------------------------------------------===//
1392
1393unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001394 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001395 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001396 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001397 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1398 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001399
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001400 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001401 DEBUG(dbgs() << StageName[Stage]
1402 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001403
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001404 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001405 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001406 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001407 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001408 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1409 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001410
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001411 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1412
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001413 // The first time we see a live range, don't try to split or spill.
1414 // Wait until the second time, when all smaller ranges have been allocated.
1415 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001416 if (Stage < RS_Split) {
1417 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001418 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001419 NewVRegs.push_back(&VirtReg);
1420 return 0;
1421 }
1422
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001423 // If we couldn't allocate a register from spilling, there is probably some
1424 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001425 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001426 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001427
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001428 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001429 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1430 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001431 return PhysReg;
1432
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001433 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001434 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001435 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1436 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001437 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001438
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001439 if (VerifyEnabled)
1440 MF->verify(this, "After spilling");
1441
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001442 // The live virtual register requesting allocation was spilled, so tell
1443 // the caller not to allocate anything during this round.
1444 return 0;
1445}
1446
1447bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1448 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1449 << "********** Function: "
1450 << ((Value*)mf.getFunction())->getName() << '\n');
1451
1452 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001453 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001454 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001455
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001456 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001457 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001458 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001459 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001460 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001461 Bundles = &getAnalysis<EdgeBundles>();
1462 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001463 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001464
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001465 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001466 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001467 ExtraRegInfo.clear();
1468 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1469 NextCascade = 1;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001470 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001471
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001472 allocatePhysRegs();
1473 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001474 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001475
1476 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001477 {
1478 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001479 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001480 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001481
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001482 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001483 DebugVars->emitDebugValues(VRM);
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001484
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001485 // The pass output is in VirtRegMap. Release all the transient data.
1486 releaseMemory();
1487
1488 return true;
1489}