blob: 27dc07b54c9bee4de86c5d619e808d6967cb8e34 [file] [log] [blame]
Jakob Stoklund Olesenb8812a12010-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 Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen4d7432e2010-12-10 22:21:05 +000017#include "AllocationOrder.h"
Jakob Stoklund Olesen91cbcaf2011-04-02 06:03:35 +000018#include "InterferenceCache.h"
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +000019#include "LiveDebugVariables.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000020#include "RegAllocBase.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "Spiller.h"
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000025#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000026#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000027#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000028#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000029#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000030#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000032#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000033#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineLoopInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000037#include "llvm/CodeGen/RegAllocRegistry.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/CodeGen/VirtRegMap.h"
39#include "llvm/PassAnalysisSupport.h"
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +000040#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +000043#include "llvm/Support/Timer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000045#include <queue>
46
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000047using namespace llvm;
48
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000049STATISTIC(NumGlobalSplits, "Number of split global live ranges");
50STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000051STATISTIC(NumEvicted, "Number of interferences evicted");
52
Jakob Stoklund Oleseneecb2fb2011-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 Olesenb8812a12010-12-08 03:26:16 +000062static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
63 createGreedyRegisterAllocator);
64
65namespace {
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +000066class RAGreedy : public MachineFunctionPass,
67 public RegAllocBase,
68 private LiveRangeEdit::Delegate {
69
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000070 // context
71 MachineFunction *MF;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000072
73 // analyses
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000074 SlotIndexes *Indexes;
Benjamin Kramere2a1d892013-06-17 19:00:36 +000075 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000076 MachineDominatorTree *DomTree;
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +000077 MachineLoopInfo *Loops;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000078 EdgeBundles *Bundles;
79 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +000080 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000081
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000082 // state
Andy Gibbs95777552013-04-12 10:56:28 +000083 OwningPtr<Spiller> SpillerInstance;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000084 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +000085 unsigned NextCascade;
Jakob Stoklund Olesen5f9f0812011-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 Olesen3ef8cf12011-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 Olesen45011172011-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 Olesen3ef8cf12011-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 Olesen5f9f0812011-03-01 21:10:07 +0000121 };
122
Eli Friedman78bffa52013-09-10 23:18:14 +0000123#ifndef NDEBUG
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000124 static const char *const StageName[];
Eli Friedman78bffa52013-09-10 23:18:14 +0000125#endif
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000126
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000127 // RegInfo - Keep additional information about each live range.
128 struct RegInfo {
129 LiveRangeStage Stage;
130
131 // Cascade - Eviction loop prevention. See canEvictInterference().
132 unsigned Cascade;
133
134 RegInfo() : Stage(RS_New), Cascade(0) {}
135 };
136
137 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000138
139 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000140 return ExtraRegInfo[VirtReg.reg].Stage;
141 }
142
143 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
144 ExtraRegInfo.resize(MRI->getNumVirtRegs());
145 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000146 }
147
148 template<typename Iterator>
149 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000150 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000151 for (;Begin != End; ++Begin) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000152 unsigned Reg = *Begin;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000153 if (ExtraRegInfo[Reg].Stage == RS_New)
154 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000155 }
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000156 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000157
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000158 /// Cost of evicting interference.
159 struct EvictionCost {
160 unsigned BrokenHints; ///< Total number of broken hints.
161 float MaxWeight; ///< Maximum spill weight evicted.
162
Andrew Trick3621b8a2013-11-22 19:07:38 +0000163 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000164
Andrew Trick84852572013-07-25 18:35:14 +0000165 bool isMax() const { return BrokenHints == ~0u; }
166
Andrew Trick3621b8a2013-11-22 19:07:38 +0000167 void setMax() { BrokenHints = ~0u; }
168
169 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
170
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000171 bool operator<(const EvictionCost &O) const {
172 if (BrokenHints != O.BrokenHints)
173 return BrokenHints < O.BrokenHints;
174 return MaxWeight < O.MaxWeight;
175 }
176 };
177
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000178 // splitting state.
Andy Gibbs95777552013-04-12 10:56:28 +0000179 OwningPtr<SplitAnalysis> SA;
180 OwningPtr<SplitEditor> SE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000181
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000182 /// Cached per-block interference maps
183 InterferenceCache IntfCache;
184
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000185 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000186 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000187
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000188 /// Global live range splitting candidate info.
189 struct GlobalSplitCandidate {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000190 // Register intended for assignment, or 0.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000191 unsigned PhysReg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000192
193 // SplitKit interval index for this candidate.
194 unsigned IntvIdx;
195
196 // Interference for PhysReg.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000197 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000198
199 // Bundles where this candidate should be live.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000200 BitVector LiveBundles;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000201 SmallVector<unsigned, 8> ActiveBlocks;
202
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000203 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000204 PhysReg = Reg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000205 IntvIdx = 0;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000206 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000207 LiveBundles.clear();
208 ActiveBlocks.clear();
209 }
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000210
211 // Set B[i] = C for every live bundle where B[i] was NoCand.
212 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
213 unsigned Count = 0;
214 for (int i = LiveBundles.find_first(); i >= 0;
215 i = LiveBundles.find_next(i))
216 if (B[i] == NoCand) {
217 B[i] = C;
218 Count++;
219 }
220 return Count;
221 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000222 };
223
Aditya Nandakumarc1fd0dd2013-11-19 23:51:32 +0000224 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000225 /// This vector never shrinks, but grows to the size of the largest register
226 /// class.
227 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
228
Reid Klecknercd4a25d2013-10-08 20:15:11 +0000229 enum LLVM_ENUM_INT_TYPE(unsigned) { NoCand = ~0u };
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000230
231 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
232 /// NoCand which indicates the stack interval.
233 SmallVector<unsigned, 32> BundleCand;
234
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000235public:
236 RAGreedy();
237
238 /// Return the pass name.
239 virtual const char* getPassName() const {
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +0000240 return "Greedy Register Allocator";
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000241 }
242
243 /// RAGreedy analysis usage.
244 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000245 virtual void releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000246 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000247 virtual void enqueue(LiveInterval *LI);
248 virtual LiveInterval *dequeue();
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +0000249 virtual unsigned selectOrSplit(LiveInterval&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000250 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000251
252 /// Perform register allocation.
253 virtual bool runOnMachineFunction(MachineFunction &mf);
254
255 static char ID;
Andrew Trickccef0982010-12-09 18:15:21 +0000256
257private:
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000258 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000259 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000260 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000261
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000262 BlockFrequency calcSpillCost();
263 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000264 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000265 void growRegion(GlobalSplitCandidate &Cand);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000266 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000267 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000268 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000269 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000270 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000271 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
272 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
273 void evictInterference(LiveInterval&, unsigned,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000274 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000275
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000276 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000277 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000278 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000279 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000280 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000281 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +0000282 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000283 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +0000284 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000285 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000286 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000287 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000288 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000289 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000290};
291} // end anonymous namespace
292
293char RAGreedy::ID = 0;
294
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000295#ifndef NDEBUG
296const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000297 "RS_New",
298 "RS_Assign",
299 "RS_Split",
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000300 "RS_Split2",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000301 "RS_Spill",
302 "RS_Done"
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000303};
304#endif
305
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000306// Hysteresis to use when comparing floats.
307// This helps stabilize decisions based on float comparisons.
308const float Hysteresis = 0.98f;
309
310
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000311FunctionPass* llvm::createGreedyRegisterAllocator() {
312 return new RAGreedy();
313}
314
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000315RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000316 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000317 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000318 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
319 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola676c4052011-06-26 22:34:10 +0000320 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Tricke1c034f2012-01-17 06:55:03 +0000321 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000322 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
323 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
324 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
325 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000326 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000327 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
328 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000329}
330
331void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
332 AU.setPreservesCFG();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000333 AU.addRequired<MachineBlockFrequencyInfo>();
334 AU.addPreserved<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000335 AU.addRequired<AliasAnalysis>();
336 AU.addPreserved<AliasAnalysis>();
337 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen12243122012-06-08 23:44:45 +0000338 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000339 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000340 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000341 AU.addRequired<LiveDebugVariables>();
342 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000343 AU.addRequired<LiveStacks>();
344 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000345 AU.addRequired<MachineDominatorTree>();
346 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000347 AU.addRequired<MachineLoopInfo>();
348 AU.addPreserved<MachineLoopInfo>();
349 AU.addRequired<VirtRegMap>();
350 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000351 AU.addRequired<LiveRegMatrix>();
352 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000353 AU.addRequired<EdgeBundles>();
354 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000355 MachineFunctionPass::getAnalysisUsage(AU);
356}
357
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000358
359//===----------------------------------------------------------------------===//
360// LiveRangeEdit delegate methods
361//===----------------------------------------------------------------------===//
362
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000363bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000364 if (VRM->hasPhys(VirtReg)) {
365 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000366 return true;
367 }
368 // Unassigned virtreg is probably in the priority queue.
369 // RegAllocBase will erase it after dequeueing.
370 return false;
371}
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000372
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000373void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000374 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000375 return;
376
377 // Register is assigned, put it back on the queue for reassignment.
378 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000379 Matrix->unassign(LI);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000380 enqueue(&LI);
381}
382
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000383void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen811b9c42011-09-14 17:34:37 +0000384 // Cloning a register we haven't even heard about yet? Just ignore it.
385 if (!ExtraRegInfo.inBounds(Old))
386 return;
387
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000388 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000389 // be split into connected components. The new components are much smaller
390 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000391 // same stage as the parent.
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000392 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000393 ExtraRegInfo.grow(New);
394 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000395}
396
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000397void RAGreedy::releaseMemory() {
398 SpillerInstance.reset(0);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000399 ExtraRegInfo.clear();
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000400 GlobalCand.clear();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000401}
402
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000403void RAGreedy::enqueue(LiveInterval *LI) {
404 // Prioritize live ranges by size, assigning larger ranges first.
405 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000406 const unsigned Size = LI->getSize();
407 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000408 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
409 "Can only enqueue virtual registers");
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000410 unsigned Prio;
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000411
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000412 ExtraRegInfo.grow(Reg);
413 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000414 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000415
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000416 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000417 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +0000418 // everything else has been allocated.
419 Prio = Size;
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000420 } else {
Andrew Trick84852572013-07-25 18:35:14 +0000421 if (ExtraRegInfo[Reg].Stage == RS_Assign && !LI->empty() &&
422 LIS->intervalIsInOneMBB(*LI)) {
423 // Allocate original local ranges in linear instruction order. Since they
424 // are singly defined, this produces optimal coloring in the absence of
425 // global interference and other constraints.
Andrew Trickc7934b32013-07-30 19:59:19 +0000426 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
Andrew Trick84852572013-07-25 18:35:14 +0000427 }
428 else {
429 // Allocate global and split ranges in long->short order. Long ranges that
430 // don't fit should be spilled (or split) ASAP so they don't create
431 // interference. Mark a bit to prioritize global above local ranges.
432 Prio = (1u << 29) + Size;
433 }
434 // Mark a higher bit to prioritize global and local above RS_Split.
435 Prio |= (1u << 31);
Jakob Stoklund Olesenb51f65c2011-02-23 00:56:56 +0000436
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000437 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen74052b02012-12-03 23:23:50 +0000438 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000439 Prio |= (1u << 30);
440 }
Andrew Trickf4b1ee32013-07-25 18:35:22 +0000441 // The virtual register number is a tie breaker for same-sized ranges.
442 // Give lower vreg numbers higher priority to assign them first.
Jakob Stoklund Olesen291007b2012-04-02 22:30:39 +0000443 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000444}
445
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000446LiveInterval *RAGreedy::dequeue() {
447 if (Queue.empty())
448 return 0;
Jakob Stoklund Olesen291007b2012-04-02 22:30:39 +0000449 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000450 Queue.pop();
451 return LI;
452}
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000453
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000454
455//===----------------------------------------------------------------------===//
456// Direct Assignment
457//===----------------------------------------------------------------------===//
458
459/// tryAssign - Try to assign VirtReg to an available register.
460unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
461 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000462 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000463 Order.rewind();
464 unsigned PhysReg;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000465 while ((PhysReg = Order.next()))
466 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000467 break;
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000468 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000469 return PhysReg;
470
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000471 // PhysReg is available, but there may be a better choice.
472
473 // If we missed a simple hint, try to cheaply evict interference from the
474 // preferred register.
475 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000476 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000477 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
Andrew Trick3621b8a2013-11-22 19:07:38 +0000478 EvictionCost MaxCost;
479 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000480 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
481 evictInterference(VirtReg, Hint, NewVRegs);
482 return Hint;
483 }
484 }
485
486 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000487 unsigned Cost = TRI->getCostPerUse(PhysReg);
488
489 // Most registers have 0 additional cost.
490 if (!Cost)
491 return PhysReg;
492
493 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
494 << '\n');
495 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
496 return CheapReg ? CheapReg : PhysReg;
497}
498
499
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000500//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000501// Interference eviction
502//===----------------------------------------------------------------------===//
503
Andrew Trick8bb0a252013-07-25 18:35:19 +0000504unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
505 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
506 unsigned PhysReg;
507 while ((PhysReg = Order.next())) {
508 if (PhysReg == PrevReg)
509 continue;
510
511 MCRegUnitIterator Units(PhysReg, TRI);
512 for (; Units.isValid(); ++Units) {
513 // Instantiate a "subquery", not to be confused with the Queries array.
514 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
515 if (subQ.checkInterference())
516 break;
517 }
518 // If no units have interference, break out with the current PhysReg.
519 if (!Units.isValid())
520 break;
521 }
522 if (PhysReg)
523 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
524 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
525 << '\n');
526 return PhysReg;
527}
528
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000529/// shouldEvict - determine if A should evict the assigned live range B. The
530/// eviction policy defined by this function together with the allocation order
531/// defined by enqueue() decides which registers ultimately end up being split
532/// and spilled.
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000533///
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000534/// Cascade numbers are used to prevent infinite loops if this function is a
535/// cyclic relation.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000536///
537/// @param A The live range to be assigned.
538/// @param IsHint True when A is about to be assigned to its preferred
539/// register.
540/// @param B The live range to be evicted.
541/// @param BreaksHint True when B is already assigned to its preferred register.
542bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
543 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000544 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000545
546 // Be fairly aggressive about following hints as long as the evictee can be
547 // split.
548 if (CanSplit && IsHint && !BreaksHint)
549 return true;
550
Andrew Trick059e8002013-11-22 19:07:42 +0000551 if (A.weight > B.weight) {
552 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
553 return true;
554 }
555 return false;
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000556}
557
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000558/// canEvictInterference - Return true if all interferences between VirtReg and
559/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
560///
561/// @param VirtReg Live range that is about to be assigned.
562/// @param PhysReg Desired register for assignment.
Dmitri Gribenko881929c2012-09-12 16:59:47 +0000563/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000564/// @param MaxCost Only look for cheaper candidates and update with new cost
565/// when returning true.
566/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000567bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000568 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000569 // It is only possible to evict virtual register interference.
570 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
571 return false;
572
Andrew Trick84852572013-07-25 18:35:14 +0000573 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
574
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000575 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
576 // involved in an eviction before. If a cascade number was assigned, deny
577 // evicting anything with the same or a newer cascade number. This prevents
578 // infinite eviction loops.
579 //
580 // This works out so a register without a cascade number is allowed to evict
581 // anything, and it can be evicted by anything.
582 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
583 if (!Cascade)
584 Cascade = NextCascade;
585
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000586 EvictionCost Cost;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000587 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
588 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000589 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000590 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000591 return false;
592
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000593 // Check if any interfering live range is heavier than MaxWeight.
594 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
595 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000596 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
597 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000598 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000599 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000600 return false;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000601 // Once a live range becomes small enough, it is urgent that we find a
602 // register for it. This is indicated by an infinite spill weight. These
603 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen05e22452012-05-30 21:46:58 +0000604 //
605 // Also allow urgent evictions of unspillable ranges from a strictly
606 // larger allocation order.
607 bool Urgent = !VirtReg.isSpillable() &&
608 (Intf->isSpillable() ||
609 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
610 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000611 // Only evict older cascades or live ranges without a cascade.
612 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
613 if (Cascade <= IntfCascade) {
614 if (!Urgent)
615 return false;
616 // We permit breaking cascades for urgent evictions. It should be the
617 // last resort, though, so make it really expensive.
618 Cost.BrokenHints += 10;
619 }
620 // Would this break a satisfied hint?
621 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
622 // Update eviction cost.
623 Cost.BrokenHints += BreaksHint;
624 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
625 // Abort if this would be too expensive.
626 if (!(Cost < MaxCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000627 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000628 if (Urgent)
629 continue;
630 // If !MaxCost.isMax(), then we're just looking for a cheap register.
631 // Evicting another local live range in this case could lead to suboptimal
632 // coloring.
Andrew Trick8bb0a252013-07-25 18:35:19 +0000633 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
634 !canReassign(*Intf, PhysReg)) {
Andrew Trick84852572013-07-25 18:35:14 +0000635 return false;
Andrew Trick8bb0a252013-07-25 18:35:19 +0000636 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000637 // Finally, apply the eviction policy for non-urgent evictions.
Andrew Trick84852572013-07-25 18:35:14 +0000638 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesen73e18b72011-05-31 21:02:44 +0000639 return false;
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000640 }
641 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000642 MaxCost = Cost;
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000643 return true;
644}
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000645
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000646/// evictInterference - Evict any interferring registers that prevent VirtReg
647/// from being assigned to Physreg. This assumes that canEvictInterference
648/// returned true.
649void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000650 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000651 // Make sure that VirtReg has a cascade number, and assign that cascade
652 // number to every evicted register. These live ranges than then only be
653 // evicted by a newer cascade, preventing infinite loops.
654 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
655 if (!Cascade)
656 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
657
658 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
659 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000660
661 // Collect all interfering virtregs first.
662 SmallVector<LiveInterval*, 8> Intfs;
663 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
664 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000665 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000666 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
667 Intfs.append(IVR.begin(), IVR.end());
668 }
669
670 // Evict them second. This will invalidate the queries.
671 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
672 LiveInterval *Intf = Intfs[i];
673 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
674 if (!VRM->hasPhys(Intf->reg))
675 continue;
676 Matrix->unassign(*Intf);
677 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
678 VirtReg.isSpillable() < Intf->isSpillable()) &&
679 "Cannot decrease cascade number, illegal eviction");
680 ExtraRegInfo[Intf->reg].Cascade = Cascade;
681 ++NumEvicted;
Mark Laceyf9ea8852013-08-14 23:50:04 +0000682 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000683 }
684}
685
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000686/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +0000687/// @param VirtReg Currently unassigned virtual register.
688/// @param Order Physregs to try.
689/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000690unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
691 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000692 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000693 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000694 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
695
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000696 // Keep track of the cheapest interference seen so far.
Andrew Trick3621b8a2013-11-22 19:07:38 +0000697 EvictionCost BestCost;
698 BestCost.setMax();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000699 unsigned BestPhys = 0;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000700 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000701
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000702 // When we are just looking for a reduced cost per use, don't break any
703 // hints, and only evict smaller spill weights.
704 if (CostPerUseLimit < ~0u) {
705 BestCost.BrokenHints = 0;
706 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000707
708 // Check of any registers in RC are below CostPerUseLimit.
709 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
710 unsigned MinCost = RegClassInfo.getMinCost(RC);
711 if (MinCost >= CostPerUseLimit) {
712 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
713 << ", no cheaper registers to be found.\n");
714 return 0;
715 }
716
717 // It is normal for register classes to have a long tail of registers with
718 // the same cost. We don't need to look at them if they're too expensive.
719 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
720 OrderLimit = RegClassInfo.getLastCostChange(RC);
721 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
722 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000723 }
724
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000725 Order.rewind();
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000726 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000727 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
728 continue;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000729 // The first use of a callee-saved register in a function has cost 1.
730 // Don't start using a CSR when the CostPerUseLimit is low.
731 if (CostPerUseLimit == 1)
732 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
733 if (!MRI->isPhysRegUsed(CSR)) {
734 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
735 << PrintReg(CSR, TRI) << '\n');
736 continue;
737 }
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000738
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000739 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000740 continue;
741
742 // Best so far.
743 BestPhys = PhysReg;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000744
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000745 // Stop if the hint can be used.
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000746 if (Order.isHint())
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000747 break;
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000748 }
749
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000750 if (!BestPhys)
751 return 0;
752
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000753 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000754 return BestPhys;
Andrew Trickccef0982010-12-09 18:15:21 +0000755}
756
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000757
758//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000759// Region Splitting
760//===----------------------------------------------------------------------===//
761
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000762/// addSplitConstraints - Fill out the SplitConstraints vector based on the
763/// interference pattern in Physreg and its aliases. Add the constraints to
764/// SpillPlacement and return the static cost of this split in Cost, assuming
765/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000766/// Return false if there are no bundles with positive bias.
767bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000768 BlockFrequency &Cost) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000769 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000770
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000771 // Reset interference dependent info.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000772 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000773 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000774 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
775 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000776 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000777
Jakob Stoklund Olesenb1b76ad2011-02-09 22:50:26 +0000778 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000779 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000780 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
781 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie041f1aa2013-05-15 07:36:59 +0000782 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000783
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000784 if (!Intf.hasInterference())
785 continue;
786
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000787 // Number of spill code instructions to insert.
788 unsigned Ins = 0;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000789
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000790 // Interference for the live-in value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000791 if (BI.LiveIn) {
Jakob Stoklund Olesen89339072011-04-04 15:32:15 +0000792 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000793 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000794 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000795 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000796 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000797 ++Ins;
Jakob Stoklund Olesenf248b202011-02-08 23:02:58 +0000798 }
799
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000800 // Interference for the live-out value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000801 if (BI.LiveOut) {
Jakob Stoklund Olesend93b0e32011-04-05 04:20:29 +0000802 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000803 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000804 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000805 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000806 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000807 ++Ins;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000808 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000809
810 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000811 while (Ins--)
812 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000813 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000814 Cost = StaticCost;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000815
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000816 // Add constraints for use-blocks. Note that these are the only constraints
817 // that may add a positive bias, it is downhill from here.
818 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000819 return SpillPlacer->scanActiveBundles();
820}
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000821
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000822
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000823/// addThroughConstraints - Add constraints and links to SpillPlacer from the
824/// live-through blocks in Blocks.
825void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
826 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000827 const unsigned GroupSize = 8;
828 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000829 unsigned TBS[GroupSize];
830 unsigned B = 0, T = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000831
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000832 for (unsigned i = 0; i != Blocks.size(); ++i) {
833 unsigned Number = Blocks[i];
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000834 Intf.moveToBlock(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000835
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000836 if (!Intf.hasInterference()) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000837 assert(T < GroupSize && "Array overflow");
838 TBS[T] = Number;
839 if (++T == GroupSize) {
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000840 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000841 T = 0;
842 }
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000843 continue;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000844 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000845
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000846 assert(B < GroupSize && "Array overflow");
847 BCS[B].Number = Number;
848
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000849 // Interference for the live-in value.
850 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
851 BCS[B].Entry = SpillPlacement::MustSpill;
852 else
853 BCS[B].Entry = SpillPlacement::PrefSpill;
854
855 // Interference for the live-out value.
856 if (Intf.last() >= SA->getLastSplitPoint(Number))
857 BCS[B].Exit = SpillPlacement::MustSpill;
858 else
859 BCS[B].Exit = SpillPlacement::PrefSpill;
860
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000861 if (++B == GroupSize) {
862 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
863 SpillPlacer->addConstraints(Array);
864 B = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000865 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000866 }
867
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000868 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
869 SpillPlacer->addConstraints(Array);
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000870 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000871}
872
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000873void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000874 // Keep track of through blocks that have not been added to SpillPlacer.
875 BitVector Todo = SA->getThroughBlocks();
876 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
877 unsigned AddedTo = 0;
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000878#ifndef NDEBUG
879 unsigned Visited = 0;
880#endif
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000881
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000882 for (;;) {
883 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000884 // Find new through blocks in the periphery of PrefRegBundles.
885 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
886 unsigned Bundle = NewBundles[i];
887 // Look at all blocks connected to Bundle in the full graph.
888 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
889 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
890 I != E; ++I) {
891 unsigned Block = *I;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000892 if (!Todo.test(Block))
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000893 continue;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000894 Todo.reset(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000895 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000896 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000897#ifndef NDEBUG
898 ++Visited;
899#endif
900 }
901 }
902 // Any new blocks to add?
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +0000903 if (ActiveBlocks.size() == AddedTo)
904 break;
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +0000905
906 // Compute through constraints from the interference, or assume that all
907 // through blocks prefer spilling when forming compact regions.
908 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
909 if (Cand.PhysReg)
910 addThroughConstraints(Cand.Intf, NewBlocks);
911 else
Jakob Stoklund Olesen86954522011-08-03 23:09:38 +0000912 // Provide a strong negative bias on through blocks to prevent unwanted
913 // liveness on loop backedges.
914 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +0000915 AddedTo = ActiveBlocks.size();
916
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000917 // Perhaps iterating can enable more bundles?
918 SpillPlacer->iterate();
919 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000920 DEBUG(dbgs() << ", v=" << Visited);
921}
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000922
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000923/// calcCompactRegion - Compute the set of edge bundles that should be live
924/// when splitting the current live range into compact regions. Compact
925/// regions can be computed without looking at interference. They are the
926/// regions formed by removing all the live-through blocks from the live range.
927///
928/// Returns false if the current live range is already compact, or if the
929/// compact regions would form single block regions anyway.
930bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
931 // Without any through blocks, the live range is already compact.
932 if (!SA->getNumThroughBlocks())
933 return false;
934
935 // Compact regions don't correspond to any physreg.
936 Cand.reset(IntfCache, 0);
937
938 DEBUG(dbgs() << "Compact region bundles");
939
940 // Use the spill placer to determine the live bundles. GrowRegion pretends
941 // that all the through blocks have interference when PhysReg is unset.
942 SpillPlacer->prepare(Cand.LiveBundles);
943
944 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000945 BlockFrequency Cost;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000946 if (!addSplitConstraints(Cand.Intf, Cost)) {
947 DEBUG(dbgs() << ", none.\n");
948 return false;
949 }
950
951 growRegion(Cand);
952 SpillPlacer->finish();
953
954 if (!Cand.LiveBundles.any()) {
955 DEBUG(dbgs() << ", none.\n");
956 return false;
957 }
958
959 DEBUG({
960 for (int i = Cand.LiveBundles.find_first(); i>=0;
961 i = Cand.LiveBundles.find_next(i))
962 dbgs() << " EB#" << i;
963 dbgs() << ".\n";
964 });
965 return true;
966}
967
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000968/// calcSpillCost - Compute how expensive it would be to split the live range in
969/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000970BlockFrequency RAGreedy::calcSpillCost() {
971 BlockFrequency Cost = 0;
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000972 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
973 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
974 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
975 unsigned Number = BI.MBB->getNumber();
976 // We normally only need one spill instruction - a load or a store.
977 Cost += SpillPlacer->getBlockFrequency(Number);
978
979 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3c145052011-08-02 23:04:08 +0000980 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
981 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000982 }
983 return Cost;
984}
985
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000986/// calcGlobalSplitCost - Return the global split cost of following the split
987/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000988/// interference pattern in SplitConstraints.
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000989///
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000990BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
991 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000992 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000993 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
994 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
995 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000996 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +0000997 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
998 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
999 unsigned Ins = 0;
1000
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001001 if (BI.LiveIn)
1002 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1003 if (BI.LiveOut)
1004 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001005 while (Ins--)
1006 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001007 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001008
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001009 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1010 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001011 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1012 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001013 if (!RegIn && !RegOut)
1014 continue;
1015 if (RegIn && RegOut) {
1016 // We need double spill code if this block has interference.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001017 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001018 if (Cand.Intf.hasInterference()) {
1019 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1020 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1021 }
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001022 continue;
1023 }
1024 // live-in / stack-out or stack-in live-out.
1025 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001026 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001027 return GlobalCost;
1028}
1029
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001030/// splitAroundRegion - Split the current live range around the regions
1031/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001032///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001033/// Before calling this function, GlobalCand and BundleCand must be initialized
1034/// so each bundle is assigned to a valid candidate, or NoCand for the
1035/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1036/// objects must be initialized for the current live range, and intervals
1037/// created for the used candidates.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001038///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001039/// @param LREdit The LiveRangeEdit object handling the current split.
1040/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1041/// must appear in this list.
1042void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1043 ArrayRef<unsigned> UsedCands) {
1044 // These are the intervals created for new global ranges. We may create more
1045 // intervals for local ranges.
1046 const unsigned NumGlobalIntvs = LREdit.size();
1047 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1048 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001049
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001050 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen22f37a12011-08-06 18:20:24 +00001051 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001052 // is all copies.
1053 unsigned Reg = SA->getParent().reg;
1054 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1055
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001056 // First handle all the blocks with uses.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001057 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1058 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1059 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001060 unsigned Number = BI.MBB->getNumber();
1061 unsigned IntvIn = 0, IntvOut = 0;
1062 SlotIndex IntfIn, IntfOut;
1063 if (BI.LiveIn) {
1064 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1065 if (CandIn != NoCand) {
1066 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1067 IntvIn = Cand.IntvIdx;
1068 Cand.Intf.moveToBlock(Number);
1069 IntfIn = Cand.Intf.first();
1070 }
1071 }
1072 if (BI.LiveOut) {
1073 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1074 if (CandOut != NoCand) {
1075 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1076 IntvOut = Cand.IntvIdx;
1077 Cand.Intf.moveToBlock(Number);
1078 IntfOut = Cand.Intf.last();
1079 }
1080 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001081
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001082 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001083 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001084 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001085 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001086 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001087 continue;
1088 }
1089
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001090 if (IntvIn && IntvOut)
1091 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1092 else if (IntvIn)
1093 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesen795da1c2011-07-15 21:47:57 +00001094 else
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001095 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001096 }
1097
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001098 // Handle live-through blocks. The relevant live-through blocks are stored in
1099 // the ActiveBlocks list with each candidate. We need to filter out
1100 // duplicates.
1101 BitVector Todo = SA->getThroughBlocks();
1102 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1103 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1104 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1105 unsigned Number = Blocks[i];
1106 if (!Todo.test(Number))
1107 continue;
1108 Todo.reset(Number);
1109
1110 unsigned IntvIn = 0, IntvOut = 0;
1111 SlotIndex IntfIn, IntfOut;
1112
1113 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1114 if (CandIn != NoCand) {
1115 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1116 IntvIn = Cand.IntvIdx;
1117 Cand.Intf.moveToBlock(Number);
1118 IntfIn = Cand.Intf.first();
1119 }
1120
1121 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1122 if (CandOut != NoCand) {
1123 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1124 IntvOut = Cand.IntvIdx;
1125 Cand.Intf.moveToBlock(Number);
1126 IntfOut = Cand.Intf.last();
1127 }
1128 if (!IntvIn && !IntvOut)
1129 continue;
1130 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1131 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001132 }
1133
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001134 ++NumGlobalSplits;
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001135
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001136 SmallVector<unsigned, 8> IntvMap;
1137 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001138 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001139
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001140 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesen5cc91b22011-05-28 02:32:57 +00001141 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001142
1143 // Sort out the new intervals created by splitting. We get four kinds:
1144 // - Remainder intervals should not be split again.
1145 // - Candidate intervals can be assigned to Cand.PhysReg.
1146 // - Block-local splits are candidates for local splitting.
1147 // - DCE leftovers should go back on the queue.
1148 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001149 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001150
1151 // Ignore old intervals from DCE.
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001152 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001153 continue;
1154
1155 // Remainder interval. Don't try splitting again, spill if it doesn't
1156 // allocate.
1157 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001158 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001159 continue;
1160 }
1161
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001162 // Global intervals. Allow repeated splitting as long as the number of live
1163 // blocks is strictly decreasing.
1164 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001165 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001166 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1167 << " blocks as original.\n");
1168 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001169 setStage(Reg, RS_Split2);
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001170 }
1171 continue;
1172 }
1173
1174 // Other intervals are treated as new. This includes local intervals created
1175 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001176 }
1177
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +00001178 if (VerifyEnabled)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001179 MF->verify(this, "After splitting live range around region");
1180}
1181
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001182unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001183 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001184 unsigned NumCands = 0;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001185 unsigned BestCand = NoCand;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001186 BlockFrequency BestCost;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001187 SmallVector<unsigned, 8> UsedCands;
1188
1189 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +00001190 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001191 if (HasCompact) {
1192 // Yes, keep GlobalCand[0] as the compact region candidate.
1193 NumCands = 1;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001194 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001195 } else {
1196 // No benefit from the compact region, our fallback will be per-block
1197 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001198 BestCost = calcSpillCost();
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001199 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1200 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001201
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001202 Order.rewind();
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001203 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001204 // Discard bad candidates before we run out of interference cache cursors.
1205 // This will only affect register classes with a lot of registers (>32).
1206 if (NumCands == IntfCache.getMaxCursors()) {
1207 unsigned WorstCount = ~0u;
1208 unsigned Worst = 0;
1209 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001210 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001211 continue;
1212 unsigned Count = GlobalCand[i].LiveBundles.count();
1213 if (Count < WorstCount)
1214 Worst = i, WorstCount = Count;
1215 }
1216 --NumCands;
1217 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen559d4dc2011-11-01 00:02:31 +00001218 if (BestCand == NumCands)
1219 BestCand = Worst;
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001220 }
1221
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001222 if (GlobalCand.size() <= NumCands)
1223 GlobalCand.resize(NumCands+1);
1224 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1225 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001226
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001227 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001228 BlockFrequency Cost;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001229 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001230 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001231 continue;
1232 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001233 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001234 if (Cost >= BestCost) {
1235 DEBUG({
1236 if (BestCand == NoCand)
1237 dbgs() << " worse than no bundles\n";
1238 else
1239 dbgs() << " worse than "
1240 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1241 });
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001242 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001243 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001244 growRegion(Cand);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001245
Jakob Stoklund Olesen36b5d8a2011-04-06 19:13:57 +00001246 SpillPlacer->finish();
1247
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001248 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001249 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001250 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001251 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001252 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001253
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001254 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001255 DEBUG({
1256 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001257 for (int i = Cand.LiveBundles.find_first(); i>=0;
1258 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001259 dbgs() << " EB#" << i;
1260 dbgs() << ".\n";
1261 });
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001262 if (Cost < BestCost) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001263 BestCand = NumCands;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001264 BestCost = Cost;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001265 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001266 ++NumCands;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001267 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001268
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001269 // No solutions found, fall back to single block splitting.
1270 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001271 return 0;
1272
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001273 // Prepare split editor.
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001274 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001275 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001276
1277 // Assign all edge bundles to the preferred candidate, or NoCand.
1278 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1279
1280 // Assign bundles for the best candidate region.
1281 if (BestCand != NoCand) {
1282 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1283 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1284 UsedCands.push_back(BestCand);
1285 Cand.IntvIdx = SE->openIntv();
1286 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1287 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001288 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001289 }
1290 }
1291
1292 // Assign bundles for the compact region.
1293 if (HasCompact) {
1294 GlobalSplitCandidate &Cand = GlobalCand.front();
1295 assert(!Cand.PhysReg && "Compact region has no physreg");
1296 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1297 UsedCands.push_back(0);
1298 Cand.IntvIdx = SE->openIntv();
1299 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1300 << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001301 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001302 }
1303 }
1304
1305 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001306 return 0;
1307}
1308
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001309
1310//===----------------------------------------------------------------------===//
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001311// Per-Block Splitting
1312//===----------------------------------------------------------------------===//
1313
1314/// tryBlockSplit - Split a global live range around every block with uses. This
1315/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1316/// they don't allocate.
1317unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001318 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001319 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1320 unsigned Reg = VirtReg.reg;
1321 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001322 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001323 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001324 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1325 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1326 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1327 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1328 SE->splitSingleBlock(BI);
1329 }
1330 // No blocks were split.
1331 if (LREdit.empty())
1332 return 0;
1333
1334 // We did split for some blocks.
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001335 SmallVector<unsigned, 8> IntvMap;
1336 SE->finish(&IntvMap);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001337
1338 // Tell LiveDebugVariables about the new ranges.
Mark Laceyf9ea8852013-08-14 23:50:04 +00001339 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001340
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001341 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1342
1343 // Sort out the new intervals created by splitting. The remainder interval
1344 // goes straight to spilling, the new local ranges get to stay RS_New.
1345 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001346 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001347 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1348 setStage(LI, RS_Spill);
1349 }
1350
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001351 if (VerifyEnabled)
1352 MF->verify(this, "After splitting live range around basic blocks");
1353 return 0;
1354}
1355
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001356
1357//===----------------------------------------------------------------------===//
1358// Per-Instruction Splitting
1359//===----------------------------------------------------------------------===//
1360
1361/// tryInstructionSplit - Split a live range around individual instructions.
1362/// This is normally not worthwhile since the spiller is doing essentially the
1363/// same thing. However, when the live range is in a constrained register
1364/// class, it may help to insert copies such that parts of the live range can
1365/// be moved to a larger register class.
1366///
1367/// This is similar to spilling to a larger register class.
1368unsigned
1369RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001370 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001371 // There is no point to this if there are no larger sub-classes.
1372 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1373 return 0;
1374
1375 // Always enable split spill mode, since we're effectively spilling to a
1376 // register.
1377 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1378 SE->reset(LREdit, SplitEditor::SM_Size);
1379
1380 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1381 if (Uses.size() <= 1)
1382 return 0;
1383
1384 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1385
1386 // Split around every non-copy instruction.
1387 for (unsigned i = 0; i != Uses.size(); ++i) {
1388 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1389 if (MI->isFullCopy()) {
1390 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1391 continue;
1392 }
1393 SE->openIntv();
1394 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1395 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1396 SE->useIntv(SegStart, SegStop);
1397 }
1398
1399 if (LREdit.empty()) {
1400 DEBUG(dbgs() << "All uses were copies.\n");
1401 return 0;
1402 }
1403
1404 SmallVector<unsigned, 8> IntvMap;
1405 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001406 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001407 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1408
1409 // Assign all new registers to RS_Spill. This was the last chance.
1410 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1411 return 0;
1412}
1413
1414
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001415//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001416// Local Splitting
1417//===----------------------------------------------------------------------===//
1418
1419
1420/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1421/// in order to use PhysReg between two entries in SA->UseSlots.
1422///
1423/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1424///
1425void RAGreedy::calcGapWeights(unsigned PhysReg,
1426 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001427 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1428 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001429 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001430 const unsigned NumGaps = Uses.size()-1;
1431
1432 // Start and end points for the interference check.
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001433 SlotIndex StartIdx =
1434 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1435 SlotIndex StopIdx =
1436 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001437
1438 GapWeight.assign(NumGaps, 0.0f);
1439
1440 // Add interference from each overlapping register.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001441 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1442 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1443 .checkInterference())
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001444 continue;
1445
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001446 // We know that VirtReg is a continuous interval from FirstInstr to
1447 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001448 //
1449 // Interference that overlaps an instruction is counted in both gaps
1450 // surrounding the instruction. The exception is interference before
1451 // StartIdx and after StopIdx.
1452 //
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001453 LiveIntervalUnion::SegmentIter IntI =
1454 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001455 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1456 // Skip the gaps before IntI.
1457 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1458 if (++Gap == NumGaps)
1459 break;
1460 if (Gap == NumGaps)
1461 break;
1462
1463 // Update the gaps covered by IntI.
1464 const float weight = IntI.value()->weight;
1465 for (; Gap != NumGaps; ++Gap) {
1466 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1467 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1468 break;
1469 }
1470 if (Gap == NumGaps)
1471 break;
1472 }
1473 }
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001474
1475 // Add fixed interference.
1476 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001477 const LiveRange &LR = LIS->getRegUnit(*Units);
1478 LiveRange::const_iterator I = LR.find(StartIdx);
1479 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001480
1481 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1482 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1483 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1484 if (++Gap == NumGaps)
1485 break;
1486 if (Gap == NumGaps)
1487 break;
1488
1489 for (; Gap != NumGaps; ++Gap) {
Aaron Ballman04999042013-11-13 00:15:44 +00001490 GapWeight[Gap] = llvm::huge_valf;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001491 if (Uses[Gap+1].getBaseIndex() >= I->end)
1492 break;
1493 }
1494 if (Gap == NumGaps)
1495 break;
1496 }
1497 }
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001498}
1499
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001500/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1501/// basic block.
1502///
1503unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001504 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001505 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1506 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001507
1508 // Note that it is possible to have an interval that is live-in or live-out
1509 // while only covering a single block - A phi-def can use undef values from
1510 // predecessors, and the block could be a single-block loop.
1511 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001512 // that the interval is continuous from FirstInstr to LastInstr. We should
1513 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001514
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001515 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001516 if (Uses.size() <= 2)
1517 return 0;
1518 const unsigned NumGaps = Uses.size()-1;
1519
1520 DEBUG({
1521 dbgs() << "tryLocalSplit: ";
1522 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001523 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001524 dbgs() << '\n';
1525 });
1526
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001527 // If VirtReg is live across any register mask operands, compute a list of
1528 // gaps with register masks.
1529 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001530 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001531 // Get regmask slots for the whole block.
1532 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001533 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001534 // Constrain to VirtReg's live range.
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001535 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1536 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001537 unsigned re = RMS.size();
1538 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001539 // Look for Uses[i] <= RMS <= Uses[i+1].
1540 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1541 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001542 continue;
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001543 // Skip a regmask on the same instruction as the last use. It doesn't
1544 // overlap the live range.
1545 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1546 break;
1547 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001548 RegMaskGaps.push_back(i);
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001549 // Advance ri to the next gap. A regmask on one of the uses counts in
1550 // both gaps.
1551 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1552 ++ri;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001553 }
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001554 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001555 }
1556
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001557 // Since we allow local split results to be split again, there is a risk of
1558 // creating infinite loops. It is tempting to require that the new live
1559 // ranges have less instructions than the original. That would guarantee
1560 // convergence, but it is too strict. A live range with 3 instructions can be
1561 // split 2+3 (including the COPY), and we want to allow that.
1562 //
1563 // Instead we use these rules:
1564 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001565 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001566 // noop split, of course).
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001567 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001568 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001569 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001570 // smaller ranges are marked RS_New.
1571 //
1572 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1573 // excessive splitting and infinite loops.
1574 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001575 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001576
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001577 // Best split candidate.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001578 unsigned BestBefore = NumGaps;
1579 unsigned BestAfter = 0;
1580 float BestDiff = 0;
1581
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001582 const float blockFreq =
1583 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1584 (1.0f / BlockFrequency::getEntryFrequency());
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001585 SmallVector<float, 8> GapWeight;
1586
1587 Order.rewind();
1588 while (unsigned PhysReg = Order.next()) {
1589 // Keep track of the largest spill weight that would need to be evicted in
1590 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1591 calcGapWeights(PhysReg, GapWeight);
1592
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001593 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001594 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001595 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Aaron Ballman04999042013-11-13 00:15:44 +00001596 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001597
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001598 // Try to find the best sequence of gaps to close.
1599 // The new spill weight must be larger than any gap interference.
1600
1601 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001602 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001603
1604 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1605 // It is the spill weight that needs to be evicted.
1606 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001607
1608 for (;;) {
1609 // Live before/after split?
1610 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1611 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1612
1613 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1614 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1615 << " i=" << MaxGap);
1616
1617 // Stop before the interval gets so big we wouldn't be making progress.
1618 if (!LiveBefore && !LiveAfter) {
1619 DEBUG(dbgs() << " all\n");
1620 break;
1621 }
1622 // Should the interval be extended or shrunk?
1623 bool Shrink = true;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001624
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001625 // How many gaps would the new range have?
1626 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1627
1628 // Legally, without causing looping?
1629 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1630
Aaron Ballman04999042013-11-13 00:15:44 +00001631 if (Legal && MaxGap < llvm::huge_valf) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001632 // Estimate the new spill weight. Each instruction reads or writes the
1633 // register. Conservatively assume there are no read-modify-write
1634 // instructions.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001635 //
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001636 // Try to guess the size of the new interval.
1637 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1638 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1639 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001640 // Would this split be possible to allocate?
1641 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001642 DEBUG(dbgs() << " w=" << EstWeight);
1643 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001644 Shrink = false;
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001645 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001646 if (Diff > BestDiff) {
1647 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001648 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001649 BestBefore = SplitBefore;
1650 BestAfter = SplitAfter;
1651 }
1652 }
1653 }
1654
1655 // Try to shrink.
1656 if (Shrink) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001657 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001658 DEBUG(dbgs() << " shrink\n");
1659 // Recompute the max when necessary.
1660 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1661 MaxGap = GapWeight[SplitBefore];
1662 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1663 MaxGap = std::max(MaxGap, GapWeight[i]);
1664 }
1665 continue;
1666 }
1667 MaxGap = 0;
1668 }
1669
1670 // Try to extend the interval.
1671 if (SplitAfter >= NumGaps) {
1672 DEBUG(dbgs() << " end\n");
1673 break;
1674 }
1675
1676 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001677 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001678 }
1679 }
1680
1681 // Didn't find any candidates?
1682 if (BestBefore == NumGaps)
1683 return 0;
1684
1685 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1686 << '-' << Uses[BestAfter] << ", " << BestDiff
1687 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1688
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001689 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001690 SE->reset(LREdit);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001691
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001692 SE->openIntv();
1693 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1694 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1695 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001696 SmallVector<unsigned, 8> IntvMap;
1697 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001698 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001699
1700 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001701 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001702 // leave the new intervals as RS_New so they can compete.
1703 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1704 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1705 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1706 if (NewGaps >= NumGaps) {
1707 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1708 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001709 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1710 if (IntvMap[i] == 1) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001711 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1712 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001713 }
1714 DEBUG(dbgs() << '\n');
1715 }
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001716 ++NumLocalSplits;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001717
1718 return 0;
1719}
1720
1721//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001722// Live Range Splitting
1723//===----------------------------------------------------------------------===//
1724
1725/// trySplit - Try to split VirtReg or one of its interferences, making it
1726/// assignable.
1727/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1728unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001729 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesend4bb1d42011-08-05 23:50:33 +00001730 // Ranges must be Split2 or less.
1731 if (getStage(VirtReg) >= RS_Spill)
1732 return 0;
1733
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001734 // Local intervals are handled separately.
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001735 if (LIS->intervalIsInOneMBB(VirtReg)) {
1736 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001737 SA->analyze(&VirtReg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001738 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1739 if (PhysReg || !NewVRegs.empty())
1740 return PhysReg;
1741 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001742 }
1743
1744 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001745
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001746 SA->analyze(&VirtReg);
1747
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00001748 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1749 // coalescer. That may cause the range to become allocatable which means that
1750 // tryRegionSplit won't be making progress. This check should be replaced with
1751 // an assertion when the coalescer is fixed.
1752 if (SA->didRepairRange()) {
1753 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001754 Matrix->invalidateVirtRegs();
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00001755 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1756 return PhysReg;
1757 }
1758
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001759 // First try to split around a region spanning multiple blocks. RS_Split2
1760 // ranges already made dubious progress with region splitting, so they go
1761 // straight to single block splitting.
1762 if (getStage(VirtReg) < RS_Split2) {
1763 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1764 if (PhysReg || !NewVRegs.empty())
1765 return PhysReg;
1766 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001767
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001768 // Then isolate blocks.
1769 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001770}
1771
1772
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001773//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001774// Main Entry Point
1775//===----------------------------------------------------------------------===//
1776
1777unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001778 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001779 // First try assigning a free register.
Jakob Stoklund Olesenb8bf3c02011-06-03 20:34:53 +00001780 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001781 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1782 return PhysReg;
Andrew Trickccef0982010-12-09 18:15:21 +00001783
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00001784 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001785 DEBUG(dbgs() << StageName[Stage]
1786 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00001787
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001788 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001789 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001790 // get a second chance until they have been split.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001791 if (Stage != RS_Split)
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001792 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1793 return PhysReg;
Andrew Trickccef0982010-12-09 18:15:21 +00001794
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001795 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1796
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00001797 // The first time we see a live range, don't try to split or spill.
1798 // Wait until the second time, when all smaller ranges have been allocated.
1799 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001800 if (Stage < RS_Split) {
1801 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesen86985072011-03-19 23:02:47 +00001802 DEBUG(dbgs() << "wait for second round\n");
Mark Laceyf9ea8852013-08-14 23:50:04 +00001803 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00001804 return 0;
1805 }
1806
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00001807 // If we couldn't allocate a register from spilling, there is probably some
1808 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001809 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00001810 return ~0u;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001811
Jakob Stoklund Olesen903b6d32010-12-14 00:37:49 +00001812 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001813 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1814 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +00001815 return PhysReg;
1816
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001817 // Finally spill VirtReg itself.
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +00001818 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001819 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen4d6eafa2011-03-10 01:51:42 +00001820 spiller().spill(LRE);
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001821 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001822
Jakob Stoklund Olesen557a82c2011-03-16 22:56:08 +00001823 if (VerifyEnabled)
1824 MF->verify(this, "After spilling");
1825
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001826 // The live virtual register requesting allocation was spilled, so tell
1827 // the caller not to allocate anything during this round.
1828 return 0;
1829}
1830
1831bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1832 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikiec8c29202012-08-22 17:18:53 +00001833 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001834
1835 MF = &mf;
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00001836 if (VerifyEnabled)
Jakob Stoklund Olesenbf4550e2010-12-18 00:06:56 +00001837 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00001838
Jakob Stoklund Olesen2d2dec92012-06-20 22:52:29 +00001839 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1840 getAnalysis<LiveIntervals>(),
1841 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001842 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +00001843 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +00001844 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenadecb5e2010-12-10 22:54:44 +00001845 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00001846 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001847 Bundles = &getAnalysis<EdgeBundles>();
1848 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001849 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001850
Arnaud A. de Grandmaisonea3ac162013-11-11 19:04:45 +00001851 calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +00001852
Andrew Trick97064962013-07-25 07:26:26 +00001853 DEBUG(LIS->dump());
1854
Jakob Stoklund Olesenf1a60a62011-02-19 00:53:42 +00001855 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramere2a1d892013-06-17 19:00:36 +00001856 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001857 ExtraRegInfo.clear();
1858 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1859 NextCascade = 1;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001860 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001861 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00001862
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001863 allocatePhysRegs();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001864 releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001865 return true;
1866}