blob: 55f2fc68a752c42561d7633cf2c15e84b2a21158 [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>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000264 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
265 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
266 void evictInterference(LiveInterval&, unsigned,
267 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000268
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000269 unsigned tryAssign(LiveInterval&, AllocationOrder&,
270 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000271 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000272 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000273 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
274 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000275 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +0000277 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
278 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000279 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
280 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000281 unsigned trySplit(LiveInterval&, AllocationOrder&,
282 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000283};
284} // end anonymous namespace
285
286char RAGreedy::ID = 0;
287
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000288#ifndef NDEBUG
289const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000290 "RS_New",
291 "RS_Assign",
292 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000293 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000294 "RS_Spill",
295 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000296};
297#endif
298
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000299// Hysteresis to use when comparing floats.
300// This helps stabilize decisions based on float comparisons.
301const float Hysteresis = 0.98f;
302
303
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000304FunctionPass* llvm::createGreedyRegisterAllocator() {
305 return new RAGreedy();
306}
307
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000308RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000309 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000310 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000311 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
312 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000313 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000314 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000315 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
316 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
317 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
318 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
319 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000320 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000321 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
322 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000323}
324
325void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
326 AU.setPreservesCFG();
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000327 AU.addRequired<MachineBlockFrequencyInfo>();
328 AU.addPreserved<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000329 AU.addRequired<AliasAnalysis>();
330 AU.addPreserved<AliasAnalysis>();
331 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000332 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000333 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000334 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000335 AU.addRequired<LiveDebugVariables>();
336 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000337 AU.addRequired<LiveStacks>();
338 AU.addPreserved<LiveStacks>();
Evan Chengbb36a432012-09-21 20:04:28 +0000339 AU.addRequired<CalculateSpillWeights>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000340 AU.addRequired<MachineDominatorTree>();
341 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000342 AU.addRequired<MachineLoopInfo>();
343 AU.addPreserved<MachineLoopInfo>();
344 AU.addRequired<VirtRegMap>();
345 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000346 AU.addRequired<LiveRegMatrix>();
347 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000348 AU.addRequired<EdgeBundles>();
349 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000350 MachineFunctionPass::getAnalysisUsage(AU);
351}
352
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000353
354//===----------------------------------------------------------------------===//
355// LiveRangeEdit delegate methods
356//===----------------------------------------------------------------------===//
357
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000358bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000359 if (VRM->hasPhys(VirtReg)) {
360 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000361 return true;
362 }
363 // Unassigned virtreg is probably in the priority queue.
364 // RegAllocBase will erase it after dequeueing.
365 return false;
366}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000367
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000368void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000369 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000370 return;
371
372 // Register is assigned, put it back on the queue for reassignment.
373 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000374 Matrix->unassign(LI);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000375 enqueue(&LI);
376}
377
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000378void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000379 // Cloning a register we haven't even heard about yet? Just ignore it.
380 if (!ExtraRegInfo.inBounds(Old))
381 return;
382
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000383 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000384 // be split into connected components. The new components are much smaller
385 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000386 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000387 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000388 ExtraRegInfo.grow(New);
389 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000390}
391
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000392void RAGreedy::releaseMemory() {
393 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000394 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000395 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000396}
397
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000398void RAGreedy::enqueue(LiveInterval *LI) {
399 // Prioritize live ranges by size, assigning larger ranges first.
400 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000401 const unsigned Size = LI->getSize();
402 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000403 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
404 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000405 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000406
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000407 ExtraRegInfo.grow(Reg);
408 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000409 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000410
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000411 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000412 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000413 // everything else has been allocated.
414 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000415 } else {
Andrew Trick6ea2b962013-07-25 18:35:14 +0000416 if (ExtraRegInfo[Reg].Stage == RS_Assign && !LI->empty() &&
417 LIS->intervalIsInOneMBB(*LI)) {
418 // Allocate original local ranges in linear instruction order. Since they
419 // are singly defined, this produces optimal coloring in the absence of
420 // global interference and other constraints.
421 Prio = LI->beginIndex().distance(Indexes->getLastIndex());
422 }
423 else {
424 // Allocate global and split ranges in long->short order. Long ranges that
425 // don't fit should be spilled (or split) ASAP so they don't create
426 // interference. Mark a bit to prioritize global above local ranges.
427 Prio = (1u << 29) + Size;
428 }
429 // Mark a higher bit to prioritize global and local above RS_Split.
430 Prio |= (1u << 31);
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000431
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000432 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesenfc637442012-12-03 23:23:50 +0000433 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000434 Prio |= (1u << 30);
435 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000436
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000437 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000438}
439
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000440LiveInterval *RAGreedy::dequeue() {
441 if (Queue.empty())
442 return 0;
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000443 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000444 Queue.pop();
445 return LI;
446}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000447
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000448
449//===----------------------------------------------------------------------===//
450// Direct Assignment
451//===----------------------------------------------------------------------===//
452
453/// tryAssign - Try to assign VirtReg to an available register.
454unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
455 AllocationOrder &Order,
456 SmallVectorImpl<LiveInterval*> &NewVRegs) {
457 Order.rewind();
458 unsigned PhysReg;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000459 while ((PhysReg = Order.next()))
460 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000461 break;
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000462 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000463 return PhysReg;
464
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000465 // PhysReg is available, but there may be a better choice.
466
467 // If we missed a simple hint, try to cheaply evict interference from the
468 // preferred register.
469 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000470 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000471 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
472 EvictionCost MaxCost(1);
473 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
474 evictInterference(VirtReg, Hint, NewVRegs);
475 return Hint;
476 }
477 }
478
479 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000480 unsigned Cost = TRI->getCostPerUse(PhysReg);
481
482 // Most registers have 0 additional cost.
483 if (!Cost)
484 return PhysReg;
485
486 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
487 << '\n');
488 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
489 return CheapReg ? CheapReg : PhysReg;
490}
491
492
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000493//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000494// Interference eviction
495//===----------------------------------------------------------------------===//
496
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000497/// shouldEvict - determine if A should evict the assigned live range B. The
498/// eviction policy defined by this function together with the allocation order
499/// defined by enqueue() decides which registers ultimately end up being split
500/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000501///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000502/// Cascade numbers are used to prevent infinite loops if this function is a
503/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000504///
505/// @param A The live range to be assigned.
506/// @param IsHint True when A is about to be assigned to its preferred
507/// register.
508/// @param B The live range to be evicted.
509/// @param BreaksHint True when B is already assigned to its preferred register.
510bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
511 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000512 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000513
514 // Be fairly aggressive about following hints as long as the evictee can be
515 // split.
516 if (CanSplit && IsHint && !BreaksHint)
517 return true;
518
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000519 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000520}
521
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000522/// canEvictInterference - Return true if all interferences between VirtReg and
523/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
524///
525/// @param VirtReg Live range that is about to be assigned.
526/// @param PhysReg Desired register for assignment.
Dmitri Gribenko67c89782012-09-12 16:59:47 +0000527/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000528/// @param MaxCost Only look for cheaper candidates and update with new cost
529/// when returning true.
530/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000531bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000532 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000533 // It is only possible to evict virtual register interference.
534 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
535 return false;
536
Andrew Trick6ea2b962013-07-25 18:35:14 +0000537 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
538
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000539 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
540 // involved in an eviction before. If a cascade number was assigned, deny
541 // evicting anything with the same or a newer cascade number. This prevents
542 // infinite eviction loops.
543 //
544 // This works out so a register without a cascade number is allowed to evict
545 // anything, and it can be evicted by anything.
546 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
547 if (!Cascade)
548 Cascade = NextCascade;
549
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000550 EvictionCost Cost;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000551 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
552 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000553 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000554 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000555 return false;
556
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000557 // Check if any interfering live range is heavier than MaxWeight.
558 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
559 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000560 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
561 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000562 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000563 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000564 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000565 // Once a live range becomes small enough, it is urgent that we find a
566 // register for it. This is indicated by an infinite spill weight. These
567 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000568 //
569 // Also allow urgent evictions of unspillable ranges from a strictly
570 // larger allocation order.
571 bool Urgent = !VirtReg.isSpillable() &&
572 (Intf->isSpillable() ||
573 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
574 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000575 // Only evict older cascades or live ranges without a cascade.
576 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
577 if (Cascade <= IntfCascade) {
578 if (!Urgent)
579 return false;
580 // We permit breaking cascades for urgent evictions. It should be the
581 // last resort, though, so make it really expensive.
582 Cost.BrokenHints += 10;
583 }
584 // Would this break a satisfied hint?
585 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
586 // Update eviction cost.
587 Cost.BrokenHints += BreaksHint;
588 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
589 // Abort if this would be too expensive.
590 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000591 return false;
Andrew Trick6ea2b962013-07-25 18:35:14 +0000592 if (Urgent)
593 continue;
594 // If !MaxCost.isMax(), then we're just looking for a cheap register.
595 // Evicting another local live range in this case could lead to suboptimal
596 // coloring.
597 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf))
598 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000599 // Finally, apply the eviction policy for non-urgent evictions.
Andrew Trick6ea2b962013-07-25 18:35:14 +0000600 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000601 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000602 }
603 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000604 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000605 return true;
606}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000607
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000608/// evictInterference - Evict any interferring registers that prevent VirtReg
609/// from being assigned to Physreg. This assumes that canEvictInterference
610/// returned true.
611void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
612 SmallVectorImpl<LiveInterval*> &NewVRegs) {
613 // Make sure that VirtReg has a cascade number, and assign that cascade
614 // number to every evicted register. These live ranges than then only be
615 // evicted by a newer cascade, preventing infinite loops.
616 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
617 if (!Cascade)
618 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
619
620 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
621 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000622
623 // Collect all interfering virtregs first.
624 SmallVector<LiveInterval*, 8> Intfs;
625 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
626 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000627 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000628 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
629 Intfs.append(IVR.begin(), IVR.end());
630 }
631
632 // Evict them second. This will invalidate the queries.
633 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
634 LiveInterval *Intf = Intfs[i];
635 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
636 if (!VRM->hasPhys(Intf->reg))
637 continue;
638 Matrix->unassign(*Intf);
639 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
640 VirtReg.isSpillable() < Intf->isSpillable()) &&
641 "Cannot decrease cascade number, illegal eviction");
642 ExtraRegInfo[Intf->reg].Cascade = Cascade;
643 ++NumEvicted;
644 NewVRegs.push_back(Intf);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000645 }
646}
647
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000648/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000649/// @param VirtReg Currently unassigned virtual register.
650/// @param Order Physregs to try.
651/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000652unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
653 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000654 SmallVectorImpl<LiveInterval*> &NewVRegs,
655 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000656 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
657
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000658 // Keep track of the cheapest interference seen so far.
659 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000660 unsigned BestPhys = 0;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000661 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000662
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000663 // When we are just looking for a reduced cost per use, don't break any
664 // hints, and only evict smaller spill weights.
665 if (CostPerUseLimit < ~0u) {
666 BestCost.BrokenHints = 0;
667 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000668
669 // Check of any registers in RC are below CostPerUseLimit.
670 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
671 unsigned MinCost = RegClassInfo.getMinCost(RC);
672 if (MinCost >= CostPerUseLimit) {
673 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
674 << ", no cheaper registers to be found.\n");
675 return 0;
676 }
677
678 // It is normal for register classes to have a long tail of registers with
679 // the same cost. We don't need to look at them if they're too expensive.
680 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
681 OrderLimit = RegClassInfo.getLastCostChange(RC);
682 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
683 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000684 }
685
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000686 Order.rewind();
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000687 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000688 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
689 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000690 // The first use of a callee-saved register in a function has cost 1.
691 // Don't start using a CSR when the CostPerUseLimit is low.
692 if (CostPerUseLimit == 1)
693 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
694 if (!MRI->isPhysRegUsed(CSR)) {
695 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
696 << PrintReg(CSR, TRI) << '\n');
697 continue;
698 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000699
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000700 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000701 continue;
702
703 // Best so far.
704 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000705
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000706 // Stop if the hint can be used.
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000707 if (Order.isHint())
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000708 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000709 }
710
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000711 if (!BestPhys)
712 return 0;
713
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000714 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000715 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000716}
717
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000718
719//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000720// Region Splitting
721//===----------------------------------------------------------------------===//
722
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000723/// addSplitConstraints - Fill out the SplitConstraints vector based on the
724/// interference pattern in Physreg and its aliases. Add the constraints to
725/// SpillPlacement and return the static cost of this split in Cost, assuming
726/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000727/// Return false if there are no bundles with positive bias.
728bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000729 BlockFrequency &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000730 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000731
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000732 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000733 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000734 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000735 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
736 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000737 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000738
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000739 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000740 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000741 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
742 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie453f4f02013-05-15 07:36:59 +0000743 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000744
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000745 if (!Intf.hasInterference())
746 continue;
747
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000748 // Number of spill code instructions to insert.
749 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000750
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000751 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000752 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000753 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000754 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000755 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000756 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000757 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000758 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000759 }
760
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000761 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000762 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000763 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000764 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000765 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000766 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000767 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000768 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000769 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000770
771 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000772 while (Ins--)
773 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000774 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000775 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000776
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000777 // Add constraints for use-blocks. Note that these are the only constraints
778 // that may add a positive bias, it is downhill from here.
779 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000780 return SpillPlacer->scanActiveBundles();
781}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000782
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000783
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000784/// addThroughConstraints - Add constraints and links to SpillPlacer from the
785/// live-through blocks in Blocks.
786void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
787 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000788 const unsigned GroupSize = 8;
789 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000790 unsigned TBS[GroupSize];
791 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000792
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000793 for (unsigned i = 0; i != Blocks.size(); ++i) {
794 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000795 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000796
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000797 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000798 assert(T < GroupSize && "Array overflow");
799 TBS[T] = Number;
800 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000801 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000802 T = 0;
803 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000804 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000805 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000806
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000807 assert(B < GroupSize && "Array overflow");
808 BCS[B].Number = Number;
809
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000810 // Interference for the live-in value.
811 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
812 BCS[B].Entry = SpillPlacement::MustSpill;
813 else
814 BCS[B].Entry = SpillPlacement::PrefSpill;
815
816 // Interference for the live-out value.
817 if (Intf.last() >= SA->getLastSplitPoint(Number))
818 BCS[B].Exit = SpillPlacement::MustSpill;
819 else
820 BCS[B].Exit = SpillPlacement::PrefSpill;
821
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000822 if (++B == GroupSize) {
823 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
824 SpillPlacer->addConstraints(Array);
825 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000826 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000827 }
828
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000829 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
830 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000831 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000832}
833
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000834void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000835 // Keep track of through blocks that have not been added to SpillPlacer.
836 BitVector Todo = SA->getThroughBlocks();
837 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
838 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000839#ifndef NDEBUG
840 unsigned Visited = 0;
841#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000842
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000843 for (;;) {
844 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000845 // Find new through blocks in the periphery of PrefRegBundles.
846 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
847 unsigned Bundle = NewBundles[i];
848 // Look at all blocks connected to Bundle in the full graph.
849 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
850 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
851 I != E; ++I) {
852 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000853 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000854 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000855 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000856 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000857 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000858#ifndef NDEBUG
859 ++Visited;
860#endif
861 }
862 }
863 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000864 if (ActiveBlocks.size() == AddedTo)
865 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000866
867 // Compute through constraints from the interference, or assume that all
868 // through blocks prefer spilling when forming compact regions.
869 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
870 if (Cand.PhysReg)
871 addThroughConstraints(Cand.Intf, NewBlocks);
872 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000873 // Provide a strong negative bias on through blocks to prevent unwanted
874 // liveness on loop backedges.
875 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000876 AddedTo = ActiveBlocks.size();
877
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000878 // Perhaps iterating can enable more bundles?
879 SpillPlacer->iterate();
880 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000881 DEBUG(dbgs() << ", v=" << Visited);
882}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000883
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000884/// calcCompactRegion - Compute the set of edge bundles that should be live
885/// when splitting the current live range into compact regions. Compact
886/// regions can be computed without looking at interference. They are the
887/// regions formed by removing all the live-through blocks from the live range.
888///
889/// Returns false if the current live range is already compact, or if the
890/// compact regions would form single block regions anyway.
891bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
892 // Without any through blocks, the live range is already compact.
893 if (!SA->getNumThroughBlocks())
894 return false;
895
896 // Compact regions don't correspond to any physreg.
897 Cand.reset(IntfCache, 0);
898
899 DEBUG(dbgs() << "Compact region bundles");
900
901 // Use the spill placer to determine the live bundles. GrowRegion pretends
902 // that all the through blocks have interference when PhysReg is unset.
903 SpillPlacer->prepare(Cand.LiveBundles);
904
905 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000906 BlockFrequency Cost;
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000907 if (!addSplitConstraints(Cand.Intf, Cost)) {
908 DEBUG(dbgs() << ", none.\n");
909 return false;
910 }
911
912 growRegion(Cand);
913 SpillPlacer->finish();
914
915 if (!Cand.LiveBundles.any()) {
916 DEBUG(dbgs() << ", none.\n");
917 return false;
918 }
919
920 DEBUG({
921 for (int i = Cand.LiveBundles.find_first(); i>=0;
922 i = Cand.LiveBundles.find_next(i))
923 dbgs() << " EB#" << i;
924 dbgs() << ".\n";
925 });
926 return true;
927}
928
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000929/// calcSpillCost - Compute how expensive it would be to split the live range in
930/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000931BlockFrequency RAGreedy::calcSpillCost() {
932 BlockFrequency Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000933 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
934 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
935 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
936 unsigned Number = BI.MBB->getNumber();
937 // We normally only need one spill instruction - a load or a store.
938 Cost += SpillPlacer->getBlockFrequency(Number);
939
940 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000941 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
942 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000943 }
944 return Cost;
945}
946
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000947/// calcGlobalSplitCost - Return the global split cost of following the split
948/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000949/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000950///
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000951BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
952 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000953 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000954 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
955 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
956 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000957 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000958 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
959 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
960 unsigned Ins = 0;
961
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000962 if (BI.LiveIn)
963 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
964 if (BI.LiveOut)
965 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000966 while (Ins--)
967 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000968 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000969
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000970 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
971 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000972 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
973 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000974 if (!RegIn && !RegOut)
975 continue;
976 if (RegIn && RegOut) {
977 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000978 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000979 if (Cand.Intf.hasInterference()) {
980 GlobalCost += SpillPlacer->getBlockFrequency(Number);
981 GlobalCost += SpillPlacer->getBlockFrequency(Number);
982 }
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000983 continue;
984 }
985 // live-in / stack-out or stack-in live-out.
986 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000987 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000988 return GlobalCost;
989}
990
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000991/// splitAroundRegion - Split the current live range around the regions
992/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000993///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000994/// Before calling this function, GlobalCand and BundleCand must be initialized
995/// so each bundle is assigned to a valid candidate, or NoCand for the
996/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
997/// objects must be initialized for the current live range, and intervals
998/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000999///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001000/// @param LREdit The LiveRangeEdit object handling the current split.
1001/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1002/// must appear in this list.
1003void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1004 ArrayRef<unsigned> UsedCands) {
1005 // These are the intervals created for new global ranges. We may create more
1006 // intervals for local ranges.
1007 const unsigned NumGlobalIntvs = LREdit.size();
1008 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1009 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001010
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001011 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +00001012 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001013 // is all copies.
1014 unsigned Reg = SA->getParent().reg;
1015 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1016
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001017 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001018 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1019 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1020 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001021 unsigned Number = BI.MBB->getNumber();
1022 unsigned IntvIn = 0, IntvOut = 0;
1023 SlotIndex IntfIn, IntfOut;
1024 if (BI.LiveIn) {
1025 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1026 if (CandIn != NoCand) {
1027 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1028 IntvIn = Cand.IntvIdx;
1029 Cand.Intf.moveToBlock(Number);
1030 IntfIn = Cand.Intf.first();
1031 }
1032 }
1033 if (BI.LiveOut) {
1034 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1035 if (CandOut != NoCand) {
1036 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1037 IntvOut = Cand.IntvIdx;
1038 Cand.Intf.moveToBlock(Number);
1039 IntfOut = Cand.Intf.last();
1040 }
1041 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001042
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001043 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001044 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001045 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001046 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001047 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001048 continue;
1049 }
1050
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001051 if (IntvIn && IntvOut)
1052 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1053 else if (IntvIn)
1054 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001055 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001056 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001057 }
1058
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001059 // Handle live-through blocks. The relevant live-through blocks are stored in
1060 // the ActiveBlocks list with each candidate. We need to filter out
1061 // duplicates.
1062 BitVector Todo = SA->getThroughBlocks();
1063 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1064 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1065 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1066 unsigned Number = Blocks[i];
1067 if (!Todo.test(Number))
1068 continue;
1069 Todo.reset(Number);
1070
1071 unsigned IntvIn = 0, IntvOut = 0;
1072 SlotIndex IntfIn, IntfOut;
1073
1074 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1075 if (CandIn != NoCand) {
1076 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1077 IntvIn = Cand.IntvIdx;
1078 Cand.Intf.moveToBlock(Number);
1079 IntfIn = Cand.Intf.first();
1080 }
1081
1082 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1083 if (CandOut != NoCand) {
1084 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1085 IntvOut = Cand.IntvIdx;
1086 Cand.Intf.moveToBlock(Number);
1087 IntfOut = Cand.Intf.last();
1088 }
1089 if (!IntvIn && !IntvOut)
1090 continue;
1091 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1092 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001093 }
1094
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001095 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001096
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001097 SmallVector<unsigned, 8> IntvMap;
1098 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001099 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001100
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001101 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001102 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001103
1104 // Sort out the new intervals created by splitting. We get four kinds:
1105 // - Remainder intervals should not be split again.
1106 // - Candidate intervals can be assigned to Cand.PhysReg.
1107 // - Block-local splits are candidates for local splitting.
1108 // - DCE leftovers should go back on the queue.
1109 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001110 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001111
1112 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001113 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001114 continue;
1115
1116 // Remainder interval. Don't try splitting again, spill if it doesn't
1117 // allocate.
1118 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001119 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001120 continue;
1121 }
1122
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001123 // Global intervals. Allow repeated splitting as long as the number of live
1124 // blocks is strictly decreasing.
1125 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001126 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001127 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1128 << " blocks as original.\n");
1129 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001130 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001131 }
1132 continue;
1133 }
1134
1135 // Other intervals are treated as new. This includes local intervals created
1136 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001137 }
1138
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001139 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001140 MF->verify(this, "After splitting live range around region");
1141}
1142
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001143unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1144 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001145 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001146 unsigned BestCand = NoCand;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001147 BlockFrequency BestCost;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001148 SmallVector<unsigned, 8> UsedCands;
1149
1150 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001151 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001152 if (HasCompact) {
1153 // Yes, keep GlobalCand[0] as the compact region candidate.
1154 NumCands = 1;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001155 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001156 } else {
1157 // No benefit from the compact region, our fallback will be per-block
1158 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001159 BestCost = calcSpillCost();
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001160 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1161 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001162
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001163 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001164 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001165 // Discard bad candidates before we run out of interference cache cursors.
1166 // This will only affect register classes with a lot of registers (>32).
1167 if (NumCands == IntfCache.getMaxCursors()) {
1168 unsigned WorstCount = ~0u;
1169 unsigned Worst = 0;
1170 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001171 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001172 continue;
1173 unsigned Count = GlobalCand[i].LiveBundles.count();
1174 if (Count < WorstCount)
1175 Worst = i, WorstCount = Count;
1176 }
1177 --NumCands;
1178 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001179 if (BestCand == NumCands)
1180 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001181 }
1182
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001183 if (GlobalCand.size() <= NumCands)
1184 GlobalCand.resize(NumCands+1);
1185 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1186 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001187
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001188 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001189 BlockFrequency Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001190 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001191 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001192 continue;
1193 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001194 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001195 if (Cost >= BestCost) {
1196 DEBUG({
1197 if (BestCand == NoCand)
1198 dbgs() << " worse than no bundles\n";
1199 else
1200 dbgs() << " worse than "
1201 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1202 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001203 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001204 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001205 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001206
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001207 SpillPlacer->finish();
1208
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001209 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001210 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001211 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001212 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001213 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001214
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001215 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001216 DEBUG({
1217 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001218 for (int i = Cand.LiveBundles.find_first(); i>=0;
1219 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001220 dbgs() << " EB#" << i;
1221 dbgs() << ".\n";
1222 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001223 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001224 BestCand = NumCands;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001225 BestCost = Cost;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001226 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001227 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001228 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001229
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001230 // No solutions found, fall back to single block splitting.
1231 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001232 return 0;
1233
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001234 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001235 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001236 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001237
1238 // Assign all edge bundles to the preferred candidate, or NoCand.
1239 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1240
1241 // Assign bundles for the best candidate region.
1242 if (BestCand != NoCand) {
1243 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1244 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1245 UsedCands.push_back(BestCand);
1246 Cand.IntvIdx = SE->openIntv();
1247 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1248 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001249 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001250 }
1251 }
1252
1253 // Assign bundles for the compact region.
1254 if (HasCompact) {
1255 GlobalSplitCandidate &Cand = GlobalCand.front();
1256 assert(!Cand.PhysReg && "Compact region has no physreg");
1257 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1258 UsedCands.push_back(0);
1259 Cand.IntvIdx = SE->openIntv();
1260 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1261 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001262 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001263 }
1264 }
1265
1266 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001267 return 0;
1268}
1269
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001270
1271//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001272// Per-Block Splitting
1273//===----------------------------------------------------------------------===//
1274
1275/// tryBlockSplit - Split a global live range around every block with uses. This
1276/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1277/// they don't allocate.
1278unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1279 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1280 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1281 unsigned Reg = VirtReg.reg;
1282 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001283 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001284 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001285 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1286 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1287 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1288 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1289 SE->splitSingleBlock(BI);
1290 }
1291 // No blocks were split.
1292 if (LREdit.empty())
1293 return 0;
1294
1295 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001296 SmallVector<unsigned, 8> IntvMap;
1297 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001298
1299 // Tell LiveDebugVariables about the new ranges.
1300 DebugVars->splitRegister(Reg, LREdit.regs());
1301
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001302 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1303
1304 // Sort out the new intervals created by splitting. The remainder interval
1305 // goes straight to spilling, the new local ranges get to stay RS_New.
1306 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1307 LiveInterval &LI = *LREdit.get(i);
1308 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1309 setStage(LI, RS_Spill);
1310 }
1311
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001312 if (VerifyEnabled)
1313 MF->verify(this, "After splitting live range around basic blocks");
1314 return 0;
1315}
1316
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001317
1318//===----------------------------------------------------------------------===//
1319// Per-Instruction Splitting
1320//===----------------------------------------------------------------------===//
1321
1322/// tryInstructionSplit - Split a live range around individual instructions.
1323/// This is normally not worthwhile since the spiller is doing essentially the
1324/// same thing. However, when the live range is in a constrained register
1325/// class, it may help to insert copies such that parts of the live range can
1326/// be moved to a larger register class.
1327///
1328/// This is similar to spilling to a larger register class.
1329unsigned
1330RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1331 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1332 // There is no point to this if there are no larger sub-classes.
1333 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1334 return 0;
1335
1336 // Always enable split spill mode, since we're effectively spilling to a
1337 // register.
1338 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1339 SE->reset(LREdit, SplitEditor::SM_Size);
1340
1341 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1342 if (Uses.size() <= 1)
1343 return 0;
1344
1345 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1346
1347 // Split around every non-copy instruction.
1348 for (unsigned i = 0; i != Uses.size(); ++i) {
1349 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1350 if (MI->isFullCopy()) {
1351 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1352 continue;
1353 }
1354 SE->openIntv();
1355 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1356 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1357 SE->useIntv(SegStart, SegStop);
1358 }
1359
1360 if (LREdit.empty()) {
1361 DEBUG(dbgs() << "All uses were copies.\n");
1362 return 0;
1363 }
1364
1365 SmallVector<unsigned, 8> IntvMap;
1366 SE->finish(&IntvMap);
1367 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1368 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1369
1370 // Assign all new registers to RS_Spill. This was the last chance.
1371 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1372 return 0;
1373}
1374
1375
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001376//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001377// Local Splitting
1378//===----------------------------------------------------------------------===//
1379
1380
1381/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1382/// in order to use PhysReg between two entries in SA->UseSlots.
1383///
1384/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1385///
1386void RAGreedy::calcGapWeights(unsigned PhysReg,
1387 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001388 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1389 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001390 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001391 const unsigned NumGaps = Uses.size()-1;
1392
1393 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001394 SlotIndex StartIdx =
1395 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1396 SlotIndex StopIdx =
1397 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001398
1399 GapWeight.assign(NumGaps, 0.0f);
1400
1401 // Add interference from each overlapping register.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001402 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1403 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1404 .checkInterference())
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001405 continue;
1406
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001407 // We know that VirtReg is a continuous interval from FirstInstr to
1408 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001409 //
1410 // Interference that overlaps an instruction is counted in both gaps
1411 // surrounding the instruction. The exception is interference before
1412 // StartIdx and after StopIdx.
1413 //
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001414 LiveIntervalUnion::SegmentIter IntI =
1415 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001416 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1417 // Skip the gaps before IntI.
1418 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1419 if (++Gap == NumGaps)
1420 break;
1421 if (Gap == NumGaps)
1422 break;
1423
1424 // Update the gaps covered by IntI.
1425 const float weight = IntI.value()->weight;
1426 for (; Gap != NumGaps; ++Gap) {
1427 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1428 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1429 break;
1430 }
1431 if (Gap == NumGaps)
1432 break;
1433 }
1434 }
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001435
1436 // Add fixed interference.
1437 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1438 const LiveInterval &LI = LIS->getRegUnit(*Units);
1439 LiveInterval::const_iterator I = LI.find(StartIdx);
1440 LiveInterval::const_iterator E = LI.end();
1441
1442 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1443 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1444 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1445 if (++Gap == NumGaps)
1446 break;
1447 if (Gap == NumGaps)
1448 break;
1449
1450 for (; Gap != NumGaps; ++Gap) {
1451 GapWeight[Gap] = HUGE_VALF;
1452 if (Uses[Gap+1].getBaseIndex() >= I->end)
1453 break;
1454 }
1455 if (Gap == NumGaps)
1456 break;
1457 }
1458 }
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001459}
1460
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001461/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1462/// basic block.
1463///
1464unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1465 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001466 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1467 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001468
1469 // Note that it is possible to have an interval that is live-in or live-out
1470 // while only covering a single block - A phi-def can use undef values from
1471 // predecessors, and the block could be a single-block loop.
1472 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001473 // that the interval is continuous from FirstInstr to LastInstr. We should
1474 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001475
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001476 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001477 if (Uses.size() <= 2)
1478 return 0;
1479 const unsigned NumGaps = Uses.size()-1;
1480
1481 DEBUG({
1482 dbgs() << "tryLocalSplit: ";
1483 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001484 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001485 dbgs() << '\n';
1486 });
1487
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001488 // If VirtReg is live across any register mask operands, compute a list of
1489 // gaps with register masks.
1490 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001491 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001492 // Get regmask slots for the whole block.
1493 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001494 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001495 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001496 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1497 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001498 unsigned re = RMS.size();
1499 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001500 // Look for Uses[i] <= RMS <= Uses[i+1].
1501 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1502 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001503 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001504 // Skip a regmask on the same instruction as the last use. It doesn't
1505 // overlap the live range.
1506 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1507 break;
1508 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001509 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001510 // Advance ri to the next gap. A regmask on one of the uses counts in
1511 // both gaps.
1512 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1513 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001514 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001515 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001516 }
1517
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001518 // Since we allow local split results to be split again, there is a risk of
1519 // creating infinite loops. It is tempting to require that the new live
1520 // ranges have less instructions than the original. That would guarantee
1521 // convergence, but it is too strict. A live range with 3 instructions can be
1522 // split 2+3 (including the COPY), and we want to allow that.
1523 //
1524 // Instead we use these rules:
1525 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001526 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001527 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001528 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001529 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001530 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001531 // smaller ranges are marked RS_New.
1532 //
1533 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1534 // excessive splitting and infinite loops.
1535 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001536 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001537
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001538 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001539 unsigned BestBefore = NumGaps;
1540 unsigned BestAfter = 0;
1541 float BestDiff = 0;
1542
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001543 const float blockFreq =
1544 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1545 (1.0f / BlockFrequency::getEntryFrequency());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001546 SmallVector<float, 8> GapWeight;
1547
1548 Order.rewind();
1549 while (unsigned PhysReg = Order.next()) {
1550 // Keep track of the largest spill weight that would need to be evicted in
1551 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1552 calcGapWeights(PhysReg, GapWeight);
1553
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001554 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001555 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001556 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1557 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1558
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001559 // Try to find the best sequence of gaps to close.
1560 // The new spill weight must be larger than any gap interference.
1561
1562 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001563 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001564
1565 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1566 // It is the spill weight that needs to be evicted.
1567 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001568
1569 for (;;) {
1570 // Live before/after split?
1571 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1572 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1573
1574 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1575 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1576 << " i=" << MaxGap);
1577
1578 // Stop before the interval gets so big we wouldn't be making progress.
1579 if (!LiveBefore && !LiveAfter) {
1580 DEBUG(dbgs() << " all\n");
1581 break;
1582 }
1583 // Should the interval be extended or shrunk?
1584 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001585
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001586 // How many gaps would the new range have?
1587 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1588
1589 // Legally, without causing looping?
1590 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1591
1592 if (Legal && MaxGap < HUGE_VALF) {
1593 // Estimate the new spill weight. Each instruction reads or writes the
1594 // register. Conservatively assume there are no read-modify-write
1595 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001596 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001597 // Try to guess the size of the new interval.
1598 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1599 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1600 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001601 // Would this split be possible to allocate?
1602 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001603 DEBUG(dbgs() << " w=" << EstWeight);
1604 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001605 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001606 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001607 if (Diff > BestDiff) {
1608 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001609 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001610 BestBefore = SplitBefore;
1611 BestAfter = SplitAfter;
1612 }
1613 }
1614 }
1615
1616 // Try to shrink.
1617 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001618 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001619 DEBUG(dbgs() << " shrink\n");
1620 // Recompute the max when necessary.
1621 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1622 MaxGap = GapWeight[SplitBefore];
1623 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1624 MaxGap = std::max(MaxGap, GapWeight[i]);
1625 }
1626 continue;
1627 }
1628 MaxGap = 0;
1629 }
1630
1631 // Try to extend the interval.
1632 if (SplitAfter >= NumGaps) {
1633 DEBUG(dbgs() << " end\n");
1634 break;
1635 }
1636
1637 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001638 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001639 }
1640 }
1641
1642 // Didn't find any candidates?
1643 if (BestBefore == NumGaps)
1644 return 0;
1645
1646 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1647 << '-' << Uses[BestAfter] << ", " << BestDiff
1648 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1649
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001650 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001651 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001652
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001653 SE->openIntv();
1654 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1655 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1656 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001657 SmallVector<unsigned, 8> IntvMap;
1658 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001659 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001660
1661 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001662 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001663 // leave the new intervals as RS_New so they can compete.
1664 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1665 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1666 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1667 if (NewGaps >= NumGaps) {
1668 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1669 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001670 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1671 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001672 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001673 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1674 }
1675 DEBUG(dbgs() << '\n');
1676 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001677 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001678
1679 return 0;
1680}
1681
1682//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001683// Live Range Splitting
1684//===----------------------------------------------------------------------===//
1685
1686/// trySplit - Try to split VirtReg or one of its interferences, making it
1687/// assignable.
1688/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1689unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1690 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001691 // Ranges must be Split2 or less.
1692 if (getStage(VirtReg) >= RS_Spill)
1693 return 0;
1694
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001695 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001696 if (LIS->intervalIsInOneMBB(VirtReg)) {
1697 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001698 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001699 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1700 if (PhysReg || !NewVRegs.empty())
1701 return PhysReg;
1702 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001703 }
1704
1705 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001706
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001707 SA->analyze(&VirtReg);
1708
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001709 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1710 // coalescer. That may cause the range to become allocatable which means that
1711 // tryRegionSplit won't be making progress. This check should be replaced with
1712 // an assertion when the coalescer is fixed.
1713 if (SA->didRepairRange()) {
1714 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001715 Matrix->invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001716 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1717 return PhysReg;
1718 }
1719
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001720 // First try to split around a region spanning multiple blocks. RS_Split2
1721 // ranges already made dubious progress with region splitting, so they go
1722 // straight to single block splitting.
1723 if (getStage(VirtReg) < RS_Split2) {
1724 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1725 if (PhysReg || !NewVRegs.empty())
1726 return PhysReg;
1727 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001728
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001729 // Then isolate blocks.
1730 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001731}
1732
1733
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001734//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001735// Main Entry Point
1736//===----------------------------------------------------------------------===//
1737
1738unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001739 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001740 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001741 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001742 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1743 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001744
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001745 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001746 DEBUG(dbgs() << StageName[Stage]
1747 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001748
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001749 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001750 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001751 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001752 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001753 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1754 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001755
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001756 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1757
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001758 // The first time we see a live range, don't try to split or spill.
1759 // Wait until the second time, when all smaller ranges have been allocated.
1760 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001761 if (Stage < RS_Split) {
1762 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001763 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001764 NewVRegs.push_back(&VirtReg);
1765 return 0;
1766 }
1767
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001768 // If we couldn't allocate a register from spilling, there is probably some
1769 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001770 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001771 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001772
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001773 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001774 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1775 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001776 return PhysReg;
1777
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001778 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001779 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001780 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001781 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001782 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001783
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001784 if (VerifyEnabled)
1785 MF->verify(this, "After spilling");
1786
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001787 // The live virtual register requesting allocation was spilled, so tell
1788 // the caller not to allocate anything during this round.
1789 return 0;
1790}
1791
1792bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1793 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikie986d76d2012-08-22 17:18:53 +00001794 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001795
1796 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001797 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001798 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001799
Jakob Stoklund Olesend4348a22012-06-20 22:52:29 +00001800 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1801 getAnalysis<LiveIntervals>(),
1802 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001803 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramer4eed7562013-06-17 19:00:36 +00001804 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001805 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001806 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001807 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001808 Bundles = &getAnalysis<EdgeBundles>();
1809 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001810 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001811
Andrew Trick5dca6132013-07-25 07:26:26 +00001812 DEBUG(LIS->dump());
1813
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001814 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramer4eed7562013-06-17 19:00:36 +00001815 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001816 ExtraRegInfo.clear();
1817 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1818 NextCascade = 1;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001819 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001820 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001821
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001822 allocatePhysRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001823 releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001824 return true;
1825}