blob: 87b11a5f51c0691e05f73b5fa08dbfc3011bd755 [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 }
Andrew Trickbef4c3e2013-07-25 18:35:22 +0000437 // The virtual register number is a tie breaker for same-sized ranges.
438 // Give lower vreg numbers higher priority to assign them first.
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000439 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000440}
441
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000442LiveInterval *RAGreedy::dequeue() {
443 if (Queue.empty())
444 return 0;
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000445 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000446 Queue.pop();
447 return LI;
448}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000449
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000450
451//===----------------------------------------------------------------------===//
452// Direct Assignment
453//===----------------------------------------------------------------------===//
454
455/// tryAssign - Try to assign VirtReg to an available register.
456unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
457 AllocationOrder &Order,
458 SmallVectorImpl<LiveInterval*> &NewVRegs) {
459 Order.rewind();
460 unsigned PhysReg;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000461 while ((PhysReg = Order.next()))
462 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000463 break;
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000464 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000465 return PhysReg;
466
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000467 // PhysReg is available, but there may be a better choice.
468
469 // If we missed a simple hint, try to cheaply evict interference from the
470 // preferred register.
471 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000472 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000473 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
474 EvictionCost MaxCost(1);
475 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
476 evictInterference(VirtReg, Hint, NewVRegs);
477 return Hint;
478 }
479 }
480
481 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000482 unsigned Cost = TRI->getCostPerUse(PhysReg);
483
484 // Most registers have 0 additional cost.
485 if (!Cost)
486 return PhysReg;
487
488 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
489 << '\n');
490 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
491 return CheapReg ? CheapReg : PhysReg;
492}
493
494
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000495//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000496// Interference eviction
497//===----------------------------------------------------------------------===//
498
Andrew Trick8adae962013-07-25 18:35:19 +0000499unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
500 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
501 unsigned PhysReg;
502 while ((PhysReg = Order.next())) {
503 if (PhysReg == PrevReg)
504 continue;
505
506 MCRegUnitIterator Units(PhysReg, TRI);
507 for (; Units.isValid(); ++Units) {
508 // Instantiate a "subquery", not to be confused with the Queries array.
509 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
510 if (subQ.checkInterference())
511 break;
512 }
513 // If no units have interference, break out with the current PhysReg.
514 if (!Units.isValid())
515 break;
516 }
517 if (PhysReg)
518 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
519 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
520 << '\n');
521 return PhysReg;
522}
523
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000524/// shouldEvict - determine if A should evict the assigned live range B. The
525/// eviction policy defined by this function together with the allocation order
526/// defined by enqueue() decides which registers ultimately end up being split
527/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000528///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000529/// Cascade numbers are used to prevent infinite loops if this function is a
530/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000531///
532/// @param A The live range to be assigned.
533/// @param IsHint True when A is about to be assigned to its preferred
534/// register.
535/// @param B The live range to be evicted.
536/// @param BreaksHint True when B is already assigned to its preferred register.
537bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
538 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000539 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000540
541 // Be fairly aggressive about following hints as long as the evictee can be
542 // split.
543 if (CanSplit && IsHint && !BreaksHint)
544 return true;
545
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000546 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000547}
548
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000549/// canEvictInterference - Return true if all interferences between VirtReg and
550/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
551///
552/// @param VirtReg Live range that is about to be assigned.
553/// @param PhysReg Desired register for assignment.
Dmitri Gribenko67c89782012-09-12 16:59:47 +0000554/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000555/// @param MaxCost Only look for cheaper candidates and update with new cost
556/// when returning true.
557/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000558bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000559 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000560 // It is only possible to evict virtual register interference.
561 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
562 return false;
563
Andrew Trick6ea2b962013-07-25 18:35:14 +0000564 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
565
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000566 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
567 // involved in an eviction before. If a cascade number was assigned, deny
568 // evicting anything with the same or a newer cascade number. This prevents
569 // infinite eviction loops.
570 //
571 // This works out so a register without a cascade number is allowed to evict
572 // anything, and it can be evicted by anything.
573 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
574 if (!Cascade)
575 Cascade = NextCascade;
576
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000577 EvictionCost Cost;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000578 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
579 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000580 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000581 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000582 return false;
583
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000584 // Check if any interfering live range is heavier than MaxWeight.
585 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
586 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000587 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
588 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000589 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000590 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000591 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000592 // Once a live range becomes small enough, it is urgent that we find a
593 // register for it. This is indicated by an infinite spill weight. These
594 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000595 //
596 // Also allow urgent evictions of unspillable ranges from a strictly
597 // larger allocation order.
598 bool Urgent = !VirtReg.isSpillable() &&
599 (Intf->isSpillable() ||
600 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
601 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000602 // Only evict older cascades or live ranges without a cascade.
603 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
604 if (Cascade <= IntfCascade) {
605 if (!Urgent)
606 return false;
607 // We permit breaking cascades for urgent evictions. It should be the
608 // last resort, though, so make it really expensive.
609 Cost.BrokenHints += 10;
610 }
611 // Would this break a satisfied hint?
612 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
613 // Update eviction cost.
614 Cost.BrokenHints += BreaksHint;
615 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
616 // Abort if this would be too expensive.
617 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000618 return false;
Andrew Trick6ea2b962013-07-25 18:35:14 +0000619 if (Urgent)
620 continue;
621 // If !MaxCost.isMax(), then we're just looking for a cheap register.
622 // Evicting another local live range in this case could lead to suboptimal
623 // coloring.
Andrew Trick8adae962013-07-25 18:35:19 +0000624 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
625 !canReassign(*Intf, PhysReg)) {
Andrew Trick6ea2b962013-07-25 18:35:14 +0000626 return false;
Andrew Trick8adae962013-07-25 18:35:19 +0000627 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000628 // Finally, apply the eviction policy for non-urgent evictions.
Andrew Trick6ea2b962013-07-25 18:35:14 +0000629 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000630 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000631 }
632 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000633 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000634 return true;
635}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000636
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000637/// evictInterference - Evict any interferring registers that prevent VirtReg
638/// from being assigned to Physreg. This assumes that canEvictInterference
639/// returned true.
640void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
641 SmallVectorImpl<LiveInterval*> &NewVRegs) {
642 // Make sure that VirtReg has a cascade number, and assign that cascade
643 // number to every evicted register. These live ranges than then only be
644 // evicted by a newer cascade, preventing infinite loops.
645 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
646 if (!Cascade)
647 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
648
649 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
650 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000651
652 // Collect all interfering virtregs first.
653 SmallVector<LiveInterval*, 8> Intfs;
654 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
655 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000656 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000657 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
658 Intfs.append(IVR.begin(), IVR.end());
659 }
660
661 // Evict them second. This will invalidate the queries.
662 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
663 LiveInterval *Intf = Intfs[i];
664 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
665 if (!VRM->hasPhys(Intf->reg))
666 continue;
667 Matrix->unassign(*Intf);
668 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
669 VirtReg.isSpillable() < Intf->isSpillable()) &&
670 "Cannot decrease cascade number, illegal eviction");
671 ExtraRegInfo[Intf->reg].Cascade = Cascade;
672 ++NumEvicted;
673 NewVRegs.push_back(Intf);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000674 }
675}
676
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000677/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000678/// @param VirtReg Currently unassigned virtual register.
679/// @param Order Physregs to try.
680/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000681unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
682 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000683 SmallVectorImpl<LiveInterval*> &NewVRegs,
684 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000685 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
686
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000687 // Keep track of the cheapest interference seen so far.
688 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000689 unsigned BestPhys = 0;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000690 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000691
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000692 // When we are just looking for a reduced cost per use, don't break any
693 // hints, and only evict smaller spill weights.
694 if (CostPerUseLimit < ~0u) {
695 BestCost.BrokenHints = 0;
696 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000697
698 // Check of any registers in RC are below CostPerUseLimit.
699 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
700 unsigned MinCost = RegClassInfo.getMinCost(RC);
701 if (MinCost >= CostPerUseLimit) {
702 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
703 << ", no cheaper registers to be found.\n");
704 return 0;
705 }
706
707 // It is normal for register classes to have a long tail of registers with
708 // the same cost. We don't need to look at them if they're too expensive.
709 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
710 OrderLimit = RegClassInfo.getLastCostChange(RC);
711 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
712 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000713 }
714
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000715 Order.rewind();
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000716 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000717 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
718 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000719 // The first use of a callee-saved register in a function has cost 1.
720 // Don't start using a CSR when the CostPerUseLimit is low.
721 if (CostPerUseLimit == 1)
722 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
723 if (!MRI->isPhysRegUsed(CSR)) {
724 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
725 << PrintReg(CSR, TRI) << '\n');
726 continue;
727 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000728
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000729 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000730 continue;
731
732 // Best so far.
733 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000734
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000735 // Stop if the hint can be used.
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000736 if (Order.isHint())
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000737 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000738 }
739
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000740 if (!BestPhys)
741 return 0;
742
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000743 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000744 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000745}
746
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000747
748//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000749// Region Splitting
750//===----------------------------------------------------------------------===//
751
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000752/// addSplitConstraints - Fill out the SplitConstraints vector based on the
753/// interference pattern in Physreg and its aliases. Add the constraints to
754/// SpillPlacement and return the static cost of this split in Cost, assuming
755/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000756/// Return false if there are no bundles with positive bias.
757bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000758 BlockFrequency &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000759 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000760
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000761 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000762 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000763 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000764 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
765 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000766 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000767
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000768 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000769 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000770 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
771 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie453f4f02013-05-15 07:36:59 +0000772 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000773
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000774 if (!Intf.hasInterference())
775 continue;
776
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000777 // Number of spill code instructions to insert.
778 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000779
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000780 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000781 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000782 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000783 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000784 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000785 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000786 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000787 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000788 }
789
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000790 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000791 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000792 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000793 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000794 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000795 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000796 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000797 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000798 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000799
800 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000801 while (Ins--)
802 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000803 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000804 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000805
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000806 // Add constraints for use-blocks. Note that these are the only constraints
807 // that may add a positive bias, it is downhill from here.
808 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000809 return SpillPlacer->scanActiveBundles();
810}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000811
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000812
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000813/// addThroughConstraints - Add constraints and links to SpillPlacer from the
814/// live-through blocks in Blocks.
815void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
816 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000817 const unsigned GroupSize = 8;
818 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000819 unsigned TBS[GroupSize];
820 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000821
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000822 for (unsigned i = 0; i != Blocks.size(); ++i) {
823 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000824 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000825
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000826 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000827 assert(T < GroupSize && "Array overflow");
828 TBS[T] = Number;
829 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000830 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000831 T = 0;
832 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000833 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000834 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000835
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000836 assert(B < GroupSize && "Array overflow");
837 BCS[B].Number = Number;
838
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000839 // Interference for the live-in value.
840 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
841 BCS[B].Entry = SpillPlacement::MustSpill;
842 else
843 BCS[B].Entry = SpillPlacement::PrefSpill;
844
845 // Interference for the live-out value.
846 if (Intf.last() >= SA->getLastSplitPoint(Number))
847 BCS[B].Exit = SpillPlacement::MustSpill;
848 else
849 BCS[B].Exit = SpillPlacement::PrefSpill;
850
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000851 if (++B == GroupSize) {
852 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
853 SpillPlacer->addConstraints(Array);
854 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000855 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000856 }
857
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000858 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
859 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000860 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000861}
862
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000863void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000864 // Keep track of through blocks that have not been added to SpillPlacer.
865 BitVector Todo = SA->getThroughBlocks();
866 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
867 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000868#ifndef NDEBUG
869 unsigned Visited = 0;
870#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000871
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000872 for (;;) {
873 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000874 // Find new through blocks in the periphery of PrefRegBundles.
875 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
876 unsigned Bundle = NewBundles[i];
877 // Look at all blocks connected to Bundle in the full graph.
878 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
879 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
880 I != E; ++I) {
881 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000882 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000883 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000884 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000885 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000886 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000887#ifndef NDEBUG
888 ++Visited;
889#endif
890 }
891 }
892 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000893 if (ActiveBlocks.size() == AddedTo)
894 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000895
896 // Compute through constraints from the interference, or assume that all
897 // through blocks prefer spilling when forming compact regions.
898 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
899 if (Cand.PhysReg)
900 addThroughConstraints(Cand.Intf, NewBlocks);
901 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000902 // Provide a strong negative bias on through blocks to prevent unwanted
903 // liveness on loop backedges.
904 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000905 AddedTo = ActiveBlocks.size();
906
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000907 // Perhaps iterating can enable more bundles?
908 SpillPlacer->iterate();
909 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000910 DEBUG(dbgs() << ", v=" << Visited);
911}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000912
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000913/// calcCompactRegion - Compute the set of edge bundles that should be live
914/// when splitting the current live range into compact regions. Compact
915/// regions can be computed without looking at interference. They are the
916/// regions formed by removing all the live-through blocks from the live range.
917///
918/// Returns false if the current live range is already compact, or if the
919/// compact regions would form single block regions anyway.
920bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
921 // Without any through blocks, the live range is already compact.
922 if (!SA->getNumThroughBlocks())
923 return false;
924
925 // Compact regions don't correspond to any physreg.
926 Cand.reset(IntfCache, 0);
927
928 DEBUG(dbgs() << "Compact region bundles");
929
930 // Use the spill placer to determine the live bundles. GrowRegion pretends
931 // that all the through blocks have interference when PhysReg is unset.
932 SpillPlacer->prepare(Cand.LiveBundles);
933
934 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000935 BlockFrequency Cost;
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000936 if (!addSplitConstraints(Cand.Intf, Cost)) {
937 DEBUG(dbgs() << ", none.\n");
938 return false;
939 }
940
941 growRegion(Cand);
942 SpillPlacer->finish();
943
944 if (!Cand.LiveBundles.any()) {
945 DEBUG(dbgs() << ", none.\n");
946 return false;
947 }
948
949 DEBUG({
950 for (int i = Cand.LiveBundles.find_first(); i>=0;
951 i = Cand.LiveBundles.find_next(i))
952 dbgs() << " EB#" << i;
953 dbgs() << ".\n";
954 });
955 return true;
956}
957
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000958/// calcSpillCost - Compute how expensive it would be to split the live range in
959/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000960BlockFrequency RAGreedy::calcSpillCost() {
961 BlockFrequency Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000962 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
963 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
964 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
965 unsigned Number = BI.MBB->getNumber();
966 // We normally only need one spill instruction - a load or a store.
967 Cost += SpillPlacer->getBlockFrequency(Number);
968
969 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000970 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
971 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000972 }
973 return Cost;
974}
975
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000976/// calcGlobalSplitCost - Return the global split cost of following the split
977/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000978/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000979///
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000980BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
981 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000982 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000983 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
984 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
985 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000986 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000987 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
988 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
989 unsigned Ins = 0;
990
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000991 if (BI.LiveIn)
992 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
993 if (BI.LiveOut)
994 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000995 while (Ins--)
996 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000997 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000998
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000999 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1000 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001001 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1002 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +00001003 if (!RegIn && !RegOut)
1004 continue;
1005 if (RegIn && RegOut) {
1006 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001007 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001008 if (Cand.Intf.hasInterference()) {
1009 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1010 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1011 }
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +00001012 continue;
1013 }
1014 // live-in / stack-out or stack-in live-out.
1015 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001016 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001017 return GlobalCost;
1018}
1019
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001020/// splitAroundRegion - Split the current live range around the regions
1021/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001022///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001023/// Before calling this function, GlobalCand and BundleCand must be initialized
1024/// so each bundle is assigned to a valid candidate, or NoCand for the
1025/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1026/// objects must be initialized for the current live range, and intervals
1027/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001028///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001029/// @param LREdit The LiveRangeEdit object handling the current split.
1030/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1031/// must appear in this list.
1032void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1033 ArrayRef<unsigned> UsedCands) {
1034 // These are the intervals created for new global ranges. We may create more
1035 // intervals for local ranges.
1036 const unsigned NumGlobalIntvs = LREdit.size();
1037 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1038 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001039
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001040 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +00001041 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001042 // is all copies.
1043 unsigned Reg = SA->getParent().reg;
1044 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1045
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001046 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001047 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1048 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1049 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001050 unsigned Number = BI.MBB->getNumber();
1051 unsigned IntvIn = 0, IntvOut = 0;
1052 SlotIndex IntfIn, IntfOut;
1053 if (BI.LiveIn) {
1054 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1055 if (CandIn != NoCand) {
1056 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1057 IntvIn = Cand.IntvIdx;
1058 Cand.Intf.moveToBlock(Number);
1059 IntfIn = Cand.Intf.first();
1060 }
1061 }
1062 if (BI.LiveOut) {
1063 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1064 if (CandOut != NoCand) {
1065 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1066 IntvOut = Cand.IntvIdx;
1067 Cand.Intf.moveToBlock(Number);
1068 IntfOut = Cand.Intf.last();
1069 }
1070 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001071
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001072 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001073 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001074 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001075 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001076 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001077 continue;
1078 }
1079
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001080 if (IntvIn && IntvOut)
1081 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1082 else if (IntvIn)
1083 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001084 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001085 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001086 }
1087
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001088 // Handle live-through blocks. The relevant live-through blocks are stored in
1089 // the ActiveBlocks list with each candidate. We need to filter out
1090 // duplicates.
1091 BitVector Todo = SA->getThroughBlocks();
1092 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1093 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1094 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1095 unsigned Number = Blocks[i];
1096 if (!Todo.test(Number))
1097 continue;
1098 Todo.reset(Number);
1099
1100 unsigned IntvIn = 0, IntvOut = 0;
1101 SlotIndex IntfIn, IntfOut;
1102
1103 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1104 if (CandIn != NoCand) {
1105 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1106 IntvIn = Cand.IntvIdx;
1107 Cand.Intf.moveToBlock(Number);
1108 IntfIn = Cand.Intf.first();
1109 }
1110
1111 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1112 if (CandOut != NoCand) {
1113 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1114 IntvOut = Cand.IntvIdx;
1115 Cand.Intf.moveToBlock(Number);
1116 IntfOut = Cand.Intf.last();
1117 }
1118 if (!IntvIn && !IntvOut)
1119 continue;
1120 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1121 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001122 }
1123
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001124 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001125
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001126 SmallVector<unsigned, 8> IntvMap;
1127 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001128 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001129
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001130 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001131 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001132
1133 // Sort out the new intervals created by splitting. We get four kinds:
1134 // - Remainder intervals should not be split again.
1135 // - Candidate intervals can be assigned to Cand.PhysReg.
1136 // - Block-local splits are candidates for local splitting.
1137 // - DCE leftovers should go back on the queue.
1138 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001139 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001140
1141 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001142 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001143 continue;
1144
1145 // Remainder interval. Don't try splitting again, spill if it doesn't
1146 // allocate.
1147 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001148 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001149 continue;
1150 }
1151
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001152 // Global intervals. Allow repeated splitting as long as the number of live
1153 // blocks is strictly decreasing.
1154 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001155 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001156 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1157 << " blocks as original.\n");
1158 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001159 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001160 }
1161 continue;
1162 }
1163
1164 // Other intervals are treated as new. This includes local intervals created
1165 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001166 }
1167
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001168 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001169 MF->verify(this, "After splitting live range around region");
1170}
1171
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001172unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1173 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001174 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001175 unsigned BestCand = NoCand;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001176 BlockFrequency BestCost;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001177 SmallVector<unsigned, 8> UsedCands;
1178
1179 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001180 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001181 if (HasCompact) {
1182 // Yes, keep GlobalCand[0] as the compact region candidate.
1183 NumCands = 1;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001184 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001185 } else {
1186 // No benefit from the compact region, our fallback will be per-block
1187 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001188 BestCost = calcSpillCost();
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001189 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1190 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001191
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001192 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001193 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001194 // Discard bad candidates before we run out of interference cache cursors.
1195 // This will only affect register classes with a lot of registers (>32).
1196 if (NumCands == IntfCache.getMaxCursors()) {
1197 unsigned WorstCount = ~0u;
1198 unsigned Worst = 0;
1199 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001200 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001201 continue;
1202 unsigned Count = GlobalCand[i].LiveBundles.count();
1203 if (Count < WorstCount)
1204 Worst = i, WorstCount = Count;
1205 }
1206 --NumCands;
1207 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001208 if (BestCand == NumCands)
1209 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001210 }
1211
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001212 if (GlobalCand.size() <= NumCands)
1213 GlobalCand.resize(NumCands+1);
1214 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1215 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001216
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001217 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001218 BlockFrequency Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001219 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001220 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001221 continue;
1222 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001223 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001224 if (Cost >= BestCost) {
1225 DEBUG({
1226 if (BestCand == NoCand)
1227 dbgs() << " worse than no bundles\n";
1228 else
1229 dbgs() << " worse than "
1230 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1231 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001232 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001233 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001234 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001235
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001236 SpillPlacer->finish();
1237
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001238 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001239 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001240 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001241 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001242 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001243
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001244 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001245 DEBUG({
1246 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001247 for (int i = Cand.LiveBundles.find_first(); i>=0;
1248 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001249 dbgs() << " EB#" << i;
1250 dbgs() << ".\n";
1251 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001252 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001253 BestCand = NumCands;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001254 BestCost = Cost;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001255 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001256 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001257 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001258
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001259 // No solutions found, fall back to single block splitting.
1260 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001261 return 0;
1262
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001263 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001264 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001265 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001266
1267 // Assign all edge bundles to the preferred candidate, or NoCand.
1268 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1269
1270 // Assign bundles for the best candidate region.
1271 if (BestCand != NoCand) {
1272 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1273 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1274 UsedCands.push_back(BestCand);
1275 Cand.IntvIdx = SE->openIntv();
1276 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1277 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001278 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001279 }
1280 }
1281
1282 // Assign bundles for the compact region.
1283 if (HasCompact) {
1284 GlobalSplitCandidate &Cand = GlobalCand.front();
1285 assert(!Cand.PhysReg && "Compact region has no physreg");
1286 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1287 UsedCands.push_back(0);
1288 Cand.IntvIdx = SE->openIntv();
1289 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1290 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001291 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001292 }
1293 }
1294
1295 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001296 return 0;
1297}
1298
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001299
1300//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001301// Per-Block Splitting
1302//===----------------------------------------------------------------------===//
1303
1304/// tryBlockSplit - Split a global live range around every block with uses. This
1305/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1306/// they don't allocate.
1307unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1308 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1309 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1310 unsigned Reg = VirtReg.reg;
1311 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001312 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001313 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001314 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1315 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1316 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1317 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1318 SE->splitSingleBlock(BI);
1319 }
1320 // No blocks were split.
1321 if (LREdit.empty())
1322 return 0;
1323
1324 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001325 SmallVector<unsigned, 8> IntvMap;
1326 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001327
1328 // Tell LiveDebugVariables about the new ranges.
1329 DebugVars->splitRegister(Reg, LREdit.regs());
1330
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001331 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1332
1333 // Sort out the new intervals created by splitting. The remainder interval
1334 // goes straight to spilling, the new local ranges get to stay RS_New.
1335 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1336 LiveInterval &LI = *LREdit.get(i);
1337 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1338 setStage(LI, RS_Spill);
1339 }
1340
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001341 if (VerifyEnabled)
1342 MF->verify(this, "After splitting live range around basic blocks");
1343 return 0;
1344}
1345
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001346
1347//===----------------------------------------------------------------------===//
1348// Per-Instruction Splitting
1349//===----------------------------------------------------------------------===//
1350
1351/// tryInstructionSplit - Split a live range around individual instructions.
1352/// This is normally not worthwhile since the spiller is doing essentially the
1353/// same thing. However, when the live range is in a constrained register
1354/// class, it may help to insert copies such that parts of the live range can
1355/// be moved to a larger register class.
1356///
1357/// This is similar to spilling to a larger register class.
1358unsigned
1359RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1360 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1361 // There is no point to this if there are no larger sub-classes.
1362 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1363 return 0;
1364
1365 // Always enable split spill mode, since we're effectively spilling to a
1366 // register.
1367 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1368 SE->reset(LREdit, SplitEditor::SM_Size);
1369
1370 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1371 if (Uses.size() <= 1)
1372 return 0;
1373
1374 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1375
1376 // Split around every non-copy instruction.
1377 for (unsigned i = 0; i != Uses.size(); ++i) {
1378 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1379 if (MI->isFullCopy()) {
1380 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1381 continue;
1382 }
1383 SE->openIntv();
1384 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1385 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1386 SE->useIntv(SegStart, SegStop);
1387 }
1388
1389 if (LREdit.empty()) {
1390 DEBUG(dbgs() << "All uses were copies.\n");
1391 return 0;
1392 }
1393
1394 SmallVector<unsigned, 8> IntvMap;
1395 SE->finish(&IntvMap);
1396 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1397 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1398
1399 // Assign all new registers to RS_Spill. This was the last chance.
1400 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1401 return 0;
1402}
1403
1404
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001405//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001406// Local Splitting
1407//===----------------------------------------------------------------------===//
1408
1409
1410/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1411/// in order to use PhysReg between two entries in SA->UseSlots.
1412///
1413/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1414///
1415void RAGreedy::calcGapWeights(unsigned PhysReg,
1416 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001417 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1418 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001419 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001420 const unsigned NumGaps = Uses.size()-1;
1421
1422 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001423 SlotIndex StartIdx =
1424 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1425 SlotIndex StopIdx =
1426 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001427
1428 GapWeight.assign(NumGaps, 0.0f);
1429
1430 // Add interference from each overlapping register.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001431 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1432 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1433 .checkInterference())
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001434 continue;
1435
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001436 // We know that VirtReg is a continuous interval from FirstInstr to
1437 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001438 //
1439 // Interference that overlaps an instruction is counted in both gaps
1440 // surrounding the instruction. The exception is interference before
1441 // StartIdx and after StopIdx.
1442 //
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001443 LiveIntervalUnion::SegmentIter IntI =
1444 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001445 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1446 // Skip the gaps before IntI.
1447 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1448 if (++Gap == NumGaps)
1449 break;
1450 if (Gap == NumGaps)
1451 break;
1452
1453 // Update the gaps covered by IntI.
1454 const float weight = IntI.value()->weight;
1455 for (; Gap != NumGaps; ++Gap) {
1456 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1457 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1458 break;
1459 }
1460 if (Gap == NumGaps)
1461 break;
1462 }
1463 }
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001464
1465 // Add fixed interference.
1466 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1467 const LiveInterval &LI = LIS->getRegUnit(*Units);
1468 LiveInterval::const_iterator I = LI.find(StartIdx);
1469 LiveInterval::const_iterator E = LI.end();
1470
1471 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1472 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1473 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1474 if (++Gap == NumGaps)
1475 break;
1476 if (Gap == NumGaps)
1477 break;
1478
1479 for (; Gap != NumGaps; ++Gap) {
1480 GapWeight[Gap] = HUGE_VALF;
1481 if (Uses[Gap+1].getBaseIndex() >= I->end)
1482 break;
1483 }
1484 if (Gap == NumGaps)
1485 break;
1486 }
1487 }
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001488}
1489
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001490/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1491/// basic block.
1492///
1493unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1494 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001495 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1496 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001497
1498 // Note that it is possible to have an interval that is live-in or live-out
1499 // while only covering a single block - A phi-def can use undef values from
1500 // predecessors, and the block could be a single-block loop.
1501 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001502 // that the interval is continuous from FirstInstr to LastInstr. We should
1503 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001504
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001505 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001506 if (Uses.size() <= 2)
1507 return 0;
1508 const unsigned NumGaps = Uses.size()-1;
1509
1510 DEBUG({
1511 dbgs() << "tryLocalSplit: ";
1512 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001513 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001514 dbgs() << '\n';
1515 });
1516
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001517 // If VirtReg is live across any register mask operands, compute a list of
1518 // gaps with register masks.
1519 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001520 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001521 // Get regmask slots for the whole block.
1522 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001523 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001524 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001525 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1526 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001527 unsigned re = RMS.size();
1528 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001529 // Look for Uses[i] <= RMS <= Uses[i+1].
1530 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1531 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001532 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001533 // Skip a regmask on the same instruction as the last use. It doesn't
1534 // overlap the live range.
1535 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1536 break;
1537 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001538 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001539 // Advance ri to the next gap. A regmask on one of the uses counts in
1540 // both gaps.
1541 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1542 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001543 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001544 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001545 }
1546
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001547 // Since we allow local split results to be split again, there is a risk of
1548 // creating infinite loops. It is tempting to require that the new live
1549 // ranges have less instructions than the original. That would guarantee
1550 // convergence, but it is too strict. A live range with 3 instructions can be
1551 // split 2+3 (including the COPY), and we want to allow that.
1552 //
1553 // Instead we use these rules:
1554 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001555 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001556 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001557 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001558 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001559 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001560 // smaller ranges are marked RS_New.
1561 //
1562 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1563 // excessive splitting and infinite loops.
1564 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001565 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001566
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001567 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001568 unsigned BestBefore = NumGaps;
1569 unsigned BestAfter = 0;
1570 float BestDiff = 0;
1571
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001572 const float blockFreq =
1573 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1574 (1.0f / BlockFrequency::getEntryFrequency());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001575 SmallVector<float, 8> GapWeight;
1576
1577 Order.rewind();
1578 while (unsigned PhysReg = Order.next()) {
1579 // Keep track of the largest spill weight that would need to be evicted in
1580 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1581 calcGapWeights(PhysReg, GapWeight);
1582
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001583 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001584 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001585 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1586 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1587
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001588 // Try to find the best sequence of gaps to close.
1589 // The new spill weight must be larger than any gap interference.
1590
1591 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001592 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001593
1594 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1595 // It is the spill weight that needs to be evicted.
1596 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001597
1598 for (;;) {
1599 // Live before/after split?
1600 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1601 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1602
1603 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1604 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1605 << " i=" << MaxGap);
1606
1607 // Stop before the interval gets so big we wouldn't be making progress.
1608 if (!LiveBefore && !LiveAfter) {
1609 DEBUG(dbgs() << " all\n");
1610 break;
1611 }
1612 // Should the interval be extended or shrunk?
1613 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001614
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001615 // How many gaps would the new range have?
1616 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1617
1618 // Legally, without causing looping?
1619 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1620
1621 if (Legal && MaxGap < HUGE_VALF) {
1622 // Estimate the new spill weight. Each instruction reads or writes the
1623 // register. Conservatively assume there are no read-modify-write
1624 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001625 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001626 // Try to guess the size of the new interval.
1627 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1628 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1629 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001630 // Would this split be possible to allocate?
1631 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001632 DEBUG(dbgs() << " w=" << EstWeight);
1633 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001634 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001635 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001636 if (Diff > BestDiff) {
1637 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001638 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001639 BestBefore = SplitBefore;
1640 BestAfter = SplitAfter;
1641 }
1642 }
1643 }
1644
1645 // Try to shrink.
1646 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001647 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001648 DEBUG(dbgs() << " shrink\n");
1649 // Recompute the max when necessary.
1650 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1651 MaxGap = GapWeight[SplitBefore];
1652 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1653 MaxGap = std::max(MaxGap, GapWeight[i]);
1654 }
1655 continue;
1656 }
1657 MaxGap = 0;
1658 }
1659
1660 // Try to extend the interval.
1661 if (SplitAfter >= NumGaps) {
1662 DEBUG(dbgs() << " end\n");
1663 break;
1664 }
1665
1666 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001667 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001668 }
1669 }
1670
1671 // Didn't find any candidates?
1672 if (BestBefore == NumGaps)
1673 return 0;
1674
1675 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1676 << '-' << Uses[BestAfter] << ", " << BestDiff
1677 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1678
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001679 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001680 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001681
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001682 SE->openIntv();
1683 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1684 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1685 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001686 SmallVector<unsigned, 8> IntvMap;
1687 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001688 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001689
1690 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001691 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001692 // leave the new intervals as RS_New so they can compete.
1693 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1694 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1695 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1696 if (NewGaps >= NumGaps) {
1697 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1698 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001699 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1700 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001701 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001702 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1703 }
1704 DEBUG(dbgs() << '\n');
1705 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001706 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001707
1708 return 0;
1709}
1710
1711//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001712// Live Range Splitting
1713//===----------------------------------------------------------------------===//
1714
1715/// trySplit - Try to split VirtReg or one of its interferences, making it
1716/// assignable.
1717/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1718unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1719 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001720 // Ranges must be Split2 or less.
1721 if (getStage(VirtReg) >= RS_Spill)
1722 return 0;
1723
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001724 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001725 if (LIS->intervalIsInOneMBB(VirtReg)) {
1726 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001727 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001728 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1729 if (PhysReg || !NewVRegs.empty())
1730 return PhysReg;
1731 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001732 }
1733
1734 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001735
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001736 SA->analyze(&VirtReg);
1737
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001738 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1739 // coalescer. That may cause the range to become allocatable which means that
1740 // tryRegionSplit won't be making progress. This check should be replaced with
1741 // an assertion when the coalescer is fixed.
1742 if (SA->didRepairRange()) {
1743 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001744 Matrix->invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001745 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1746 return PhysReg;
1747 }
1748
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001749 // First try to split around a region spanning multiple blocks. RS_Split2
1750 // ranges already made dubious progress with region splitting, so they go
1751 // straight to single block splitting.
1752 if (getStage(VirtReg) < RS_Split2) {
1753 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1754 if (PhysReg || !NewVRegs.empty())
1755 return PhysReg;
1756 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001757
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001758 // Then isolate blocks.
1759 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001760}
1761
1762
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001763//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001764// Main Entry Point
1765//===----------------------------------------------------------------------===//
1766
1767unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001768 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001769 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001770 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001771 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1772 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001773
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001774 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001775 DEBUG(dbgs() << StageName[Stage]
1776 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001777
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001778 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001779 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001780 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001781 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001782 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1783 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001784
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001785 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1786
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001787 // The first time we see a live range, don't try to split or spill.
1788 // Wait until the second time, when all smaller ranges have been allocated.
1789 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001790 if (Stage < RS_Split) {
1791 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001792 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001793 NewVRegs.push_back(&VirtReg);
1794 return 0;
1795 }
1796
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001797 // If we couldn't allocate a register from spilling, there is probably some
1798 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001799 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001800 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001801
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001802 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001803 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1804 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001805 return PhysReg;
1806
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001807 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001808 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001809 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001810 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001811 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001812
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001813 if (VerifyEnabled)
1814 MF->verify(this, "After spilling");
1815
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001816 // The live virtual register requesting allocation was spilled, so tell
1817 // the caller not to allocate anything during this round.
1818 return 0;
1819}
1820
1821bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1822 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikie986d76d2012-08-22 17:18:53 +00001823 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001824
1825 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001826 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001827 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001828
Jakob Stoklund Olesend4348a22012-06-20 22:52:29 +00001829 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1830 getAnalysis<LiveIntervals>(),
1831 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001832 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramer4eed7562013-06-17 19:00:36 +00001833 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001834 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001835 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001836 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001837 Bundles = &getAnalysis<EdgeBundles>();
1838 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001839 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001840
Andrew Trick5dca6132013-07-25 07:26:26 +00001841 DEBUG(LIS->dump());
1842
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001843 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramer4eed7562013-06-17 19:00:36 +00001844 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001845 ExtraRegInfo.clear();
1846 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1847 NextCascade = 1;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001848 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001849 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001850
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001851 allocatePhysRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001852 releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001853 return true;
1854}