blob: 6ac542860501d8a3c89b1a4868bba954e92e0838 [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 Olesen042888d2012-06-20 22:52:26 +000019#include "LiveRegMatrix.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"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000025#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000026#include "llvm/Analysis/AliasAnalysis.h"
27#include "llvm/Function.h"
28#include "llvm/PassAnalysisSupport.h"
29#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000030#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000032#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000033#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 Olesen00005782011-07-26 23:41:46 +000041#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000042#include "llvm/Support/Debug.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000045#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000046
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000047#include <queue>
48
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000049using namespace llvm;
50
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000051STATISTIC(NumGlobalSplits, "Number of split global live ranges");
52STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000053STATISTIC(NumEvicted, "Number of interferences evicted");
54
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000055static cl::opt<SplitEditor::ComplementSpillMode>
56SplitSpillMode("split-spill-mode", cl::Hidden,
57 cl::desc("Spill mode for splitting live ranges"),
58 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
59 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
60 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
61 clEnumValEnd),
62 cl::init(SplitEditor::SM_Partition));
63
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000064static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
65 createGreedyRegisterAllocator);
66
67namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000068class RAGreedy : public MachineFunctionPass,
69 public RegAllocBase,
70 private LiveRangeEdit::Delegate {
71
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000072 // context
73 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000074
75 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000076 SlotIndexes *Indexes;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000077 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000078 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000079 EdgeBundles *Bundles;
80 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000081 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000082
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000083 // state
84 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000085 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000086 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000087
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 {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000102 /// 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
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000111 /// 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
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000116 /// 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
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000122 };
123
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000124 static const char *const StageName[];
125
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000126 // 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;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000137
138 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000139 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;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000145 }
146
147 template<typename Iterator>
148 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000149 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000150 for (;Begin != End; ++Begin) {
151 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000152 if (ExtraRegInfo[Reg].Stage == RS_New)
153 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000154 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000155 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000156
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000157 /// 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
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000171 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000172 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000173 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000174
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000175 /// Cached per-block interference maps
176 InterferenceCache IntfCache;
177
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000178 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000179 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000180
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000181 /// Global live range splitting candidate info.
182 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000183 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000184 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000185
186 // SplitKit interval index for this candidate.
187 unsigned IntvIdx;
188
189 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000190 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000191
192 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000193 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000194 SmallVector<unsigned, 8> ActiveBlocks;
195
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000196 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000197 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000198 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000199 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000200 LiveBundles.clear();
201 ActiveBlocks.clear();
202 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000203
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 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000215 };
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
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000222 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
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000228public:
229 RAGreedy();
230
231 /// Return the pass name.
232 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000233 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000234 }
235
236 /// RAGreedy analysis usage.
237 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000238 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000239 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000240 virtual void enqueue(LiveInterval *LI);
241 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000242 virtual unsigned selectOrSplit(LiveInterval&,
243 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000244
245 /// Perform register allocation.
246 virtual bool runOnMachineFunction(MachineFunction &mf);
247
248 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000249
250private:
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000251 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000252 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000253 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000254
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000255 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000256 bool addSplitConstraints(InterferenceCache::Cursor, float&);
257 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000258 void growRegion(GlobalSplitCandidate &Cand);
259 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000260 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000261 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000262 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000263 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
264 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
265 void evictInterference(LiveInterval&, unsigned,
266 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000267
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000268 unsigned tryAssign(LiveInterval&, AllocationOrder&,
269 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000270 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000271 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000272 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
273 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000274 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
275 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +0000276 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
277 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000278 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
279 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000280 unsigned trySplit(LiveInterval&, AllocationOrder&,
281 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000282};
283} // end anonymous namespace
284
285char RAGreedy::ID = 0;
286
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000287#ifndef NDEBUG
288const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000289 "RS_New",
290 "RS_Assign",
291 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000292 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000293 "RS_Spill",
294 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000295};
296#endif
297
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000298// Hysteresis to use when comparing floats.
299// This helps stabilize decisions based on float comparisons.
300const float Hysteresis = 0.98f;
301
302
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000303FunctionPass* llvm::createGreedyRegisterAllocator() {
304 return new RAGreedy();
305}
306
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000307RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000308 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000309 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000310 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
311 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000312 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000313 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000314 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
315 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
316 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
317 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
318 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000319 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000320 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
321 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000322}
323
324void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
325 AU.setPreservesCFG();
326 AU.addRequired<AliasAnalysis>();
327 AU.addPreserved<AliasAnalysis>();
328 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000329 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000330 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000331 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000332 AU.addRequired<LiveDebugVariables>();
333 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000334 AU.addRequired<CalculateSpillWeights>();
335 AU.addRequired<LiveStacks>();
336 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000337 AU.addRequired<MachineDominatorTree>();
338 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000339 AU.addRequired<MachineLoopInfo>();
340 AU.addPreserved<MachineLoopInfo>();
341 AU.addRequired<VirtRegMap>();
342 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000343 AU.addRequired<LiveRegMatrix>();
344 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000345 AU.addRequired<EdgeBundles>();
346 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000347 MachineFunctionPass::getAnalysisUsage(AU);
348}
349
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000350
351//===----------------------------------------------------------------------===//
352// LiveRangeEdit delegate methods
353//===----------------------------------------------------------------------===//
354
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000355bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000356 if (VRM->hasPhys(VirtReg)) {
357 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000358 return true;
359 }
360 // Unassigned virtreg is probably in the priority queue.
361 // RegAllocBase will erase it after dequeueing.
362 return false;
363}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000364
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000365void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000366 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000367 return;
368
369 // Register is assigned, put it back on the queue for reassignment.
370 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000371 Matrix->unassign(LI);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000372 enqueue(&LI);
373}
374
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000375void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000376 // Cloning a register we haven't even heard about yet? Just ignore it.
377 if (!ExtraRegInfo.inBounds(Old))
378 return;
379
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000380 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000381 // be split into connected components. The new components are much smaller
382 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000383 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000384 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000385 ExtraRegInfo.grow(New);
386 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000387}
388
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000389void RAGreedy::releaseMemory() {
390 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000391 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000392 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000393}
394
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000395void RAGreedy::enqueue(LiveInterval *LI) {
396 // Prioritize live ranges by size, assigning larger ranges first.
397 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000398 const unsigned Size = LI->getSize();
399 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000400 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
401 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000402 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000403
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000404 ExtraRegInfo.grow(Reg);
405 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000406 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000407
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000408 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000409 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000410 // everything else has been allocated.
411 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000412 } else {
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000413 // Everything is allocated in long->short order. Long ranges that don't fit
414 // should be spilled (or split) ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000415 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000416
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000417 // Boost ranges that have a physical register hint.
418 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
419 Prio |= (1u << 30);
420 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000421
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000422 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000423}
424
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000425LiveInterval *RAGreedy::dequeue() {
426 if (Queue.empty())
427 return 0;
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000428 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000429 Queue.pop();
430 return LI;
431}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000432
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000433
434//===----------------------------------------------------------------------===//
435// Direct Assignment
436//===----------------------------------------------------------------------===//
437
438/// tryAssign - Try to assign VirtReg to an available register.
439unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
440 AllocationOrder &Order,
441 SmallVectorImpl<LiveInterval*> &NewVRegs) {
442 Order.rewind();
443 unsigned PhysReg;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000444 while ((PhysReg = Order.next()))
445 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000446 break;
447 if (!PhysReg || Order.isHint(PhysReg))
448 return PhysReg;
449
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000450 // PhysReg is available, but there may be a better choice.
451
452 // If we missed a simple hint, try to cheaply evict interference from the
453 // preferred register.
454 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000455 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000456 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
457 EvictionCost MaxCost(1);
458 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
459 evictInterference(VirtReg, Hint, NewVRegs);
460 return Hint;
461 }
462 }
463
464 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000465 unsigned Cost = TRI->getCostPerUse(PhysReg);
466
467 // Most registers have 0 additional cost.
468 if (!Cost)
469 return PhysReg;
470
471 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
472 << '\n');
473 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
474 return CheapReg ? CheapReg : PhysReg;
475}
476
477
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000478//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000479// Interference eviction
480//===----------------------------------------------------------------------===//
481
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000482/// shouldEvict - determine if A should evict the assigned live range B. The
483/// eviction policy defined by this function together with the allocation order
484/// defined by enqueue() decides which registers ultimately end up being split
485/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000486///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000487/// Cascade numbers are used to prevent infinite loops if this function is a
488/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000489///
490/// @param A The live range to be assigned.
491/// @param IsHint True when A is about to be assigned to its preferred
492/// register.
493/// @param B The live range to be evicted.
494/// @param BreaksHint True when B is already assigned to its preferred register.
495bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
496 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000497 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000498
499 // Be fairly aggressive about following hints as long as the evictee can be
500 // split.
501 if (CanSplit && IsHint && !BreaksHint)
502 return true;
503
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000504 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000505}
506
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000507/// canEvictInterference - Return true if all interferences between VirtReg and
508/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
509///
510/// @param VirtReg Live range that is about to be assigned.
511/// @param PhysReg Desired register for assignment.
512/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
513/// @param MaxCost Only look for cheaper candidates and update with new cost
514/// when returning true.
515/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000516bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000517 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000518 // It is only possible to evict virtual register interference.
519 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
520 return false;
521
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000522 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
523 // involved in an eviction before. If a cascade number was assigned, deny
524 // evicting anything with the same or a newer cascade number. This prevents
525 // infinite eviction loops.
526 //
527 // This works out so a register without a cascade number is allowed to evict
528 // anything, and it can be evicted by anything.
529 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
530 if (!Cascade)
531 Cascade = NextCascade;
532
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000533 EvictionCost Cost;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000534 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
535 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000536 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000537 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000538 return false;
539
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000540 // Check if any interfering live range is heavier than MaxWeight.
541 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
542 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000543 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
544 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000545 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000546 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000547 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000548 // Once a live range becomes small enough, it is urgent that we find a
549 // register for it. This is indicated by an infinite spill weight. These
550 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000551 //
552 // Also allow urgent evictions of unspillable ranges from a strictly
553 // larger allocation order.
554 bool Urgent = !VirtReg.isSpillable() &&
555 (Intf->isSpillable() ||
556 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
557 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000558 // Only evict older cascades or live ranges without a cascade.
559 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
560 if (Cascade <= IntfCascade) {
561 if (!Urgent)
562 return false;
563 // We permit breaking cascades for urgent evictions. It should be the
564 // last resort, though, so make it really expensive.
565 Cost.BrokenHints += 10;
566 }
567 // Would this break a satisfied hint?
568 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
569 // Update eviction cost.
570 Cost.BrokenHints += BreaksHint;
571 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
572 // Abort if this would be too expensive.
573 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000574 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000575 // Finally, apply the eviction policy for non-urgent evictions.
576 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000577 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000578 }
579 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000580 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000581 return true;
582}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000583
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000584/// evictInterference - Evict any interferring registers that prevent VirtReg
585/// from being assigned to Physreg. This assumes that canEvictInterference
586/// returned true.
587void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
588 SmallVectorImpl<LiveInterval*> &NewVRegs) {
589 // Make sure that VirtReg has a cascade number, and assign that cascade
590 // number to every evicted register. These live ranges than then only be
591 // evicted by a newer cascade, preventing infinite loops.
592 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
593 if (!Cascade)
594 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
595
596 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
597 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000598
599 // Collect all interfering virtregs first.
600 SmallVector<LiveInterval*, 8> Intfs;
601 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
602 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000603 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000604 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
605 Intfs.append(IVR.begin(), IVR.end());
606 }
607
608 // Evict them second. This will invalidate the queries.
609 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
610 LiveInterval *Intf = Intfs[i];
611 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
612 if (!VRM->hasPhys(Intf->reg))
613 continue;
614 Matrix->unassign(*Intf);
615 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
616 VirtReg.isSpillable() < Intf->isSpillable()) &&
617 "Cannot decrease cascade number, illegal eviction");
618 ExtraRegInfo[Intf->reg].Cascade = Cascade;
619 ++NumEvicted;
620 NewVRegs.push_back(Intf);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000621 }
622}
623
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000624/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000625/// @param VirtReg Currently unassigned virtual register.
626/// @param Order Physregs to try.
627/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000628unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
629 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000630 SmallVectorImpl<LiveInterval*> &NewVRegs,
631 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000632 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
633
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000634 // Keep track of the cheapest interference seen so far.
635 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000636 unsigned BestPhys = 0;
637
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000638 // When we are just looking for a reduced cost per use, don't break any
639 // hints, and only evict smaller spill weights.
640 if (CostPerUseLimit < ~0u) {
641 BestCost.BrokenHints = 0;
642 BestCost.MaxWeight = VirtReg.weight;
643 }
644
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000645 Order.rewind();
646 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000647 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
648 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000649 // The first use of a callee-saved register in a function has cost 1.
650 // Don't start using a CSR when the CostPerUseLimit is low.
651 if (CostPerUseLimit == 1)
652 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
653 if (!MRI->isPhysRegUsed(CSR)) {
654 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
655 << PrintReg(CSR, TRI) << '\n');
656 continue;
657 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000658
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000659 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000660 continue;
661
662 // Best so far.
663 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000664
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000665 // Stop if the hint can be used.
666 if (Order.isHint(PhysReg))
667 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000668 }
669
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000670 if (!BestPhys)
671 return 0;
672
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000673 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000674 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000675}
676
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000677
678//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000679// Region Splitting
680//===----------------------------------------------------------------------===//
681
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000682/// addSplitConstraints - Fill out the SplitConstraints vector based on the
683/// interference pattern in Physreg and its aliases. Add the constraints to
684/// SpillPlacement and return the static cost of this split in Cost, assuming
685/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000686/// Return false if there are no bundles with positive bias.
687bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
688 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000689 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000690
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000691 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000692 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000693 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000694 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
695 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000696 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000697
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000698 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000699 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000700 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
701 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000702 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000703
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000704 if (!Intf.hasInterference())
705 continue;
706
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000707 // Number of spill code instructions to insert.
708 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000709
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000710 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000711 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000712 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000713 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000714 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000715 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000716 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000717 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000718 }
719
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000720 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000721 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000722 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000723 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000724 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000725 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000726 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000727 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000728 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000729
730 // Accumulate the total frequency of inserted spill code.
731 if (Ins)
732 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000733 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000734 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000735
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000736 // Add constraints for use-blocks. Note that these are the only constraints
737 // that may add a positive bias, it is downhill from here.
738 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000739 return SpillPlacer->scanActiveBundles();
740}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000741
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000742
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000743/// addThroughConstraints - Add constraints and links to SpillPlacer from the
744/// live-through blocks in Blocks.
745void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
746 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000747 const unsigned GroupSize = 8;
748 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000749 unsigned TBS[GroupSize];
750 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000751
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000752 for (unsigned i = 0; i != Blocks.size(); ++i) {
753 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000754 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000755
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000756 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000757 assert(T < GroupSize && "Array overflow");
758 TBS[T] = Number;
759 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000760 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000761 T = 0;
762 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000763 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000764 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000765
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000766 assert(B < GroupSize && "Array overflow");
767 BCS[B].Number = Number;
768
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000769 // Interference for the live-in value.
770 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
771 BCS[B].Entry = SpillPlacement::MustSpill;
772 else
773 BCS[B].Entry = SpillPlacement::PrefSpill;
774
775 // Interference for the live-out value.
776 if (Intf.last() >= SA->getLastSplitPoint(Number))
777 BCS[B].Exit = SpillPlacement::MustSpill;
778 else
779 BCS[B].Exit = SpillPlacement::PrefSpill;
780
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000781 if (++B == GroupSize) {
782 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
783 SpillPlacer->addConstraints(Array);
784 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000785 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000786 }
787
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000788 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
789 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000790 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000791}
792
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000793void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000794 // Keep track of through blocks that have not been added to SpillPlacer.
795 BitVector Todo = SA->getThroughBlocks();
796 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
797 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000798#ifndef NDEBUG
799 unsigned Visited = 0;
800#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000801
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000802 for (;;) {
803 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000804 // Find new through blocks in the periphery of PrefRegBundles.
805 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
806 unsigned Bundle = NewBundles[i];
807 // Look at all blocks connected to Bundle in the full graph.
808 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
809 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
810 I != E; ++I) {
811 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000812 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000813 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000814 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000815 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000816 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000817#ifndef NDEBUG
818 ++Visited;
819#endif
820 }
821 }
822 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000823 if (ActiveBlocks.size() == AddedTo)
824 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000825
826 // Compute through constraints from the interference, or assume that all
827 // through blocks prefer spilling when forming compact regions.
828 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
829 if (Cand.PhysReg)
830 addThroughConstraints(Cand.Intf, NewBlocks);
831 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000832 // Provide a strong negative bias on through blocks to prevent unwanted
833 // liveness on loop backedges.
834 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000835 AddedTo = ActiveBlocks.size();
836
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000837 // Perhaps iterating can enable more bundles?
838 SpillPlacer->iterate();
839 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000840 DEBUG(dbgs() << ", v=" << Visited);
841}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000842
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000843/// calcCompactRegion - Compute the set of edge bundles that should be live
844/// when splitting the current live range into compact regions. Compact
845/// regions can be computed without looking at interference. They are the
846/// regions formed by removing all the live-through blocks from the live range.
847///
848/// Returns false if the current live range is already compact, or if the
849/// compact regions would form single block regions anyway.
850bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
851 // Without any through blocks, the live range is already compact.
852 if (!SA->getNumThroughBlocks())
853 return false;
854
855 // Compact regions don't correspond to any physreg.
856 Cand.reset(IntfCache, 0);
857
858 DEBUG(dbgs() << "Compact region bundles");
859
860 // Use the spill placer to determine the live bundles. GrowRegion pretends
861 // that all the through blocks have interference when PhysReg is unset.
862 SpillPlacer->prepare(Cand.LiveBundles);
863
864 // The static split cost will be zero since Cand.Intf reports no interference.
865 float Cost;
866 if (!addSplitConstraints(Cand.Intf, Cost)) {
867 DEBUG(dbgs() << ", none.\n");
868 return false;
869 }
870
871 growRegion(Cand);
872 SpillPlacer->finish();
873
874 if (!Cand.LiveBundles.any()) {
875 DEBUG(dbgs() << ", none.\n");
876 return false;
877 }
878
879 DEBUG({
880 for (int i = Cand.LiveBundles.find_first(); i>=0;
881 i = Cand.LiveBundles.find_next(i))
882 dbgs() << " EB#" << i;
883 dbgs() << ".\n";
884 });
885 return true;
886}
887
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000888/// calcSpillCost - Compute how expensive it would be to split the live range in
889/// SA around all use blocks instead of forming bundle regions.
890float RAGreedy::calcSpillCost() {
891 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000892 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
893 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
894 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
895 unsigned Number = BI.MBB->getNumber();
896 // We normally only need one spill instruction - a load or a store.
897 Cost += SpillPlacer->getBlockFrequency(Number);
898
899 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000900 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
901 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000902 }
903 return Cost;
904}
905
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000906/// calcGlobalSplitCost - Return the global split cost of following the split
907/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000908/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000909///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000910float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000911 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000912 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000913 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
914 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
915 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000916 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000917 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
918 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
919 unsigned Ins = 0;
920
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000921 if (BI.LiveIn)
922 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
923 if (BI.LiveOut)
924 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000925 if (Ins)
926 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000927 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000928
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000929 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
930 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000931 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
932 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000933 if (!RegIn && !RegOut)
934 continue;
935 if (RegIn && RegOut) {
936 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000937 Cand.Intf.moveToBlock(Number);
938 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000939 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
940 continue;
941 }
942 // live-in / stack-out or stack-in live-out.
943 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000944 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000945 return GlobalCost;
946}
947
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000948/// splitAroundRegion - Split the current live range around the regions
949/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000950///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000951/// Before calling this function, GlobalCand and BundleCand must be initialized
952/// so each bundle is assigned to a valid candidate, or NoCand for the
953/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
954/// objects must be initialized for the current live range, and intervals
955/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000956///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000957/// @param LREdit The LiveRangeEdit object handling the current split.
958/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
959/// must appear in this list.
960void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
961 ArrayRef<unsigned> UsedCands) {
962 // These are the intervals created for new global ranges. We may create more
963 // intervals for local ranges.
964 const unsigned NumGlobalIntvs = LREdit.size();
965 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
966 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000967
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000968 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +0000969 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000970 // is all copies.
971 unsigned Reg = SA->getParent().reg;
972 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
973
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000974 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000975 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
976 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
977 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000978 unsigned Number = BI.MBB->getNumber();
979 unsigned IntvIn = 0, IntvOut = 0;
980 SlotIndex IntfIn, IntfOut;
981 if (BI.LiveIn) {
982 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
983 if (CandIn != NoCand) {
984 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
985 IntvIn = Cand.IntvIdx;
986 Cand.Intf.moveToBlock(Number);
987 IntfIn = Cand.Intf.first();
988 }
989 }
990 if (BI.LiveOut) {
991 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
992 if (CandOut != NoCand) {
993 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
994 IntvOut = Cand.IntvIdx;
995 Cand.Intf.moveToBlock(Number);
996 IntfOut = Cand.Intf.last();
997 }
998 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000999
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001000 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001001 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001002 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001003 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001004 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001005 continue;
1006 }
1007
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001008 if (IntvIn && IntvOut)
1009 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1010 else if (IntvIn)
1011 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001012 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001013 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001014 }
1015
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001016 // Handle live-through blocks. The relevant live-through blocks are stored in
1017 // the ActiveBlocks list with each candidate. We need to filter out
1018 // duplicates.
1019 BitVector Todo = SA->getThroughBlocks();
1020 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1021 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1022 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1023 unsigned Number = Blocks[i];
1024 if (!Todo.test(Number))
1025 continue;
1026 Todo.reset(Number);
1027
1028 unsigned IntvIn = 0, IntvOut = 0;
1029 SlotIndex IntfIn, IntfOut;
1030
1031 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1032 if (CandIn != NoCand) {
1033 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1034 IntvIn = Cand.IntvIdx;
1035 Cand.Intf.moveToBlock(Number);
1036 IntfIn = Cand.Intf.first();
1037 }
1038
1039 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1040 if (CandOut != NoCand) {
1041 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1042 IntvOut = Cand.IntvIdx;
1043 Cand.Intf.moveToBlock(Number);
1044 IntfOut = Cand.Intf.last();
1045 }
1046 if (!IntvIn && !IntvOut)
1047 continue;
1048 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1049 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001050 }
1051
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001052 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001053
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001054 SmallVector<unsigned, 8> IntvMap;
1055 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001056 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001057
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001058 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001059 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001060
1061 // Sort out the new intervals created by splitting. We get four kinds:
1062 // - Remainder intervals should not be split again.
1063 // - Candidate intervals can be assigned to Cand.PhysReg.
1064 // - Block-local splits are candidates for local splitting.
1065 // - DCE leftovers should go back on the queue.
1066 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001067 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001068
1069 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001070 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001071 continue;
1072
1073 // Remainder interval. Don't try splitting again, spill if it doesn't
1074 // allocate.
1075 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001076 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001077 continue;
1078 }
1079
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001080 // Global intervals. Allow repeated splitting as long as the number of live
1081 // blocks is strictly decreasing.
1082 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001083 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001084 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1085 << " blocks as original.\n");
1086 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001087 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001088 }
1089 continue;
1090 }
1091
1092 // Other intervals are treated as new. This includes local intervals created
1093 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001094 }
1095
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001096 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001097 MF->verify(this, "After splitting live range around region");
1098}
1099
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001100unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1101 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001102 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001103 unsigned BestCand = NoCand;
1104 float BestCost;
1105 SmallVector<unsigned, 8> UsedCands;
1106
1107 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001108 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001109 if (HasCompact) {
1110 // Yes, keep GlobalCand[0] as the compact region candidate.
1111 NumCands = 1;
1112 BestCost = HUGE_VALF;
1113 } else {
1114 // No benefit from the compact region, our fallback will be per-block
1115 // splitting. Make sure we find a solution that is cheaper than spilling.
1116 BestCost = Hysteresis * calcSpillCost();
1117 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1118 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001119
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001120 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001121 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001122 // Discard bad candidates before we run out of interference cache cursors.
1123 // This will only affect register classes with a lot of registers (>32).
1124 if (NumCands == IntfCache.getMaxCursors()) {
1125 unsigned WorstCount = ~0u;
1126 unsigned Worst = 0;
1127 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001128 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001129 continue;
1130 unsigned Count = GlobalCand[i].LiveBundles.count();
1131 if (Count < WorstCount)
1132 Worst = i, WorstCount = Count;
1133 }
1134 --NumCands;
1135 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001136 if (BestCand == NumCands)
1137 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001138 }
1139
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001140 if (GlobalCand.size() <= NumCands)
1141 GlobalCand.resize(NumCands+1);
1142 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1143 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001144
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001145 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001146 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001147 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001148 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001149 continue;
1150 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001151 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001152 if (Cost >= BestCost) {
1153 DEBUG({
1154 if (BestCand == NoCand)
1155 dbgs() << " worse than no bundles\n";
1156 else
1157 dbgs() << " worse than "
1158 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1159 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001160 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001161 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001162 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001163
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001164 SpillPlacer->finish();
1165
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001166 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001167 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001168 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001169 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001170 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001171
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001172 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001173 DEBUG({
1174 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001175 for (int i = Cand.LiveBundles.find_first(); i>=0;
1176 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001177 dbgs() << " EB#" << i;
1178 dbgs() << ".\n";
1179 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001180 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001181 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001182 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001183 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001184 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001185 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001186
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001187 // No solutions found, fall back to single block splitting.
1188 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001189 return 0;
1190
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001191 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001192 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001193 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001194
1195 // Assign all edge bundles to the preferred candidate, or NoCand.
1196 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1197
1198 // Assign bundles for the best candidate region.
1199 if (BestCand != NoCand) {
1200 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1201 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1202 UsedCands.push_back(BestCand);
1203 Cand.IntvIdx = SE->openIntv();
1204 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1205 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001206 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001207 }
1208 }
1209
1210 // Assign bundles for the compact region.
1211 if (HasCompact) {
1212 GlobalSplitCandidate &Cand = GlobalCand.front();
1213 assert(!Cand.PhysReg && "Compact region has no physreg");
1214 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1215 UsedCands.push_back(0);
1216 Cand.IntvIdx = SE->openIntv();
1217 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1218 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001219 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001220 }
1221 }
1222
1223 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001224 return 0;
1225}
1226
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001227
1228//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001229// Per-Block Splitting
1230//===----------------------------------------------------------------------===//
1231
1232/// tryBlockSplit - Split a global live range around every block with uses. This
1233/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1234/// they don't allocate.
1235unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1236 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1237 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1238 unsigned Reg = VirtReg.reg;
1239 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001240 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001241 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001242 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1243 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1244 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1245 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1246 SE->splitSingleBlock(BI);
1247 }
1248 // No blocks were split.
1249 if (LREdit.empty())
1250 return 0;
1251
1252 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001253 SmallVector<unsigned, 8> IntvMap;
1254 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001255
1256 // Tell LiveDebugVariables about the new ranges.
1257 DebugVars->splitRegister(Reg, LREdit.regs());
1258
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001259 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1260
1261 // Sort out the new intervals created by splitting. The remainder interval
1262 // goes straight to spilling, the new local ranges get to stay RS_New.
1263 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1264 LiveInterval &LI = *LREdit.get(i);
1265 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1266 setStage(LI, RS_Spill);
1267 }
1268
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001269 if (VerifyEnabled)
1270 MF->verify(this, "After splitting live range around basic blocks");
1271 return 0;
1272}
1273
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001274
1275//===----------------------------------------------------------------------===//
1276// Per-Instruction Splitting
1277//===----------------------------------------------------------------------===//
1278
1279/// tryInstructionSplit - Split a live range around individual instructions.
1280/// This is normally not worthwhile since the spiller is doing essentially the
1281/// same thing. However, when the live range is in a constrained register
1282/// class, it may help to insert copies such that parts of the live range can
1283/// be moved to a larger register class.
1284///
1285/// This is similar to spilling to a larger register class.
1286unsigned
1287RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1288 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1289 // There is no point to this if there are no larger sub-classes.
1290 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1291 return 0;
1292
1293 // Always enable split spill mode, since we're effectively spilling to a
1294 // register.
1295 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1296 SE->reset(LREdit, SplitEditor::SM_Size);
1297
1298 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1299 if (Uses.size() <= 1)
1300 return 0;
1301
1302 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1303
1304 // Split around every non-copy instruction.
1305 for (unsigned i = 0; i != Uses.size(); ++i) {
1306 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1307 if (MI->isFullCopy()) {
1308 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1309 continue;
1310 }
1311 SE->openIntv();
1312 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1313 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1314 SE->useIntv(SegStart, SegStop);
1315 }
1316
1317 if (LREdit.empty()) {
1318 DEBUG(dbgs() << "All uses were copies.\n");
1319 return 0;
1320 }
1321
1322 SmallVector<unsigned, 8> IntvMap;
1323 SE->finish(&IntvMap);
1324 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1325 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1326
1327 // Assign all new registers to RS_Spill. This was the last chance.
1328 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1329 return 0;
1330}
1331
1332
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001333//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001334// Local Splitting
1335//===----------------------------------------------------------------------===//
1336
1337
1338/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1339/// in order to use PhysReg between two entries in SA->UseSlots.
1340///
1341/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1342///
1343void RAGreedy::calcGapWeights(unsigned PhysReg,
1344 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001345 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1346 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001347 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001348 const unsigned NumGaps = Uses.size()-1;
1349
1350 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001351 SlotIndex StartIdx =
1352 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1353 SlotIndex StopIdx =
1354 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001355
1356 GapWeight.assign(NumGaps, 0.0f);
1357
1358 // Add interference from each overlapping register.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001359 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1360 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1361 .checkInterference())
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001362 continue;
1363
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001364 // We know that VirtReg is a continuous interval from FirstInstr to
1365 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001366 //
1367 // Interference that overlaps an instruction is counted in both gaps
1368 // surrounding the instruction. The exception is interference before
1369 // StartIdx and after StopIdx.
1370 //
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001371 LiveIntervalUnion::SegmentIter IntI =
1372 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001373 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1374 // Skip the gaps before IntI.
1375 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1376 if (++Gap == NumGaps)
1377 break;
1378 if (Gap == NumGaps)
1379 break;
1380
1381 // Update the gaps covered by IntI.
1382 const float weight = IntI.value()->weight;
1383 for (; Gap != NumGaps; ++Gap) {
1384 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1385 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1386 break;
1387 }
1388 if (Gap == NumGaps)
1389 break;
1390 }
1391 }
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001392
1393 // Add fixed interference.
1394 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1395 const LiveInterval &LI = LIS->getRegUnit(*Units);
1396 LiveInterval::const_iterator I = LI.find(StartIdx);
1397 LiveInterval::const_iterator E = LI.end();
1398
1399 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1400 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1401 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1402 if (++Gap == NumGaps)
1403 break;
1404 if (Gap == NumGaps)
1405 break;
1406
1407 for (; Gap != NumGaps; ++Gap) {
1408 GapWeight[Gap] = HUGE_VALF;
1409 if (Uses[Gap+1].getBaseIndex() >= I->end)
1410 break;
1411 }
1412 if (Gap == NumGaps)
1413 break;
1414 }
1415 }
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001416}
1417
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001418/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1419/// basic block.
1420///
1421unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1422 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001423 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1424 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001425
1426 // Note that it is possible to have an interval that is live-in or live-out
1427 // while only covering a single block - A phi-def can use undef values from
1428 // predecessors, and the block could be a single-block loop.
1429 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001430 // that the interval is continuous from FirstInstr to LastInstr. We should
1431 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001432
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001433 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001434 if (Uses.size() <= 2)
1435 return 0;
1436 const unsigned NumGaps = Uses.size()-1;
1437
1438 DEBUG({
1439 dbgs() << "tryLocalSplit: ";
1440 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001441 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001442 dbgs() << '\n';
1443 });
1444
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001445 // If VirtReg is live across any register mask operands, compute a list of
1446 // gaps with register masks.
1447 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001448 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001449 // Get regmask slots for the whole block.
1450 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001451 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001452 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001453 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1454 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001455 unsigned re = RMS.size();
1456 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001457 // Look for Uses[i] <= RMS <= Uses[i+1].
1458 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1459 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001460 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001461 // Skip a regmask on the same instruction as the last use. It doesn't
1462 // overlap the live range.
1463 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1464 break;
1465 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001466 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001467 // Advance ri to the next gap. A regmask on one of the uses counts in
1468 // both gaps.
1469 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1470 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001471 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001472 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001473 }
1474
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001475 // Since we allow local split results to be split again, there is a risk of
1476 // creating infinite loops. It is tempting to require that the new live
1477 // ranges have less instructions than the original. That would guarantee
1478 // convergence, but it is too strict. A live range with 3 instructions can be
1479 // split 2+3 (including the COPY), and we want to allow that.
1480 //
1481 // Instead we use these rules:
1482 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001483 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001484 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001485 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001486 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001487 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001488 // smaller ranges are marked RS_New.
1489 //
1490 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1491 // excessive splitting and infinite loops.
1492 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001493 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001494
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001495 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001496 unsigned BestBefore = NumGaps;
1497 unsigned BestAfter = 0;
1498 float BestDiff = 0;
1499
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001500 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001501 SmallVector<float, 8> GapWeight;
1502
1503 Order.rewind();
1504 while (unsigned PhysReg = Order.next()) {
1505 // Keep track of the largest spill weight that would need to be evicted in
1506 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1507 calcGapWeights(PhysReg, GapWeight);
1508
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001509 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001510 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001511 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1512 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1513
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001514 // Try to find the best sequence of gaps to close.
1515 // The new spill weight must be larger than any gap interference.
1516
1517 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001518 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001519
1520 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1521 // It is the spill weight that needs to be evicted.
1522 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001523
1524 for (;;) {
1525 // Live before/after split?
1526 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1527 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1528
1529 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1530 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1531 << " i=" << MaxGap);
1532
1533 // Stop before the interval gets so big we wouldn't be making progress.
1534 if (!LiveBefore && !LiveAfter) {
1535 DEBUG(dbgs() << " all\n");
1536 break;
1537 }
1538 // Should the interval be extended or shrunk?
1539 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001540
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001541 // How many gaps would the new range have?
1542 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1543
1544 // Legally, without causing looping?
1545 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1546
1547 if (Legal && MaxGap < HUGE_VALF) {
1548 // Estimate the new spill weight. Each instruction reads or writes the
1549 // register. Conservatively assume there are no read-modify-write
1550 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001551 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001552 // Try to guess the size of the new interval.
1553 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1554 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1555 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001556 // Would this split be possible to allocate?
1557 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001558 DEBUG(dbgs() << " w=" << EstWeight);
1559 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001560 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001561 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001562 if (Diff > BestDiff) {
1563 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001564 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001565 BestBefore = SplitBefore;
1566 BestAfter = SplitAfter;
1567 }
1568 }
1569 }
1570
1571 // Try to shrink.
1572 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001573 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001574 DEBUG(dbgs() << " shrink\n");
1575 // Recompute the max when necessary.
1576 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1577 MaxGap = GapWeight[SplitBefore];
1578 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1579 MaxGap = std::max(MaxGap, GapWeight[i]);
1580 }
1581 continue;
1582 }
1583 MaxGap = 0;
1584 }
1585
1586 // Try to extend the interval.
1587 if (SplitAfter >= NumGaps) {
1588 DEBUG(dbgs() << " end\n");
1589 break;
1590 }
1591
1592 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001593 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001594 }
1595 }
1596
1597 // Didn't find any candidates?
1598 if (BestBefore == NumGaps)
1599 return 0;
1600
1601 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1602 << '-' << Uses[BestAfter] << ", " << BestDiff
1603 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1604
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001605 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001606 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001607
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001608 SE->openIntv();
1609 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1610 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1611 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001612 SmallVector<unsigned, 8> IntvMap;
1613 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001614 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001615
1616 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001617 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001618 // leave the new intervals as RS_New so they can compete.
1619 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1620 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1621 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1622 if (NewGaps >= NumGaps) {
1623 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1624 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001625 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1626 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001627 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001628 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1629 }
1630 DEBUG(dbgs() << '\n');
1631 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001632 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001633
1634 return 0;
1635}
1636
1637//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001638// Live Range Splitting
1639//===----------------------------------------------------------------------===//
1640
1641/// trySplit - Try to split VirtReg or one of its interferences, making it
1642/// assignable.
1643/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1644unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1645 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001646 // Ranges must be Split2 or less.
1647 if (getStage(VirtReg) >= RS_Spill)
1648 return 0;
1649
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001650 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001651 if (LIS->intervalIsInOneMBB(VirtReg)) {
1652 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001653 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001654 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1655 if (PhysReg || !NewVRegs.empty())
1656 return PhysReg;
1657 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001658 }
1659
1660 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001661
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001662 SA->analyze(&VirtReg);
1663
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001664 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1665 // coalescer. That may cause the range to become allocatable which means that
1666 // tryRegionSplit won't be making progress. This check should be replaced with
1667 // an assertion when the coalescer is fixed.
1668 if (SA->didRepairRange()) {
1669 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001670 Matrix->invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001671 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1672 return PhysReg;
1673 }
1674
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001675 // First try to split around a region spanning multiple blocks. RS_Split2
1676 // ranges already made dubious progress with region splitting, so they go
1677 // straight to single block splitting.
1678 if (getStage(VirtReg) < RS_Split2) {
1679 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1680 if (PhysReg || !NewVRegs.empty())
1681 return PhysReg;
1682 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001683
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001684 // Then isolate blocks.
1685 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001686}
1687
1688
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001689//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001690// Main Entry Point
1691//===----------------------------------------------------------------------===//
1692
1693unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001694 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001695 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001696 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001697 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1698 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001699
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001700 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001701 DEBUG(dbgs() << StageName[Stage]
1702 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001703
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001704 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001705 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001706 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001707 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001708 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1709 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001710
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001711 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1712
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001713 // The first time we see a live range, don't try to split or spill.
1714 // Wait until the second time, when all smaller ranges have been allocated.
1715 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001716 if (Stage < RS_Split) {
1717 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001718 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001719 NewVRegs.push_back(&VirtReg);
1720 return 0;
1721 }
1722
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001723 // If we couldn't allocate a register from spilling, there is probably some
1724 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001725 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001726 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001727
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001728 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001729 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1730 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001731 return PhysReg;
1732
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001733 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001734 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001735 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001736 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001737 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001738
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001739 if (VerifyEnabled)
1740 MF->verify(this, "After spilling");
1741
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001742 // The live virtual register requesting allocation was spilled, so tell
1743 // the caller not to allocate anything during this round.
1744 return 0;
1745}
1746
1747bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1748 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1749 << "********** Function: "
1750 << ((Value*)mf.getFunction())->getName() << '\n');
1751
1752 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001753 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001754 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001755
Jakob Stoklund Olesend4348a22012-06-20 22:52:29 +00001756 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1757 getAnalysis<LiveIntervals>(),
1758 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001759 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001760 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001761 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001762 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001763 Bundles = &getAnalysis<EdgeBundles>();
1764 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001765 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001766
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001767 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001768 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001769 ExtraRegInfo.clear();
1770 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1771 NextCascade = 1;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001772 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001773 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001774
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001775 allocatePhysRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001776 releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001777 return true;
1778}