blob: 79253715c337ad1285f7183341f15b7e164672e8 [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000017#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000018#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000019#include "LiveDebugVariables.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000020#include "RegAllocBase.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "Spiller.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000025#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000026#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000027#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000028#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000029#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000030#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramer4eed7562013-06-17 19:00:36 +000032#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000033#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineLoopInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000037#include "llvm/CodeGen/RegAllocRegistry.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000038#include "llvm/CodeGen/VirtRegMap.h"
39#include "llvm/PassAnalysisSupport.h"
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000040#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000043#include "llvm/Support/Timer.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000044#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000045#include <queue>
46
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000047using namespace llvm;
48
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000049STATISTIC(NumGlobalSplits, "Number of split global live ranges");
50STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000051STATISTIC(NumEvicted, "Number of interferences evicted");
52
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000053static cl::opt<SplitEditor::ComplementSpillMode>
54SplitSpillMode("split-spill-mode", cl::Hidden,
55 cl::desc("Spill mode for splitting live ranges"),
56 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
57 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
58 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
59 clEnumValEnd),
60 cl::init(SplitEditor::SM_Partition));
61
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000062static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
63 createGreedyRegisterAllocator);
64
65namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000066class RAGreedy : public MachineFunctionPass,
67 public RegAllocBase,
68 private LiveRangeEdit::Delegate {
69
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000070 // context
71 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000072
73 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000074 SlotIndexes *Indexes;
Benjamin Kramer4eed7562013-06-17 19:00:36 +000075 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000076 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000077 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000078 EdgeBundles *Bundles;
79 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000080 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000081
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000082 // state
Andy Gibbs200241e2013-04-12 10:56:28 +000083 OwningPtr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000084 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000085 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000086
87 // Live ranges pass through a number of stages as we try to allocate them.
88 // Some of the stages may also create new live ranges:
89 //
90 // - Region splitting.
91 // - Per-block splitting.
92 // - Local splitting.
93 // - Spilling.
94 //
95 // Ranges produced by one of the stages skip the previous stages when they are
96 // dequeued. This improves performance because we can skip interference checks
97 // that are unlikely to give any results. It also guarantees that the live
98 // range splitting algorithm terminates, something that is otherwise hard to
99 // ensure.
100 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000101 /// Newly created live range that has never been queued.
102 RS_New,
103
104 /// Only attempt assignment and eviction. Then requeue as RS_Split.
105 RS_Assign,
106
107 /// Attempt live range splitting if assignment is impossible.
108 RS_Split,
109
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000110 /// Attempt more aggressive live range splitting that is guaranteed to make
111 /// progress. This is used for split products that may not be making
112 /// progress.
113 RS_Split2,
114
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000115 /// Live range will be spilled. No more splitting will be attempted.
116 RS_Spill,
117
118 /// There is nothing more we can do to this live range. Abort compilation
119 /// if it can't be assigned.
120 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000121 };
122
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000123 static const char *const StageName[];
124
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000125 // RegInfo - Keep additional information about each live range.
126 struct RegInfo {
127 LiveRangeStage Stage;
128
129 // Cascade - Eviction loop prevention. See canEvictInterference().
130 unsigned Cascade;
131
132 RegInfo() : Stage(RS_New), Cascade(0) {}
133 };
134
135 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000136
137 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000138 return ExtraRegInfo[VirtReg.reg].Stage;
139 }
140
141 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
142 ExtraRegInfo.resize(MRI->getNumVirtRegs());
143 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000144 }
145
146 template<typename Iterator>
147 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000148 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000149 for (;Begin != End; ++Begin) {
150 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000151 if (ExtraRegInfo[Reg].Stage == RS_New)
152 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000153 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000154 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000155
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000156 /// Cost of evicting interference.
157 struct EvictionCost {
158 unsigned BrokenHints; ///< Total number of broken hints.
159 float MaxWeight; ///< Maximum spill weight evicted.
160
161 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
162
Andrew Trick6ea2b962013-07-25 18:35:14 +0000163 bool isMax() const { return BrokenHints == ~0u; }
164
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000165 bool operator<(const EvictionCost &O) const {
166 if (BrokenHints != O.BrokenHints)
167 return BrokenHints < O.BrokenHints;
168 return MaxWeight < O.MaxWeight;
169 }
170 };
171
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000172 // splitting state.
Andy Gibbs200241e2013-04-12 10:56:28 +0000173 OwningPtr<SplitAnalysis> SA;
174 OwningPtr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000175
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000176 /// Cached per-block interference maps
177 InterferenceCache IntfCache;
178
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000179 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000180 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000181
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000182 /// Global live range splitting candidate info.
183 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000184 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000185 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000186
187 // SplitKit interval index for this candidate.
188 unsigned IntvIdx;
189
190 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000191 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000192
193 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000194 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000195 SmallVector<unsigned, 8> ActiveBlocks;
196
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000197 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000198 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000199 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000200 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000201 LiveBundles.clear();
202 ActiveBlocks.clear();
203 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000204
205 // Set B[i] = C for every live bundle where B[i] was NoCand.
206 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
207 unsigned Count = 0;
208 for (int i = LiveBundles.find_first(); i >= 0;
209 i = LiveBundles.find_next(i))
210 if (B[i] == NoCand) {
211 B[i] = C;
212 Count++;
213 }
214 return Count;
215 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000216 };
217
218 /// Candidate info for for each PhysReg in AllocationOrder.
219 /// This vector never shrinks, but grows to the size of the largest register
220 /// class.
221 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
222
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000223 enum { NoCand = ~0u };
224
225 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
226 /// NoCand which indicates the stack interval.
227 SmallVector<unsigned, 32> BundleCand;
228
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000229public:
230 RAGreedy();
231
232 /// Return the pass name.
233 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000234 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000235 }
236
237 /// RAGreedy analysis usage.
238 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000239 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000240 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000241 virtual void enqueue(LiveInterval *LI);
242 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000243 virtual unsigned selectOrSplit(LiveInterval&,
244 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000245
246 /// Perform register allocation.
247 virtual bool runOnMachineFunction(MachineFunction &mf);
248
249 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000250
251private:
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000252 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000253 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000254 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000255
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000256 BlockFrequency calcSpillCost();
257 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000258 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000259 void growRegion(GlobalSplitCandidate &Cand);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000260 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000261 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000262 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000263 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8adae962013-07-25 18:35:19 +0000264 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000265 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
266 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
267 void evictInterference(LiveInterval&, unsigned,
268 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000269
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000270 unsigned tryAssign(LiveInterval&, AllocationOrder&,
271 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000272 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000273 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000274 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
275 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000276 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
277 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +0000278 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
279 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000280 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
281 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000282 unsigned trySplit(LiveInterval&, AllocationOrder&,
283 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000284};
285} // end anonymous namespace
286
287char RAGreedy::ID = 0;
288
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000289#ifndef NDEBUG
290const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000291 "RS_New",
292 "RS_Assign",
293 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000294 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000295 "RS_Spill",
296 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000297};
298#endif
299
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000300// Hysteresis to use when comparing floats.
301// This helps stabilize decisions based on float comparisons.
302const float Hysteresis = 0.98f;
303
304
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000305FunctionPass* llvm::createGreedyRegisterAllocator() {
306 return new RAGreedy();
307}
308
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000309RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000310 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000311 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000312 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
313 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000314 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000315 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000316 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
317 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
318 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
319 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
320 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000321 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000322 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
323 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000324}
325
326void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
327 AU.setPreservesCFG();
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000328 AU.addRequired<MachineBlockFrequencyInfo>();
329 AU.addPreserved<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000330 AU.addRequired<AliasAnalysis>();
331 AU.addPreserved<AliasAnalysis>();
332 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000333 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000334 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000335 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000336 AU.addRequired<LiveDebugVariables>();
337 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000338 AU.addRequired<LiveStacks>();
339 AU.addPreserved<LiveStacks>();
Evan Chengbb36a432012-09-21 20:04:28 +0000340 AU.addRequired<CalculateSpillWeights>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000341 AU.addRequired<MachineDominatorTree>();
342 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000343 AU.addRequired<MachineLoopInfo>();
344 AU.addPreserved<MachineLoopInfo>();
345 AU.addRequired<VirtRegMap>();
346 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000347 AU.addRequired<LiveRegMatrix>();
348 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000349 AU.addRequired<EdgeBundles>();
350 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000351 MachineFunctionPass::getAnalysisUsage(AU);
352}
353
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000354
355//===----------------------------------------------------------------------===//
356// LiveRangeEdit delegate methods
357//===----------------------------------------------------------------------===//
358
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000359bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000360 if (VRM->hasPhys(VirtReg)) {
361 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000362 return true;
363 }
364 // Unassigned virtreg is probably in the priority queue.
365 // RegAllocBase will erase it after dequeueing.
366 return false;
367}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000368
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000369void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000370 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000371 return;
372
373 // Register is assigned, put it back on the queue for reassignment.
374 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000375 Matrix->unassign(LI);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000376 enqueue(&LI);
377}
378
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000379void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000380 // Cloning a register we haven't even heard about yet? Just ignore it.
381 if (!ExtraRegInfo.inBounds(Old))
382 return;
383
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000384 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000385 // be split into connected components. The new components are much smaller
386 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000387 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000388 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000389 ExtraRegInfo.grow(New);
390 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000391}
392
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000393void RAGreedy::releaseMemory() {
394 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000395 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000396 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000397}
398
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000399void RAGreedy::enqueue(LiveInterval *LI) {
400 // Prioritize live ranges by size, assigning larger ranges first.
401 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000402 const unsigned Size = LI->getSize();
403 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000404 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
405 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000406 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000407
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000408 ExtraRegInfo.grow(Reg);
409 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000410 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000411
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000412 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000413 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000414 // everything else has been allocated.
415 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000416 } else {
Andrew Trick6ea2b962013-07-25 18:35:14 +0000417 if (ExtraRegInfo[Reg].Stage == RS_Assign && !LI->empty() &&
418 LIS->intervalIsInOneMBB(*LI)) {
419 // Allocate original local ranges in linear instruction order. Since they
420 // are singly defined, this produces optimal coloring in the absence of
421 // global interference and other constraints.
422 Prio = LI->beginIndex().distance(Indexes->getLastIndex());
423 }
424 else {
425 // Allocate global and split ranges in long->short order. Long ranges that
426 // don't fit should be spilled (or split) ASAP so they don't create
427 // interference. Mark a bit to prioritize global above local ranges.
428 Prio = (1u << 29) + Size;
429 }
430 // Mark a higher bit to prioritize global and local above RS_Split.
431 Prio |= (1u << 31);
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000432
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000433 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesenfc637442012-12-03 23:23:50 +0000434 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000435 Prio |= (1u << 30);
436 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000437
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000438 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000439}
440
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000441LiveInterval *RAGreedy::dequeue() {
442 if (Queue.empty())
443 return 0;
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000444 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000445 Queue.pop();
446 return LI;
447}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000448
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000449
450//===----------------------------------------------------------------------===//
451// Direct Assignment
452//===----------------------------------------------------------------------===//
453
454/// tryAssign - Try to assign VirtReg to an available register.
455unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
456 AllocationOrder &Order,
457 SmallVectorImpl<LiveInterval*> &NewVRegs) {
458 Order.rewind();
459 unsigned PhysReg;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000460 while ((PhysReg = Order.next()))
461 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000462 break;
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000463 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000464 return PhysReg;
465
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000466 // PhysReg is available, but there may be a better choice.
467
468 // If we missed a simple hint, try to cheaply evict interference from the
469 // preferred register.
470 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000471 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000472 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
473 EvictionCost MaxCost(1);
474 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
475 evictInterference(VirtReg, Hint, NewVRegs);
476 return Hint;
477 }
478 }
479
480 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000481 unsigned Cost = TRI->getCostPerUse(PhysReg);
482
483 // Most registers have 0 additional cost.
484 if (!Cost)
485 return PhysReg;
486
487 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
488 << '\n');
489 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
490 return CheapReg ? CheapReg : PhysReg;
491}
492
493
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000494//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000495// Interference eviction
496//===----------------------------------------------------------------------===//
497
Andrew Trick8adae962013-07-25 18:35:19 +0000498unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
499 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
500 unsigned PhysReg;
501 while ((PhysReg = Order.next())) {
502 if (PhysReg == PrevReg)
503 continue;
504
505 MCRegUnitIterator Units(PhysReg, TRI);
506 for (; Units.isValid(); ++Units) {
507 // Instantiate a "subquery", not to be confused with the Queries array.
508 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
509 if (subQ.checkInterference())
510 break;
511 }
512 // If no units have interference, break out with the current PhysReg.
513 if (!Units.isValid())
514 break;
515 }
516 if (PhysReg)
517 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
518 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
519 << '\n');
520 return PhysReg;
521}
522
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000523/// shouldEvict - determine if A should evict the assigned live range B. The
524/// eviction policy defined by this function together with the allocation order
525/// defined by enqueue() decides which registers ultimately end up being split
526/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000527///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000528/// Cascade numbers are used to prevent infinite loops if this function is a
529/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000530///
531/// @param A The live range to be assigned.
532/// @param IsHint True when A is about to be assigned to its preferred
533/// register.
534/// @param B The live range to be evicted.
535/// @param BreaksHint True when B is already assigned to its preferred register.
536bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
537 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000538 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000539
540 // Be fairly aggressive about following hints as long as the evictee can be
541 // split.
542 if (CanSplit && IsHint && !BreaksHint)
543 return true;
544
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000545 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000546}
547
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000548/// canEvictInterference - Return true if all interferences between VirtReg and
549/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
550///
551/// @param VirtReg Live range that is about to be assigned.
552/// @param PhysReg Desired register for assignment.
Dmitri Gribenko67c89782012-09-12 16:59:47 +0000553/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000554/// @param MaxCost Only look for cheaper candidates and update with new cost
555/// when returning true.
556/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000557bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000558 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000559 // It is only possible to evict virtual register interference.
560 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
561 return false;
562
Andrew Trick6ea2b962013-07-25 18:35:14 +0000563 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
564
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000565 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
566 // involved in an eviction before. If a cascade number was assigned, deny
567 // evicting anything with the same or a newer cascade number. This prevents
568 // infinite eviction loops.
569 //
570 // This works out so a register without a cascade number is allowed to evict
571 // anything, and it can be evicted by anything.
572 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
573 if (!Cascade)
574 Cascade = NextCascade;
575
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000576 EvictionCost Cost;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000577 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
578 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000579 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000580 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000581 return false;
582
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000583 // Check if any interfering live range is heavier than MaxWeight.
584 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
585 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000586 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
587 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000588 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000589 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000590 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000591 // Once a live range becomes small enough, it is urgent that we find a
592 // register for it. This is indicated by an infinite spill weight. These
593 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000594 //
595 // Also allow urgent evictions of unspillable ranges from a strictly
596 // larger allocation order.
597 bool Urgent = !VirtReg.isSpillable() &&
598 (Intf->isSpillable() ||
599 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
600 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000601 // Only evict older cascades or live ranges without a cascade.
602 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
603 if (Cascade <= IntfCascade) {
604 if (!Urgent)
605 return false;
606 // We permit breaking cascades for urgent evictions. It should be the
607 // last resort, though, so make it really expensive.
608 Cost.BrokenHints += 10;
609 }
610 // Would this break a satisfied hint?
611 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
612 // Update eviction cost.
613 Cost.BrokenHints += BreaksHint;
614 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
615 // Abort if this would be too expensive.
616 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000617 return false;
Andrew Trick6ea2b962013-07-25 18:35:14 +0000618 if (Urgent)
619 continue;
620 // If !MaxCost.isMax(), then we're just looking for a cheap register.
621 // Evicting another local live range in this case could lead to suboptimal
622 // coloring.
Andrew Trick8adae962013-07-25 18:35:19 +0000623 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
624 !canReassign(*Intf, PhysReg)) {
Andrew Trick6ea2b962013-07-25 18:35:14 +0000625 return false;
Andrew Trick8adae962013-07-25 18:35:19 +0000626 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000627 // Finally, apply the eviction policy for non-urgent evictions.
Andrew Trick6ea2b962013-07-25 18:35:14 +0000628 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000629 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000630 }
631 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000632 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000633 return true;
634}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000635
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000636/// evictInterference - Evict any interferring registers that prevent VirtReg
637/// from being assigned to Physreg. This assumes that canEvictInterference
638/// returned true.
639void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
640 SmallVectorImpl<LiveInterval*> &NewVRegs) {
641 // Make sure that VirtReg has a cascade number, and assign that cascade
642 // number to every evicted register. These live ranges than then only be
643 // evicted by a newer cascade, preventing infinite loops.
644 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
645 if (!Cascade)
646 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
647
648 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
649 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000650
651 // Collect all interfering virtregs first.
652 SmallVector<LiveInterval*, 8> Intfs;
653 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
654 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000655 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000656 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
657 Intfs.append(IVR.begin(), IVR.end());
658 }
659
660 // Evict them second. This will invalidate the queries.
661 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
662 LiveInterval *Intf = Intfs[i];
663 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
664 if (!VRM->hasPhys(Intf->reg))
665 continue;
666 Matrix->unassign(*Intf);
667 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
668 VirtReg.isSpillable() < Intf->isSpillable()) &&
669 "Cannot decrease cascade number, illegal eviction");
670 ExtraRegInfo[Intf->reg].Cascade = Cascade;
671 ++NumEvicted;
672 NewVRegs.push_back(Intf);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000673 }
674}
675
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000676/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000677/// @param VirtReg Currently unassigned virtual register.
678/// @param Order Physregs to try.
679/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000680unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
681 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000682 SmallVectorImpl<LiveInterval*> &NewVRegs,
683 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000684 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
685
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000686 // Keep track of the cheapest interference seen so far.
687 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000688 unsigned BestPhys = 0;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000689 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000690
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000691 // When we are just looking for a reduced cost per use, don't break any
692 // hints, and only evict smaller spill weights.
693 if (CostPerUseLimit < ~0u) {
694 BestCost.BrokenHints = 0;
695 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000696
697 // Check of any registers in RC are below CostPerUseLimit.
698 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
699 unsigned MinCost = RegClassInfo.getMinCost(RC);
700 if (MinCost >= CostPerUseLimit) {
701 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
702 << ", no cheaper registers to be found.\n");
703 return 0;
704 }
705
706 // It is normal for register classes to have a long tail of registers with
707 // the same cost. We don't need to look at them if they're too expensive.
708 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
709 OrderLimit = RegClassInfo.getLastCostChange(RC);
710 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
711 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000712 }
713
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000714 Order.rewind();
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000715 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000716 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
717 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000718 // The first use of a callee-saved register in a function has cost 1.
719 // Don't start using a CSR when the CostPerUseLimit is low.
720 if (CostPerUseLimit == 1)
721 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
722 if (!MRI->isPhysRegUsed(CSR)) {
723 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
724 << PrintReg(CSR, TRI) << '\n');
725 continue;
726 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000727
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000728 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000729 continue;
730
731 // Best so far.
732 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000733
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000734 // Stop if the hint can be used.
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000735 if (Order.isHint())
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000736 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000737 }
738
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000739 if (!BestPhys)
740 return 0;
741
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000742 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000743 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000744}
745
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000746
747//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000748// Region Splitting
749//===----------------------------------------------------------------------===//
750
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000751/// addSplitConstraints - Fill out the SplitConstraints vector based on the
752/// interference pattern in Physreg and its aliases. Add the constraints to
753/// SpillPlacement and return the static cost of this split in Cost, assuming
754/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000755/// Return false if there are no bundles with positive bias.
756bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000757 BlockFrequency &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000758 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000759
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000760 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000761 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000762 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000763 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
764 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000765 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000766
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000767 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000768 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000769 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
770 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie453f4f02013-05-15 07:36:59 +0000771 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000772
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000773 if (!Intf.hasInterference())
774 continue;
775
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000776 // Number of spill code instructions to insert.
777 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000778
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000779 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000780 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000781 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000782 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000783 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000784 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000785 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000786 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000787 }
788
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000789 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000790 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000791 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000792 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000793 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000794 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000795 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000796 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000797 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000798
799 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000800 while (Ins--)
801 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000802 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000803 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000804
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000805 // Add constraints for use-blocks. Note that these are the only constraints
806 // that may add a positive bias, it is downhill from here.
807 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000808 return SpillPlacer->scanActiveBundles();
809}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000810
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000811
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000812/// addThroughConstraints - Add constraints and links to SpillPlacer from the
813/// live-through blocks in Blocks.
814void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
815 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000816 const unsigned GroupSize = 8;
817 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000818 unsigned TBS[GroupSize];
819 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000820
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000821 for (unsigned i = 0; i != Blocks.size(); ++i) {
822 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000823 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000824
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000825 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000826 assert(T < GroupSize && "Array overflow");
827 TBS[T] = Number;
828 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000829 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000830 T = 0;
831 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000832 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000833 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000834
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000835 assert(B < GroupSize && "Array overflow");
836 BCS[B].Number = Number;
837
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000838 // Interference for the live-in value.
839 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
840 BCS[B].Entry = SpillPlacement::MustSpill;
841 else
842 BCS[B].Entry = SpillPlacement::PrefSpill;
843
844 // Interference for the live-out value.
845 if (Intf.last() >= SA->getLastSplitPoint(Number))
846 BCS[B].Exit = SpillPlacement::MustSpill;
847 else
848 BCS[B].Exit = SpillPlacement::PrefSpill;
849
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000850 if (++B == GroupSize) {
851 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
852 SpillPlacer->addConstraints(Array);
853 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000854 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000855 }
856
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000857 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
858 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000859 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000860}
861
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000862void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000863 // Keep track of through blocks that have not been added to SpillPlacer.
864 BitVector Todo = SA->getThroughBlocks();
865 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
866 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000867#ifndef NDEBUG
868 unsigned Visited = 0;
869#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000870
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000871 for (;;) {
872 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000873 // Find new through blocks in the periphery of PrefRegBundles.
874 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
875 unsigned Bundle = NewBundles[i];
876 // Look at all blocks connected to Bundle in the full graph.
877 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
878 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
879 I != E; ++I) {
880 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000881 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000882 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000883 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000884 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000885 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000886#ifndef NDEBUG
887 ++Visited;
888#endif
889 }
890 }
891 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000892 if (ActiveBlocks.size() == AddedTo)
893 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000894
895 // Compute through constraints from the interference, or assume that all
896 // through blocks prefer spilling when forming compact regions.
897 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
898 if (Cand.PhysReg)
899 addThroughConstraints(Cand.Intf, NewBlocks);
900 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000901 // Provide a strong negative bias on through blocks to prevent unwanted
902 // liveness on loop backedges.
903 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000904 AddedTo = ActiveBlocks.size();
905
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000906 // Perhaps iterating can enable more bundles?
907 SpillPlacer->iterate();
908 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000909 DEBUG(dbgs() << ", v=" << Visited);
910}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000911
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000912/// calcCompactRegion - Compute the set of edge bundles that should be live
913/// when splitting the current live range into compact regions. Compact
914/// regions can be computed without looking at interference. They are the
915/// regions formed by removing all the live-through blocks from the live range.
916///
917/// Returns false if the current live range is already compact, or if the
918/// compact regions would form single block regions anyway.
919bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
920 // Without any through blocks, the live range is already compact.
921 if (!SA->getNumThroughBlocks())
922 return false;
923
924 // Compact regions don't correspond to any physreg.
925 Cand.reset(IntfCache, 0);
926
927 DEBUG(dbgs() << "Compact region bundles");
928
929 // Use the spill placer to determine the live bundles. GrowRegion pretends
930 // that all the through blocks have interference when PhysReg is unset.
931 SpillPlacer->prepare(Cand.LiveBundles);
932
933 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000934 BlockFrequency Cost;
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000935 if (!addSplitConstraints(Cand.Intf, Cost)) {
936 DEBUG(dbgs() << ", none.\n");
937 return false;
938 }
939
940 growRegion(Cand);
941 SpillPlacer->finish();
942
943 if (!Cand.LiveBundles.any()) {
944 DEBUG(dbgs() << ", none.\n");
945 return false;
946 }
947
948 DEBUG({
949 for (int i = Cand.LiveBundles.find_first(); i>=0;
950 i = Cand.LiveBundles.find_next(i))
951 dbgs() << " EB#" << i;
952 dbgs() << ".\n";
953 });
954 return true;
955}
956
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000957/// calcSpillCost - Compute how expensive it would be to split the live range in
958/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000959BlockFrequency RAGreedy::calcSpillCost() {
960 BlockFrequency Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000961 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
962 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
963 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
964 unsigned Number = BI.MBB->getNumber();
965 // We normally only need one spill instruction - a load or a store.
966 Cost += SpillPlacer->getBlockFrequency(Number);
967
968 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000969 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
970 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000971 }
972 return Cost;
973}
974
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000975/// calcGlobalSplitCost - Return the global split cost of following the split
976/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000977/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000978///
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000979BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
980 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000981 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000982 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
983 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
984 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000985 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000986 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
987 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
988 unsigned Ins = 0;
989
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000990 if (BI.LiveIn)
991 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
992 if (BI.LiveOut)
993 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000994 while (Ins--)
995 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000996 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000997
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000998 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
999 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001000 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1001 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +00001002 if (!RegIn && !RegOut)
1003 continue;
1004 if (RegIn && RegOut) {
1005 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001006 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001007 if (Cand.Intf.hasInterference()) {
1008 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1009 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1010 }
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +00001011 continue;
1012 }
1013 // live-in / stack-out or stack-in live-out.
1014 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001015 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001016 return GlobalCost;
1017}
1018
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001019/// splitAroundRegion - Split the current live range around the regions
1020/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001021///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001022/// Before calling this function, GlobalCand and BundleCand must be initialized
1023/// so each bundle is assigned to a valid candidate, or NoCand for the
1024/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1025/// objects must be initialized for the current live range, and intervals
1026/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001027///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001028/// @param LREdit The LiveRangeEdit object handling the current split.
1029/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1030/// must appear in this list.
1031void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1032 ArrayRef<unsigned> UsedCands) {
1033 // These are the intervals created for new global ranges. We may create more
1034 // intervals for local ranges.
1035 const unsigned NumGlobalIntvs = LREdit.size();
1036 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1037 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001038
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001039 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +00001040 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001041 // is all copies.
1042 unsigned Reg = SA->getParent().reg;
1043 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1044
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001045 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001046 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1047 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1048 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001049 unsigned Number = BI.MBB->getNumber();
1050 unsigned IntvIn = 0, IntvOut = 0;
1051 SlotIndex IntfIn, IntfOut;
1052 if (BI.LiveIn) {
1053 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1054 if (CandIn != NoCand) {
1055 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1056 IntvIn = Cand.IntvIdx;
1057 Cand.Intf.moveToBlock(Number);
1058 IntfIn = Cand.Intf.first();
1059 }
1060 }
1061 if (BI.LiveOut) {
1062 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1063 if (CandOut != NoCand) {
1064 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1065 IntvOut = Cand.IntvIdx;
1066 Cand.Intf.moveToBlock(Number);
1067 IntfOut = Cand.Intf.last();
1068 }
1069 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001070
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001071 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001072 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001073 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001074 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001075 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001076 continue;
1077 }
1078
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001079 if (IntvIn && IntvOut)
1080 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1081 else if (IntvIn)
1082 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001083 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001084 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001085 }
1086
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001087 // Handle live-through blocks. The relevant live-through blocks are stored in
1088 // the ActiveBlocks list with each candidate. We need to filter out
1089 // duplicates.
1090 BitVector Todo = SA->getThroughBlocks();
1091 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1092 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1093 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1094 unsigned Number = Blocks[i];
1095 if (!Todo.test(Number))
1096 continue;
1097 Todo.reset(Number);
1098
1099 unsigned IntvIn = 0, IntvOut = 0;
1100 SlotIndex IntfIn, IntfOut;
1101
1102 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1103 if (CandIn != NoCand) {
1104 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1105 IntvIn = Cand.IntvIdx;
1106 Cand.Intf.moveToBlock(Number);
1107 IntfIn = Cand.Intf.first();
1108 }
1109
1110 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1111 if (CandOut != NoCand) {
1112 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1113 IntvOut = Cand.IntvIdx;
1114 Cand.Intf.moveToBlock(Number);
1115 IntfOut = Cand.Intf.last();
1116 }
1117 if (!IntvIn && !IntvOut)
1118 continue;
1119 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1120 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001121 }
1122
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001123 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001124
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001125 SmallVector<unsigned, 8> IntvMap;
1126 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001127 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001128
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001129 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001130 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001131
1132 // Sort out the new intervals created by splitting. We get four kinds:
1133 // - Remainder intervals should not be split again.
1134 // - Candidate intervals can be assigned to Cand.PhysReg.
1135 // - Block-local splits are candidates for local splitting.
1136 // - DCE leftovers should go back on the queue.
1137 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001138 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001139
1140 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001141 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001142 continue;
1143
1144 // Remainder interval. Don't try splitting again, spill if it doesn't
1145 // allocate.
1146 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001147 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001148 continue;
1149 }
1150
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001151 // Global intervals. Allow repeated splitting as long as the number of live
1152 // blocks is strictly decreasing.
1153 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001154 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001155 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1156 << " blocks as original.\n");
1157 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001158 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001159 }
1160 continue;
1161 }
1162
1163 // Other intervals are treated as new. This includes local intervals created
1164 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001165 }
1166
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001167 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001168 MF->verify(this, "After splitting live range around region");
1169}
1170
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001171unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1172 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001173 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001174 unsigned BestCand = NoCand;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001175 BlockFrequency BestCost;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001176 SmallVector<unsigned, 8> UsedCands;
1177
1178 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001179 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001180 if (HasCompact) {
1181 // Yes, keep GlobalCand[0] as the compact region candidate.
1182 NumCands = 1;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001183 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001184 } else {
1185 // No benefit from the compact region, our fallback will be per-block
1186 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001187 BestCost = calcSpillCost();
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001188 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1189 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001190
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001191 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001192 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001193 // Discard bad candidates before we run out of interference cache cursors.
1194 // This will only affect register classes with a lot of registers (>32).
1195 if (NumCands == IntfCache.getMaxCursors()) {
1196 unsigned WorstCount = ~0u;
1197 unsigned Worst = 0;
1198 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001199 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001200 continue;
1201 unsigned Count = GlobalCand[i].LiveBundles.count();
1202 if (Count < WorstCount)
1203 Worst = i, WorstCount = Count;
1204 }
1205 --NumCands;
1206 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001207 if (BestCand == NumCands)
1208 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001209 }
1210
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001211 if (GlobalCand.size() <= NumCands)
1212 GlobalCand.resize(NumCands+1);
1213 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1214 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001215
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001216 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001217 BlockFrequency Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001218 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001219 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001220 continue;
1221 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001222 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001223 if (Cost >= BestCost) {
1224 DEBUG({
1225 if (BestCand == NoCand)
1226 dbgs() << " worse than no bundles\n";
1227 else
1228 dbgs() << " worse than "
1229 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1230 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001231 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001232 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001233 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001234
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001235 SpillPlacer->finish();
1236
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001237 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001238 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001239 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001240 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001241 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001242
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001243 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001244 DEBUG({
1245 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001246 for (int i = Cand.LiveBundles.find_first(); i>=0;
1247 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001248 dbgs() << " EB#" << i;
1249 dbgs() << ".\n";
1250 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001251 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001252 BestCand = NumCands;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001253 BestCost = Cost;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001254 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001255 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001256 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001257
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001258 // No solutions found, fall back to single block splitting.
1259 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001260 return 0;
1261
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001262 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001263 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001264 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001265
1266 // Assign all edge bundles to the preferred candidate, or NoCand.
1267 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1268
1269 // Assign bundles for the best candidate region.
1270 if (BestCand != NoCand) {
1271 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1272 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1273 UsedCands.push_back(BestCand);
1274 Cand.IntvIdx = SE->openIntv();
1275 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1276 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001277 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001278 }
1279 }
1280
1281 // Assign bundles for the compact region.
1282 if (HasCompact) {
1283 GlobalSplitCandidate &Cand = GlobalCand.front();
1284 assert(!Cand.PhysReg && "Compact region has no physreg");
1285 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1286 UsedCands.push_back(0);
1287 Cand.IntvIdx = SE->openIntv();
1288 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1289 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001290 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001291 }
1292 }
1293
1294 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001295 return 0;
1296}
1297
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001298
1299//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001300// Per-Block Splitting
1301//===----------------------------------------------------------------------===//
1302
1303/// tryBlockSplit - Split a global live range around every block with uses. This
1304/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1305/// they don't allocate.
1306unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1307 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1308 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1309 unsigned Reg = VirtReg.reg;
1310 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001311 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001312 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001313 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1314 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1315 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1316 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1317 SE->splitSingleBlock(BI);
1318 }
1319 // No blocks were split.
1320 if (LREdit.empty())
1321 return 0;
1322
1323 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001324 SmallVector<unsigned, 8> IntvMap;
1325 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001326
1327 // Tell LiveDebugVariables about the new ranges.
1328 DebugVars->splitRegister(Reg, LREdit.regs());
1329
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001330 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1331
1332 // Sort out the new intervals created by splitting. The remainder interval
1333 // goes straight to spilling, the new local ranges get to stay RS_New.
1334 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1335 LiveInterval &LI = *LREdit.get(i);
1336 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1337 setStage(LI, RS_Spill);
1338 }
1339
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001340 if (VerifyEnabled)
1341 MF->verify(this, "After splitting live range around basic blocks");
1342 return 0;
1343}
1344
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001345
1346//===----------------------------------------------------------------------===//
1347// Per-Instruction Splitting
1348//===----------------------------------------------------------------------===//
1349
1350/// tryInstructionSplit - Split a live range around individual instructions.
1351/// This is normally not worthwhile since the spiller is doing essentially the
1352/// same thing. However, when the live range is in a constrained register
1353/// class, it may help to insert copies such that parts of the live range can
1354/// be moved to a larger register class.
1355///
1356/// This is similar to spilling to a larger register class.
1357unsigned
1358RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1359 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1360 // There is no point to this if there are no larger sub-classes.
1361 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1362 return 0;
1363
1364 // Always enable split spill mode, since we're effectively spilling to a
1365 // register.
1366 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1367 SE->reset(LREdit, SplitEditor::SM_Size);
1368
1369 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1370 if (Uses.size() <= 1)
1371 return 0;
1372
1373 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1374
1375 // Split around every non-copy instruction.
1376 for (unsigned i = 0; i != Uses.size(); ++i) {
1377 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1378 if (MI->isFullCopy()) {
1379 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1380 continue;
1381 }
1382 SE->openIntv();
1383 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1384 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1385 SE->useIntv(SegStart, SegStop);
1386 }
1387
1388 if (LREdit.empty()) {
1389 DEBUG(dbgs() << "All uses were copies.\n");
1390 return 0;
1391 }
1392
1393 SmallVector<unsigned, 8> IntvMap;
1394 SE->finish(&IntvMap);
1395 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1396 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1397
1398 // Assign all new registers to RS_Spill. This was the last chance.
1399 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1400 return 0;
1401}
1402
1403
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001404//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001405// Local Splitting
1406//===----------------------------------------------------------------------===//
1407
1408
1409/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1410/// in order to use PhysReg between two entries in SA->UseSlots.
1411///
1412/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1413///
1414void RAGreedy::calcGapWeights(unsigned PhysReg,
1415 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001416 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1417 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001418 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001419 const unsigned NumGaps = Uses.size()-1;
1420
1421 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001422 SlotIndex StartIdx =
1423 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1424 SlotIndex StopIdx =
1425 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001426
1427 GapWeight.assign(NumGaps, 0.0f);
1428
1429 // Add interference from each overlapping register.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001430 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1431 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1432 .checkInterference())
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001433 continue;
1434
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001435 // We know that VirtReg is a continuous interval from FirstInstr to
1436 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001437 //
1438 // Interference that overlaps an instruction is counted in both gaps
1439 // surrounding the instruction. The exception is interference before
1440 // StartIdx and after StopIdx.
1441 //
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001442 LiveIntervalUnion::SegmentIter IntI =
1443 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001444 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1445 // Skip the gaps before IntI.
1446 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1447 if (++Gap == NumGaps)
1448 break;
1449 if (Gap == NumGaps)
1450 break;
1451
1452 // Update the gaps covered by IntI.
1453 const float weight = IntI.value()->weight;
1454 for (; Gap != NumGaps; ++Gap) {
1455 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1456 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1457 break;
1458 }
1459 if (Gap == NumGaps)
1460 break;
1461 }
1462 }
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001463
1464 // Add fixed interference.
1465 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1466 const LiveInterval &LI = LIS->getRegUnit(*Units);
1467 LiveInterval::const_iterator I = LI.find(StartIdx);
1468 LiveInterval::const_iterator E = LI.end();
1469
1470 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1471 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1472 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1473 if (++Gap == NumGaps)
1474 break;
1475 if (Gap == NumGaps)
1476 break;
1477
1478 for (; Gap != NumGaps; ++Gap) {
1479 GapWeight[Gap] = HUGE_VALF;
1480 if (Uses[Gap+1].getBaseIndex() >= I->end)
1481 break;
1482 }
1483 if (Gap == NumGaps)
1484 break;
1485 }
1486 }
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001487}
1488
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001489/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1490/// basic block.
1491///
1492unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1493 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001494 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1495 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001496
1497 // Note that it is possible to have an interval that is live-in or live-out
1498 // while only covering a single block - A phi-def can use undef values from
1499 // predecessors, and the block could be a single-block loop.
1500 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001501 // that the interval is continuous from FirstInstr to LastInstr. We should
1502 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001503
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001504 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001505 if (Uses.size() <= 2)
1506 return 0;
1507 const unsigned NumGaps = Uses.size()-1;
1508
1509 DEBUG({
1510 dbgs() << "tryLocalSplit: ";
1511 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001512 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001513 dbgs() << '\n';
1514 });
1515
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001516 // If VirtReg is live across any register mask operands, compute a list of
1517 // gaps with register masks.
1518 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001519 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001520 // Get regmask slots for the whole block.
1521 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001522 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001523 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001524 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1525 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001526 unsigned re = RMS.size();
1527 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001528 // Look for Uses[i] <= RMS <= Uses[i+1].
1529 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1530 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001531 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001532 // Skip a regmask on the same instruction as the last use. It doesn't
1533 // overlap the live range.
1534 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1535 break;
1536 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001537 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001538 // Advance ri to the next gap. A regmask on one of the uses counts in
1539 // both gaps.
1540 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1541 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001542 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001543 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001544 }
1545
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001546 // Since we allow local split results to be split again, there is a risk of
1547 // creating infinite loops. It is tempting to require that the new live
1548 // ranges have less instructions than the original. That would guarantee
1549 // convergence, but it is too strict. A live range with 3 instructions can be
1550 // split 2+3 (including the COPY), and we want to allow that.
1551 //
1552 // Instead we use these rules:
1553 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001554 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001555 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001556 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001557 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001558 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001559 // smaller ranges are marked RS_New.
1560 //
1561 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1562 // excessive splitting and infinite loops.
1563 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001564 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001565
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001566 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001567 unsigned BestBefore = NumGaps;
1568 unsigned BestAfter = 0;
1569 float BestDiff = 0;
1570
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001571 const float blockFreq =
1572 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1573 (1.0f / BlockFrequency::getEntryFrequency());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001574 SmallVector<float, 8> GapWeight;
1575
1576 Order.rewind();
1577 while (unsigned PhysReg = Order.next()) {
1578 // Keep track of the largest spill weight that would need to be evicted in
1579 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1580 calcGapWeights(PhysReg, GapWeight);
1581
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001582 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001583 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001584 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1585 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1586
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001587 // Try to find the best sequence of gaps to close.
1588 // The new spill weight must be larger than any gap interference.
1589
1590 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001591 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001592
1593 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1594 // It is the spill weight that needs to be evicted.
1595 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001596
1597 for (;;) {
1598 // Live before/after split?
1599 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1600 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1601
1602 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1603 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1604 << " i=" << MaxGap);
1605
1606 // Stop before the interval gets so big we wouldn't be making progress.
1607 if (!LiveBefore && !LiveAfter) {
1608 DEBUG(dbgs() << " all\n");
1609 break;
1610 }
1611 // Should the interval be extended or shrunk?
1612 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001613
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001614 // How many gaps would the new range have?
1615 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1616
1617 // Legally, without causing looping?
1618 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1619
1620 if (Legal && MaxGap < HUGE_VALF) {
1621 // Estimate the new spill weight. Each instruction reads or writes the
1622 // register. Conservatively assume there are no read-modify-write
1623 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001624 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001625 // Try to guess the size of the new interval.
1626 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1627 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1628 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001629 // Would this split be possible to allocate?
1630 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001631 DEBUG(dbgs() << " w=" << EstWeight);
1632 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001633 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001634 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001635 if (Diff > BestDiff) {
1636 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001637 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001638 BestBefore = SplitBefore;
1639 BestAfter = SplitAfter;
1640 }
1641 }
1642 }
1643
1644 // Try to shrink.
1645 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001646 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001647 DEBUG(dbgs() << " shrink\n");
1648 // Recompute the max when necessary.
1649 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1650 MaxGap = GapWeight[SplitBefore];
1651 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1652 MaxGap = std::max(MaxGap, GapWeight[i]);
1653 }
1654 continue;
1655 }
1656 MaxGap = 0;
1657 }
1658
1659 // Try to extend the interval.
1660 if (SplitAfter >= NumGaps) {
1661 DEBUG(dbgs() << " end\n");
1662 break;
1663 }
1664
1665 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001666 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001667 }
1668 }
1669
1670 // Didn't find any candidates?
1671 if (BestBefore == NumGaps)
1672 return 0;
1673
1674 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1675 << '-' << Uses[BestAfter] << ", " << BestDiff
1676 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1677
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001678 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001679 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001680
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001681 SE->openIntv();
1682 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1683 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1684 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001685 SmallVector<unsigned, 8> IntvMap;
1686 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001687 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001688
1689 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001690 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001691 // leave the new intervals as RS_New so they can compete.
1692 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1693 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1694 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1695 if (NewGaps >= NumGaps) {
1696 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1697 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001698 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1699 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001700 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001701 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1702 }
1703 DEBUG(dbgs() << '\n');
1704 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001705 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001706
1707 return 0;
1708}
1709
1710//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001711// Live Range Splitting
1712//===----------------------------------------------------------------------===//
1713
1714/// trySplit - Try to split VirtReg or one of its interferences, making it
1715/// assignable.
1716/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1717unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1718 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001719 // Ranges must be Split2 or less.
1720 if (getStage(VirtReg) >= RS_Spill)
1721 return 0;
1722
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001723 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001724 if (LIS->intervalIsInOneMBB(VirtReg)) {
1725 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001726 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001727 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1728 if (PhysReg || !NewVRegs.empty())
1729 return PhysReg;
1730 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001731 }
1732
1733 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001734
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001735 SA->analyze(&VirtReg);
1736
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001737 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1738 // coalescer. That may cause the range to become allocatable which means that
1739 // tryRegionSplit won't be making progress. This check should be replaced with
1740 // an assertion when the coalescer is fixed.
1741 if (SA->didRepairRange()) {
1742 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001743 Matrix->invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001744 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1745 return PhysReg;
1746 }
1747
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001748 // First try to split around a region spanning multiple blocks. RS_Split2
1749 // ranges already made dubious progress with region splitting, so they go
1750 // straight to single block splitting.
1751 if (getStage(VirtReg) < RS_Split2) {
1752 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1753 if (PhysReg || !NewVRegs.empty())
1754 return PhysReg;
1755 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001756
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001757 // Then isolate blocks.
1758 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001759}
1760
1761
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001762//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001763// Main Entry Point
1764//===----------------------------------------------------------------------===//
1765
1766unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001767 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001768 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001769 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001770 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1771 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001772
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001773 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001774 DEBUG(dbgs() << StageName[Stage]
1775 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001776
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001777 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001778 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001779 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001780 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001781 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1782 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001783
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001784 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1785
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001786 // The first time we see a live range, don't try to split or spill.
1787 // Wait until the second time, when all smaller ranges have been allocated.
1788 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001789 if (Stage < RS_Split) {
1790 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001791 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001792 NewVRegs.push_back(&VirtReg);
1793 return 0;
1794 }
1795
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001796 // If we couldn't allocate a register from spilling, there is probably some
1797 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001798 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001799 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001800
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001801 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001802 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1803 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001804 return PhysReg;
1805
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001806 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001807 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001808 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001809 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001810 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001811
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001812 if (VerifyEnabled)
1813 MF->verify(this, "After spilling");
1814
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001815 // The live virtual register requesting allocation was spilled, so tell
1816 // the caller not to allocate anything during this round.
1817 return 0;
1818}
1819
1820bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1821 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikie986d76d2012-08-22 17:18:53 +00001822 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001823
1824 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001825 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001826 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001827
Jakob Stoklund Olesend4348a22012-06-20 22:52:29 +00001828 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1829 getAnalysis<LiveIntervals>(),
1830 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001831 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramer4eed7562013-06-17 19:00:36 +00001832 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001833 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001834 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001835 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001836 Bundles = &getAnalysis<EdgeBundles>();
1837 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001838 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001839
Andrew Trick5dca6132013-07-25 07:26:26 +00001840 DEBUG(LIS->dump());
1841
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001842 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramer4eed7562013-06-17 19:00:36 +00001843 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001844 ExtraRegInfo.clear();
1845 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1846 NextCascade = 1;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001847 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001848 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001849
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001850 allocatePhysRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001851 releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001852 return true;
1853}