blob: 50b7553ad16d3b51dd9857de7bb4e517fcdd077e [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"
Quentin Colombet1fb3362a2014-01-02 22:47:22 +000038#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/CodeGen/VirtRegMap.h"
40#include "llvm/PassAnalysisSupport.h"
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +000041#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000042#include "llvm/Support/Debug.h"
43#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +000044#include "llvm/Support/Timer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000045#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000046#include <queue>
47
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000048using namespace llvm;
49
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000050STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000052STATISTIC(NumEvicted, "Number of interferences evicted");
53
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +000054static cl::opt<SplitEditor::ComplementSpillMode>
55SplitSpillMode("split-spill-mode", cl::Hidden,
56 cl::desc("Spill mode for splitting live ranges"),
57 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
58 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
59 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
60 clEnumValEnd),
61 cl::init(SplitEditor::SM_Partition));
62
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000063static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
64 createGreedyRegisterAllocator);
65
66namespace {
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +000067class RAGreedy : public MachineFunctionPass,
68 public RegAllocBase,
69 private LiveRangeEdit::Delegate {
70
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000071 // context
72 MachineFunction *MF;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000073
Quentin Colombet1fb3362a2014-01-02 22:47:22 +000074 // Shortcuts to some useful interface.
75 const TargetInstrInfo *TII;
76 const TargetRegisterInfo *TRI;
77 RegisterClassInfo RCI;
78
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000079 // analyses
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000080 SlotIndexes *Indexes;
Benjamin Kramere2a1d892013-06-17 19:00:36 +000081 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000082 MachineDominatorTree *DomTree;
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +000083 MachineLoopInfo *Loops;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000084 EdgeBundles *Bundles;
85 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +000086 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000087
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000088 // state
Andy Gibbs95777552013-04-12 10:56:28 +000089 OwningPtr<Spiller> SpillerInstance;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000090 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +000091 unsigned NextCascade;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +000092
93 // Live ranges pass through a number of stages as we try to allocate them.
94 // Some of the stages may also create new live ranges:
95 //
96 // - Region splitting.
97 // - Per-block splitting.
98 // - Local splitting.
99 // - Spilling.
100 //
101 // Ranges produced by one of the stages skip the previous stages when they are
102 // dequeued. This improves performance because we can skip interference checks
103 // that are unlikely to give any results. It also guarantees that the live
104 // range splitting algorithm terminates, something that is otherwise hard to
105 // ensure.
106 enum LiveRangeStage {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000107 /// Newly created live range that has never been queued.
108 RS_New,
109
110 /// Only attempt assignment and eviction. Then requeue as RS_Split.
111 RS_Assign,
112
113 /// Attempt live range splitting if assignment is impossible.
114 RS_Split,
115
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000116 /// Attempt more aggressive live range splitting that is guaranteed to make
117 /// progress. This is used for split products that may not be making
118 /// progress.
119 RS_Split2,
120
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000121 /// Live range will be spilled. No more splitting will be attempted.
122 RS_Spill,
123
124 /// There is nothing more we can do to this live range. Abort compilation
125 /// if it can't be assigned.
126 RS_Done
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000127 };
128
Eli Friedman78bffa52013-09-10 23:18:14 +0000129#ifndef NDEBUG
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000130 static const char *const StageName[];
Eli Friedman78bffa52013-09-10 23:18:14 +0000131#endif
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000132
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000133 // RegInfo - Keep additional information about each live range.
134 struct RegInfo {
135 LiveRangeStage Stage;
136
137 // Cascade - Eviction loop prevention. See canEvictInterference().
138 unsigned Cascade;
139
140 RegInfo() : Stage(RS_New), Cascade(0) {}
141 };
142
143 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000144
145 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000146 return ExtraRegInfo[VirtReg.reg].Stage;
147 }
148
149 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
150 ExtraRegInfo.resize(MRI->getNumVirtRegs());
151 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000152 }
153
154 template<typename Iterator>
155 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000156 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000157 for (;Begin != End; ++Begin) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000158 unsigned Reg = *Begin;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000159 if (ExtraRegInfo[Reg].Stage == RS_New)
160 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000161 }
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000162 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000163
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000164 /// Cost of evicting interference.
165 struct EvictionCost {
166 unsigned BrokenHints; ///< Total number of broken hints.
167 float MaxWeight; ///< Maximum spill weight evicted.
168
Andrew Trick3621b8a2013-11-22 19:07:38 +0000169 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000170
Andrew Trick84852572013-07-25 18:35:14 +0000171 bool isMax() const { return BrokenHints == ~0u; }
172
Andrew Trick3621b8a2013-11-22 19:07:38 +0000173 void setMax() { BrokenHints = ~0u; }
174
175 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
176
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000177 bool operator<(const EvictionCost &O) const {
178 if (BrokenHints != O.BrokenHints)
179 return BrokenHints < O.BrokenHints;
180 return MaxWeight < O.MaxWeight;
181 }
182 };
183
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000184 // splitting state.
Andy Gibbs95777552013-04-12 10:56:28 +0000185 OwningPtr<SplitAnalysis> SA;
186 OwningPtr<SplitEditor> SE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000187
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000188 /// Cached per-block interference maps
189 InterferenceCache IntfCache;
190
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000191 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000192 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000193
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000194 /// Global live range splitting candidate info.
195 struct GlobalSplitCandidate {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000196 // Register intended for assignment, or 0.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000197 unsigned PhysReg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000198
199 // SplitKit interval index for this candidate.
200 unsigned IntvIdx;
201
202 // Interference for PhysReg.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000203 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000204
205 // Bundles where this candidate should be live.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000206 BitVector LiveBundles;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000207 SmallVector<unsigned, 8> ActiveBlocks;
208
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000209 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000210 PhysReg = Reg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000211 IntvIdx = 0;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000212 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000213 LiveBundles.clear();
214 ActiveBlocks.clear();
215 }
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000216
217 // Set B[i] = C for every live bundle where B[i] was NoCand.
218 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
219 unsigned Count = 0;
220 for (int i = LiveBundles.find_first(); i >= 0;
221 i = LiveBundles.find_next(i))
222 if (B[i] == NoCand) {
223 B[i] = C;
224 Count++;
225 }
226 return Count;
227 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000228 };
229
Aditya Nandakumarc1fd0dd2013-11-19 23:51:32 +0000230 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000231 /// This vector never shrinks, but grows to the size of the largest register
232 /// class.
233 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
234
Reid Klecknercd4a25d2013-10-08 20:15:11 +0000235 enum LLVM_ENUM_INT_TYPE(unsigned) { NoCand = ~0u };
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000236
237 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
238 /// NoCand which indicates the stack interval.
239 SmallVector<unsigned, 32> BundleCand;
240
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000241public:
242 RAGreedy();
243
244 /// Return the pass name.
245 virtual const char* getPassName() const {
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +0000246 return "Greedy Register Allocator";
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000247 }
248
249 /// RAGreedy analysis usage.
250 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000251 virtual void releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000252 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000253 virtual void enqueue(LiveInterval *LI);
254 virtual LiveInterval *dequeue();
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +0000255 virtual unsigned selectOrSplit(LiveInterval&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000256 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000257
258 /// Perform register allocation.
259 virtual bool runOnMachineFunction(MachineFunction &mf);
260
261 static char ID;
Andrew Trickccef0982010-12-09 18:15:21 +0000262
263private:
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000264 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000265 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000266 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000267
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000268 BlockFrequency calcSpillCost();
269 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000270 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000271 void growRegion(GlobalSplitCandidate &Cand);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000272 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000273 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000274 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000275 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000276 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000277 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
278 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
279 void evictInterference(LiveInterval&, unsigned,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000280 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000281
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000282 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000283 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000284 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000285 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000286 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000287 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +0000288 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000289 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +0000290 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000291 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000292 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000293 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000294 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000295 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000296};
297} // end anonymous namespace
298
299char RAGreedy::ID = 0;
300
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000301#ifndef NDEBUG
302const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000303 "RS_New",
304 "RS_Assign",
305 "RS_Split",
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000306 "RS_Split2",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000307 "RS_Spill",
308 "RS_Done"
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000309};
310#endif
311
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000312// Hysteresis to use when comparing floats.
313// This helps stabilize decisions based on float comparisons.
314const float Hysteresis = 0.98f;
315
316
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000317FunctionPass* llvm::createGreedyRegisterAllocator() {
318 return new RAGreedy();
319}
320
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000321RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000322 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000323 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000324 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
325 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola676c4052011-06-26 22:34:10 +0000326 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Tricke1c034f2012-01-17 06:55:03 +0000327 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000328 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
329 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
330 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
331 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000332 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000333 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
334 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000335}
336
337void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
338 AU.setPreservesCFG();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000339 AU.addRequired<MachineBlockFrequencyInfo>();
340 AU.addPreserved<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000341 AU.addRequired<AliasAnalysis>();
342 AU.addPreserved<AliasAnalysis>();
343 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen12243122012-06-08 23:44:45 +0000344 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000345 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000346 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000347 AU.addRequired<LiveDebugVariables>();
348 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000349 AU.addRequired<LiveStacks>();
350 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000351 AU.addRequired<MachineDominatorTree>();
352 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000353 AU.addRequired<MachineLoopInfo>();
354 AU.addPreserved<MachineLoopInfo>();
355 AU.addRequired<VirtRegMap>();
356 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000357 AU.addRequired<LiveRegMatrix>();
358 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000359 AU.addRequired<EdgeBundles>();
360 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000361 MachineFunctionPass::getAnalysisUsage(AU);
362}
363
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000364
365//===----------------------------------------------------------------------===//
366// LiveRangeEdit delegate methods
367//===----------------------------------------------------------------------===//
368
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000369bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000370 if (VRM->hasPhys(VirtReg)) {
371 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000372 return true;
373 }
374 // Unassigned virtreg is probably in the priority queue.
375 // RegAllocBase will erase it after dequeueing.
376 return false;
377}
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000378
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000379void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000380 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000381 return;
382
383 // Register is assigned, put it back on the queue for reassignment.
384 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000385 Matrix->unassign(LI);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000386 enqueue(&LI);
387}
388
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000389void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen811b9c42011-09-14 17:34:37 +0000390 // Cloning a register we haven't even heard about yet? Just ignore it.
391 if (!ExtraRegInfo.inBounds(Old))
392 return;
393
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000394 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000395 // be split into connected components. The new components are much smaller
396 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000397 // same stage as the parent.
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000398 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000399 ExtraRegInfo.grow(New);
400 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000401}
402
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000403void RAGreedy::releaseMemory() {
404 SpillerInstance.reset(0);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000405 ExtraRegInfo.clear();
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000406 GlobalCand.clear();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000407}
408
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000409void RAGreedy::enqueue(LiveInterval *LI) {
410 // Prioritize live ranges by size, assigning larger ranges first.
411 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000412 const unsigned Size = LI->getSize();
413 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000414 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
415 "Can only enqueue virtual registers");
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000416 unsigned Prio;
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000417
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000418 ExtraRegInfo.grow(Reg);
419 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000420 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000421
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000422 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000423 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +0000424 // everything else has been allocated.
425 Prio = Size;
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000426 } else {
Andrew Trick84852572013-07-25 18:35:14 +0000427 if (ExtraRegInfo[Reg].Stage == RS_Assign && !LI->empty() &&
428 LIS->intervalIsInOneMBB(*LI)) {
429 // Allocate original local ranges in linear instruction order. Since they
430 // are singly defined, this produces optimal coloring in the absence of
431 // global interference and other constraints.
Andrew Trick2d8826a2013-12-11 03:40:15 +0000432 if (!TRI->reverseLocalAssignment())
433 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
434 else {
435 // Allocating bottom up may allow many short LRGs to be assigned first
436 // to one of the cheap registers. This could be much faster for very
437 // large blocks on targets with many physical registers.
438 Prio = Indexes->getZeroIndex().getInstrDistance(LI->beginIndex());
439 }
Andrew Trick84852572013-07-25 18:35:14 +0000440 }
441 else {
442 // Allocate global and split ranges in long->short order. Long ranges that
443 // don't fit should be spilled (or split) ASAP so they don't create
444 // interference. Mark a bit to prioritize global above local ranges.
445 Prio = (1u << 29) + Size;
446 }
447 // Mark a higher bit to prioritize global and local above RS_Split.
448 Prio |= (1u << 31);
Jakob Stoklund Olesenb51f65c2011-02-23 00:56:56 +0000449
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000450 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen74052b02012-12-03 23:23:50 +0000451 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000452 Prio |= (1u << 30);
453 }
Andrew Trickf4b1ee32013-07-25 18:35:22 +0000454 // The virtual register number is a tie breaker for same-sized ranges.
455 // Give lower vreg numbers higher priority to assign them first.
Jakob Stoklund Olesen291007b2012-04-02 22:30:39 +0000456 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000457}
458
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000459LiveInterval *RAGreedy::dequeue() {
460 if (Queue.empty())
461 return 0;
Jakob Stoklund Olesen291007b2012-04-02 22:30:39 +0000462 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000463 Queue.pop();
464 return LI;
465}
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000466
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000467
468//===----------------------------------------------------------------------===//
469// Direct Assignment
470//===----------------------------------------------------------------------===//
471
472/// tryAssign - Try to assign VirtReg to an available register.
473unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
474 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000475 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000476 Order.rewind();
477 unsigned PhysReg;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000478 while ((PhysReg = Order.next()))
479 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000480 break;
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000481 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000482 return PhysReg;
483
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000484 // PhysReg is available, but there may be a better choice.
485
486 // If we missed a simple hint, try to cheaply evict interference from the
487 // preferred register.
488 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000489 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000490 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
Andrew Trick3621b8a2013-11-22 19:07:38 +0000491 EvictionCost MaxCost;
492 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000493 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
494 evictInterference(VirtReg, Hint, NewVRegs);
495 return Hint;
496 }
497 }
498
499 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000500 unsigned Cost = TRI->getCostPerUse(PhysReg);
501
502 // Most registers have 0 additional cost.
503 if (!Cost)
504 return PhysReg;
505
506 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
507 << '\n');
508 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
509 return CheapReg ? CheapReg : PhysReg;
510}
511
512
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000513//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000514// Interference eviction
515//===----------------------------------------------------------------------===//
516
Andrew Trick8bb0a252013-07-25 18:35:19 +0000517unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
518 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
519 unsigned PhysReg;
520 while ((PhysReg = Order.next())) {
521 if (PhysReg == PrevReg)
522 continue;
523
524 MCRegUnitIterator Units(PhysReg, TRI);
525 for (; Units.isValid(); ++Units) {
526 // Instantiate a "subquery", not to be confused with the Queries array.
527 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
528 if (subQ.checkInterference())
529 break;
530 }
531 // If no units have interference, break out with the current PhysReg.
532 if (!Units.isValid())
533 break;
534 }
535 if (PhysReg)
536 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
537 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
538 << '\n');
539 return PhysReg;
540}
541
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000542/// shouldEvict - determine if A should evict the assigned live range B. The
543/// eviction policy defined by this function together with the allocation order
544/// defined by enqueue() decides which registers ultimately end up being split
545/// and spilled.
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000546///
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000547/// Cascade numbers are used to prevent infinite loops if this function is a
548/// cyclic relation.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000549///
550/// @param A The live range to be assigned.
551/// @param IsHint True when A is about to be assigned to its preferred
552/// register.
553/// @param B The live range to be evicted.
554/// @param BreaksHint True when B is already assigned to its preferred register.
555bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
556 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000557 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000558
559 // Be fairly aggressive about following hints as long as the evictee can be
560 // split.
561 if (CanSplit && IsHint && !BreaksHint)
562 return true;
563
Andrew Trick059e8002013-11-22 19:07:42 +0000564 if (A.weight > B.weight) {
565 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
566 return true;
567 }
568 return false;
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000569}
570
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000571/// canEvictInterference - Return true if all interferences between VirtReg and
572/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
573///
574/// @param VirtReg Live range that is about to be assigned.
575/// @param PhysReg Desired register for assignment.
Dmitri Gribenko881929c2012-09-12 16:59:47 +0000576/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000577/// @param MaxCost Only look for cheaper candidates and update with new cost
578/// when returning true.
579/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000580bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000581 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000582 // It is only possible to evict virtual register interference.
583 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
584 return false;
585
Andrew Trick84852572013-07-25 18:35:14 +0000586 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
587
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000588 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
589 // involved in an eviction before. If a cascade number was assigned, deny
590 // evicting anything with the same or a newer cascade number. This prevents
591 // infinite eviction loops.
592 //
593 // This works out so a register without a cascade number is allowed to evict
594 // anything, and it can be evicted by anything.
595 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
596 if (!Cascade)
597 Cascade = NextCascade;
598
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000599 EvictionCost Cost;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000600 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
601 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000602 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000603 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000604 return false;
605
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000606 // Check if any interfering live range is heavier than MaxWeight.
607 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
608 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000609 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
610 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000611 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000612 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000613 return false;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000614 // Once a live range becomes small enough, it is urgent that we find a
615 // register for it. This is indicated by an infinite spill weight. These
616 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen05e22452012-05-30 21:46:58 +0000617 //
618 // Also allow urgent evictions of unspillable ranges from a strictly
619 // larger allocation order.
620 bool Urgent = !VirtReg.isSpillable() &&
621 (Intf->isSpillable() ||
622 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
623 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000624 // Only evict older cascades or live ranges without a cascade.
625 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
626 if (Cascade <= IntfCascade) {
627 if (!Urgent)
628 return false;
629 // We permit breaking cascades for urgent evictions. It should be the
630 // last resort, though, so make it really expensive.
631 Cost.BrokenHints += 10;
632 }
633 // Would this break a satisfied hint?
634 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
635 // Update eviction cost.
636 Cost.BrokenHints += BreaksHint;
637 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
638 // Abort if this would be too expensive.
639 if (!(Cost < MaxCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000640 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000641 if (Urgent)
642 continue;
Andrew Trickc2ab53a2013-11-29 23:49:38 +0000643 // Apply the eviction policy for non-urgent evictions.
644 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
645 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000646 // If !MaxCost.isMax(), then we're just looking for a cheap register.
647 // Evicting another local live range in this case could lead to suboptimal
648 // coloring.
Andrew Trick8bb0a252013-07-25 18:35:19 +0000649 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
650 !canReassign(*Intf, PhysReg)) {
Andrew Trick84852572013-07-25 18:35:14 +0000651 return false;
Andrew Trick8bb0a252013-07-25 18:35:19 +0000652 }
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000653 }
654 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000655 MaxCost = Cost;
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000656 return true;
657}
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000658
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000659/// evictInterference - Evict any interferring registers that prevent VirtReg
660/// from being assigned to Physreg. This assumes that canEvictInterference
661/// returned true.
662void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000663 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000664 // Make sure that VirtReg has a cascade number, and assign that cascade
665 // number to every evicted register. These live ranges than then only be
666 // evicted by a newer cascade, preventing infinite loops.
667 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
668 if (!Cascade)
669 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
670
671 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
672 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000673
674 // Collect all interfering virtregs first.
675 SmallVector<LiveInterval*, 8> Intfs;
676 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
677 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000678 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000679 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
680 Intfs.append(IVR.begin(), IVR.end());
681 }
682
683 // Evict them second. This will invalidate the queries.
684 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
685 LiveInterval *Intf = Intfs[i];
686 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
687 if (!VRM->hasPhys(Intf->reg))
688 continue;
689 Matrix->unassign(*Intf);
690 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
691 VirtReg.isSpillable() < Intf->isSpillable()) &&
692 "Cannot decrease cascade number, illegal eviction");
693 ExtraRegInfo[Intf->reg].Cascade = Cascade;
694 ++NumEvicted;
Mark Laceyf9ea8852013-08-14 23:50:04 +0000695 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000696 }
697}
698
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000699/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +0000700/// @param VirtReg Currently unassigned virtual register.
701/// @param Order Physregs to try.
702/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000703unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
704 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000705 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000706 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000707 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
708
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000709 // Keep track of the cheapest interference seen so far.
Andrew Trick3621b8a2013-11-22 19:07:38 +0000710 EvictionCost BestCost;
711 BestCost.setMax();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000712 unsigned BestPhys = 0;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000713 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000714
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000715 // When we are just looking for a reduced cost per use, don't break any
716 // hints, and only evict smaller spill weights.
717 if (CostPerUseLimit < ~0u) {
718 BestCost.BrokenHints = 0;
719 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000720
721 // Check of any registers in RC are below CostPerUseLimit.
722 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
723 unsigned MinCost = RegClassInfo.getMinCost(RC);
724 if (MinCost >= CostPerUseLimit) {
725 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
726 << ", no cheaper registers to be found.\n");
727 return 0;
728 }
729
730 // It is normal for register classes to have a long tail of registers with
731 // the same cost. We don't need to look at them if they're too expensive.
732 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
733 OrderLimit = RegClassInfo.getLastCostChange(RC);
734 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
735 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000736 }
737
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000738 Order.rewind();
Aditya Nandakumar73f3d332013-12-05 21:18:40 +0000739 while (unsigned PhysReg = Order.next(OrderLimit)) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000740 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
741 continue;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000742 // The first use of a callee-saved register in a function has cost 1.
743 // Don't start using a CSR when the CostPerUseLimit is low.
744 if (CostPerUseLimit == 1)
745 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
746 if (!MRI->isPhysRegUsed(CSR)) {
747 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
748 << PrintReg(CSR, TRI) << '\n');
749 continue;
750 }
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000751
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000752 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000753 continue;
754
755 // Best so far.
756 BestPhys = PhysReg;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000757
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000758 // Stop if the hint can be used.
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000759 if (Order.isHint())
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000760 break;
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000761 }
762
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000763 if (!BestPhys)
764 return 0;
765
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000766 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000767 return BestPhys;
Andrew Trickccef0982010-12-09 18:15:21 +0000768}
769
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000770
771//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000772// Region Splitting
773//===----------------------------------------------------------------------===//
774
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000775/// addSplitConstraints - Fill out the SplitConstraints vector based on the
776/// interference pattern in Physreg and its aliases. Add the constraints to
777/// SpillPlacement and return the static cost of this split in Cost, assuming
778/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000779/// Return false if there are no bundles with positive bias.
780bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000781 BlockFrequency &Cost) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000782 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000783
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000784 // Reset interference dependent info.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000785 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000786 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000787 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
788 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000789 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000790
Jakob Stoklund Olesenb1b76ad2011-02-09 22:50:26 +0000791 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000792 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000793 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
794 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie041f1aa2013-05-15 07:36:59 +0000795 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000796
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000797 if (!Intf.hasInterference())
798 continue;
799
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000800 // Number of spill code instructions to insert.
801 unsigned Ins = 0;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000802
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000803 // Interference for the live-in value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000804 if (BI.LiveIn) {
Jakob Stoklund Olesen89339072011-04-04 15:32:15 +0000805 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000806 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000807 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000808 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000809 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000810 ++Ins;
Jakob Stoklund Olesenf248b202011-02-08 23:02:58 +0000811 }
812
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000813 // Interference for the live-out value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000814 if (BI.LiveOut) {
Jakob Stoklund Olesend93b0e32011-04-05 04:20:29 +0000815 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000816 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000817 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000818 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000819 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000820 ++Ins;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000821 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000822
823 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000824 while (Ins--)
825 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000826 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000827 Cost = StaticCost;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000828
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000829 // Add constraints for use-blocks. Note that these are the only constraints
830 // that may add a positive bias, it is downhill from here.
831 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000832 return SpillPlacer->scanActiveBundles();
833}
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000834
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000835
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000836/// addThroughConstraints - Add constraints and links to SpillPlacer from the
837/// live-through blocks in Blocks.
838void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
839 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000840 const unsigned GroupSize = 8;
841 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000842 unsigned TBS[GroupSize];
843 unsigned B = 0, T = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000844
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000845 for (unsigned i = 0; i != Blocks.size(); ++i) {
846 unsigned Number = Blocks[i];
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000847 Intf.moveToBlock(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000848
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000849 if (!Intf.hasInterference()) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000850 assert(T < GroupSize && "Array overflow");
851 TBS[T] = Number;
852 if (++T == GroupSize) {
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000853 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000854 T = 0;
855 }
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000856 continue;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000857 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000858
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000859 assert(B < GroupSize && "Array overflow");
860 BCS[B].Number = Number;
861
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000862 // Interference for the live-in value.
863 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
864 BCS[B].Entry = SpillPlacement::MustSpill;
865 else
866 BCS[B].Entry = SpillPlacement::PrefSpill;
867
868 // Interference for the live-out value.
869 if (Intf.last() >= SA->getLastSplitPoint(Number))
870 BCS[B].Exit = SpillPlacement::MustSpill;
871 else
872 BCS[B].Exit = SpillPlacement::PrefSpill;
873
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000874 if (++B == GroupSize) {
875 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
876 SpillPlacer->addConstraints(Array);
877 B = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000878 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000879 }
880
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000881 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
882 SpillPlacer->addConstraints(Array);
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000883 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000884}
885
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000886void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000887 // Keep track of through blocks that have not been added to SpillPlacer.
888 BitVector Todo = SA->getThroughBlocks();
889 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
890 unsigned AddedTo = 0;
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000891#ifndef NDEBUG
892 unsigned Visited = 0;
893#endif
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000894
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000895 for (;;) {
896 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000897 // Find new through blocks in the periphery of PrefRegBundles.
898 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
899 unsigned Bundle = NewBundles[i];
900 // Look at all blocks connected to Bundle in the full graph.
901 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
902 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
903 I != E; ++I) {
904 unsigned Block = *I;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000905 if (!Todo.test(Block))
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000906 continue;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000907 Todo.reset(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000908 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000909 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000910#ifndef NDEBUG
911 ++Visited;
912#endif
913 }
914 }
915 // Any new blocks to add?
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +0000916 if (ActiveBlocks.size() == AddedTo)
917 break;
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +0000918
919 // Compute through constraints from the interference, or assume that all
920 // through blocks prefer spilling when forming compact regions.
921 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
922 if (Cand.PhysReg)
923 addThroughConstraints(Cand.Intf, NewBlocks);
924 else
Jakob Stoklund Olesen86954522011-08-03 23:09:38 +0000925 // Provide a strong negative bias on through blocks to prevent unwanted
926 // liveness on loop backedges.
927 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +0000928 AddedTo = ActiveBlocks.size();
929
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000930 // Perhaps iterating can enable more bundles?
931 SpillPlacer->iterate();
932 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000933 DEBUG(dbgs() << ", v=" << Visited);
934}
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000935
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000936/// calcCompactRegion - Compute the set of edge bundles that should be live
937/// when splitting the current live range into compact regions. Compact
938/// regions can be computed without looking at interference. They are the
939/// regions formed by removing all the live-through blocks from the live range.
940///
941/// Returns false if the current live range is already compact, or if the
942/// compact regions would form single block regions anyway.
943bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
944 // Without any through blocks, the live range is already compact.
945 if (!SA->getNumThroughBlocks())
946 return false;
947
948 // Compact regions don't correspond to any physreg.
949 Cand.reset(IntfCache, 0);
950
951 DEBUG(dbgs() << "Compact region bundles");
952
953 // Use the spill placer to determine the live bundles. GrowRegion pretends
954 // that all the through blocks have interference when PhysReg is unset.
955 SpillPlacer->prepare(Cand.LiveBundles);
956
957 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000958 BlockFrequency Cost;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000959 if (!addSplitConstraints(Cand.Intf, Cost)) {
960 DEBUG(dbgs() << ", none.\n");
961 return false;
962 }
963
964 growRegion(Cand);
965 SpillPlacer->finish();
966
967 if (!Cand.LiveBundles.any()) {
968 DEBUG(dbgs() << ", none.\n");
969 return false;
970 }
971
972 DEBUG({
973 for (int i = Cand.LiveBundles.find_first(); i>=0;
974 i = Cand.LiveBundles.find_next(i))
975 dbgs() << " EB#" << i;
976 dbgs() << ".\n";
977 });
978 return true;
979}
980
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000981/// calcSpillCost - Compute how expensive it would be to split the live range in
982/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000983BlockFrequency RAGreedy::calcSpillCost() {
984 BlockFrequency Cost = 0;
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000985 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
986 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
987 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
988 unsigned Number = BI.MBB->getNumber();
989 // We normally only need one spill instruction - a load or a store.
990 Cost += SpillPlacer->getBlockFrequency(Number);
991
992 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3c145052011-08-02 23:04:08 +0000993 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
994 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000995 }
996 return Cost;
997}
998
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000999/// calcGlobalSplitCost - Return the global split cost of following the split
1000/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001001/// interference pattern in SplitConstraints.
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001002///
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001003BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1004 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001005 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001006 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1007 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1008 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001009 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001010 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
1011 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
1012 unsigned Ins = 0;
1013
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001014 if (BI.LiveIn)
1015 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1016 if (BI.LiveOut)
1017 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001018 while (Ins--)
1019 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001020 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001021
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001022 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1023 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001024 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1025 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001026 if (!RegIn && !RegOut)
1027 continue;
1028 if (RegIn && RegOut) {
1029 // We need double spill code if this block has interference.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001030 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001031 if (Cand.Intf.hasInterference()) {
1032 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1033 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1034 }
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001035 continue;
1036 }
1037 // live-in / stack-out or stack-in live-out.
1038 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001039 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001040 return GlobalCost;
1041}
1042
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001043/// splitAroundRegion - Split the current live range around the regions
1044/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001045///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001046/// Before calling this function, GlobalCand and BundleCand must be initialized
1047/// so each bundle is assigned to a valid candidate, or NoCand for the
1048/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1049/// objects must be initialized for the current live range, and intervals
1050/// created for the used candidates.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001051///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001052/// @param LREdit The LiveRangeEdit object handling the current split.
1053/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1054/// must appear in this list.
1055void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1056 ArrayRef<unsigned> UsedCands) {
1057 // These are the intervals created for new global ranges. We may create more
1058 // intervals for local ranges.
1059 const unsigned NumGlobalIntvs = LREdit.size();
1060 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1061 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001062
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001063 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen22f37a12011-08-06 18:20:24 +00001064 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001065 // is all copies.
1066 unsigned Reg = SA->getParent().reg;
1067 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1068
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001069 // First handle all the blocks with uses.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001070 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1071 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1072 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001073 unsigned Number = BI.MBB->getNumber();
1074 unsigned IntvIn = 0, IntvOut = 0;
1075 SlotIndex IntfIn, IntfOut;
1076 if (BI.LiveIn) {
1077 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1078 if (CandIn != NoCand) {
1079 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1080 IntvIn = Cand.IntvIdx;
1081 Cand.Intf.moveToBlock(Number);
1082 IntfIn = Cand.Intf.first();
1083 }
1084 }
1085 if (BI.LiveOut) {
1086 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1087 if (CandOut != NoCand) {
1088 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1089 IntvOut = Cand.IntvIdx;
1090 Cand.Intf.moveToBlock(Number);
1091 IntfOut = Cand.Intf.last();
1092 }
1093 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001094
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001095 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001096 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001097 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001098 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001099 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001100 continue;
1101 }
1102
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001103 if (IntvIn && IntvOut)
1104 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1105 else if (IntvIn)
1106 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesen795da1c2011-07-15 21:47:57 +00001107 else
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001108 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001109 }
1110
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001111 // Handle live-through blocks. The relevant live-through blocks are stored in
1112 // the ActiveBlocks list with each candidate. We need to filter out
1113 // duplicates.
1114 BitVector Todo = SA->getThroughBlocks();
1115 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1116 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1117 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1118 unsigned Number = Blocks[i];
1119 if (!Todo.test(Number))
1120 continue;
1121 Todo.reset(Number);
1122
1123 unsigned IntvIn = 0, IntvOut = 0;
1124 SlotIndex IntfIn, IntfOut;
1125
1126 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1127 if (CandIn != NoCand) {
1128 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1129 IntvIn = Cand.IntvIdx;
1130 Cand.Intf.moveToBlock(Number);
1131 IntfIn = Cand.Intf.first();
1132 }
1133
1134 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1135 if (CandOut != NoCand) {
1136 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1137 IntvOut = Cand.IntvIdx;
1138 Cand.Intf.moveToBlock(Number);
1139 IntfOut = Cand.Intf.last();
1140 }
1141 if (!IntvIn && !IntvOut)
1142 continue;
1143 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1144 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001145 }
1146
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001147 ++NumGlobalSplits;
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001148
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001149 SmallVector<unsigned, 8> IntvMap;
1150 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001151 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001152
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001153 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesen5cc91b22011-05-28 02:32:57 +00001154 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001155
1156 // Sort out the new intervals created by splitting. We get four kinds:
1157 // - Remainder intervals should not be split again.
1158 // - Candidate intervals can be assigned to Cand.PhysReg.
1159 // - Block-local splits are candidates for local splitting.
1160 // - DCE leftovers should go back on the queue.
1161 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001162 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001163
1164 // Ignore old intervals from DCE.
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001165 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001166 continue;
1167
1168 // Remainder interval. Don't try splitting again, spill if it doesn't
1169 // allocate.
1170 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001171 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001172 continue;
1173 }
1174
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001175 // Global intervals. Allow repeated splitting as long as the number of live
1176 // blocks is strictly decreasing.
1177 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001178 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001179 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1180 << " blocks as original.\n");
1181 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001182 setStage(Reg, RS_Split2);
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001183 }
1184 continue;
1185 }
1186
1187 // Other intervals are treated as new. This includes local intervals created
1188 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001189 }
1190
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +00001191 if (VerifyEnabled)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001192 MF->verify(this, "After splitting live range around region");
1193}
1194
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001195unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001196 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001197 unsigned NumCands = 0;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001198 unsigned BestCand = NoCand;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001199 BlockFrequency BestCost;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001200 SmallVector<unsigned, 8> UsedCands;
1201
1202 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +00001203 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001204 if (HasCompact) {
1205 // Yes, keep GlobalCand[0] as the compact region candidate.
1206 NumCands = 1;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001207 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001208 } else {
1209 // No benefit from the compact region, our fallback will be per-block
1210 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001211 BestCost = calcSpillCost();
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001212 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1213 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001214 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001215
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001216 Order.rewind();
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001217 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001218 // Discard bad candidates before we run out of interference cache cursors.
1219 // This will only affect register classes with a lot of registers (>32).
1220 if (NumCands == IntfCache.getMaxCursors()) {
1221 unsigned WorstCount = ~0u;
1222 unsigned Worst = 0;
1223 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001224 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001225 continue;
1226 unsigned Count = GlobalCand[i].LiveBundles.count();
1227 if (Count < WorstCount)
1228 Worst = i, WorstCount = Count;
1229 }
1230 --NumCands;
1231 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen559d4dc2011-11-01 00:02:31 +00001232 if (BestCand == NumCands)
1233 BestCand = Worst;
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001234 }
1235
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001236 if (GlobalCand.size() <= NumCands)
1237 GlobalCand.resize(NumCands+1);
1238 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1239 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001240
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001241 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001242 BlockFrequency Cost;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001243 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001244 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001245 continue;
1246 }
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001247 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1248 MBFI->printBlockFreq(dbgs(), Cost));
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001249 if (Cost >= BestCost) {
1250 DEBUG({
1251 if (BestCand == NoCand)
1252 dbgs() << " worse than no bundles\n";
1253 else
1254 dbgs() << " worse than "
1255 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1256 });
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001257 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001258 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001259 growRegion(Cand);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001260
Jakob Stoklund Olesen36b5d8a2011-04-06 19:13:57 +00001261 SpillPlacer->finish();
1262
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001263 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001264 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001265 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001266 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001267 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001268
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001269 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001270 DEBUG({
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001271 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1272 << " with bundles";
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001273 for (int i = Cand.LiveBundles.find_first(); i>=0;
1274 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001275 dbgs() << " EB#" << i;
1276 dbgs() << ".\n";
1277 });
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001278 if (Cost < BestCost) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001279 BestCand = NumCands;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001280 BestCost = Cost;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001281 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001282 ++NumCands;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001283 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001284
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001285 // No solutions found, fall back to single block splitting.
1286 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001287 return 0;
1288
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001289 // Prepare split editor.
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001290 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001291 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001292
1293 // Assign all edge bundles to the preferred candidate, or NoCand.
1294 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1295
1296 // Assign bundles for the best candidate region.
1297 if (BestCand != NoCand) {
1298 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1299 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1300 UsedCands.push_back(BestCand);
1301 Cand.IntvIdx = SE->openIntv();
1302 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1303 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001304 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001305 }
1306 }
1307
1308 // Assign bundles for the compact region.
1309 if (HasCompact) {
1310 GlobalSplitCandidate &Cand = GlobalCand.front();
1311 assert(!Cand.PhysReg && "Compact region has no physreg");
1312 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1313 UsedCands.push_back(0);
1314 Cand.IntvIdx = SE->openIntv();
1315 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1316 << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001317 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001318 }
1319 }
1320
1321 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001322 return 0;
1323}
1324
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001325
1326//===----------------------------------------------------------------------===//
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001327// Per-Block Splitting
1328//===----------------------------------------------------------------------===//
1329
1330/// tryBlockSplit - Split a global live range around every block with uses. This
1331/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1332/// they don't allocate.
1333unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001334 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001335 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1336 unsigned Reg = VirtReg.reg;
1337 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001338 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001339 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001340 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1341 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1342 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1343 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1344 SE->splitSingleBlock(BI);
1345 }
1346 // No blocks were split.
1347 if (LREdit.empty())
1348 return 0;
1349
1350 // We did split for some blocks.
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001351 SmallVector<unsigned, 8> IntvMap;
1352 SE->finish(&IntvMap);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001353
1354 // Tell LiveDebugVariables about the new ranges.
Mark Laceyf9ea8852013-08-14 23:50:04 +00001355 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001356
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001357 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1358
1359 // Sort out the new intervals created by splitting. The remainder interval
1360 // goes straight to spilling, the new local ranges get to stay RS_New.
1361 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001362 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001363 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1364 setStage(LI, RS_Spill);
1365 }
1366
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001367 if (VerifyEnabled)
1368 MF->verify(this, "After splitting live range around basic blocks");
1369 return 0;
1370}
1371
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001372
1373//===----------------------------------------------------------------------===//
1374// Per-Instruction Splitting
1375//===----------------------------------------------------------------------===//
1376
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001377/// Get the number of allocatable registers that match the constraints of \p Reg
1378/// on \p MI and that are also in \p SuperRC.
1379static unsigned getNumAllocatableRegsForConstraints(
1380 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1381 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1382 const RegisterClassInfo &RCI) {
1383 assert(SuperRC && "Invalid register class");
1384
1385 const TargetRegisterClass *ConstrainedRC =
1386 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1387 /* ExploreBundle */ true);
1388 if (!ConstrainedRC)
1389 return 0;
1390 return RCI.getNumAllocatableRegs(ConstrainedRC);
1391}
1392
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001393/// tryInstructionSplit - Split a live range around individual instructions.
1394/// This is normally not worthwhile since the spiller is doing essentially the
1395/// same thing. However, when the live range is in a constrained register
1396/// class, it may help to insert copies such that parts of the live range can
1397/// be moved to a larger register class.
1398///
1399/// This is similar to spilling to a larger register class.
1400unsigned
1401RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001402 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001403 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001404 // There is no point to this if there are no larger sub-classes.
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001405 if (!RegClassInfo.isProperSubClass(CurRC))
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001406 return 0;
1407
1408 // Always enable split spill mode, since we're effectively spilling to a
1409 // register.
1410 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1411 SE->reset(LREdit, SplitEditor::SM_Size);
1412
1413 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1414 if (Uses.size() <= 1)
1415 return 0;
1416
1417 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1418
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001419 const TargetRegisterClass *SuperRC = TRI->getLargestLegalSuperClass(CurRC);
1420 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1421 // Split around every non-copy instruction if this split will relax
1422 // the constraints on the virtual register.
1423 // Otherwise, splitting just inserts uncoalescable copies that do not help
1424 // the allocation.
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001425 for (unsigned i = 0; i != Uses.size(); ++i) {
1426 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001427 if (MI->isFullCopy() ||
1428 SuperRCNumAllocatableRegs ==
1429 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1430 TRI, RCI)) {
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001431 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1432 continue;
1433 }
1434 SE->openIntv();
1435 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1436 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1437 SE->useIntv(SegStart, SegStop);
1438 }
1439
1440 if (LREdit.empty()) {
1441 DEBUG(dbgs() << "All uses were copies.\n");
1442 return 0;
1443 }
1444
1445 SmallVector<unsigned, 8> IntvMap;
1446 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001447 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001448 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1449
1450 // Assign all new registers to RS_Spill. This was the last chance.
1451 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1452 return 0;
1453}
1454
1455
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001456//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001457// Local Splitting
1458//===----------------------------------------------------------------------===//
1459
1460
1461/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1462/// in order to use PhysReg between two entries in SA->UseSlots.
1463///
1464/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1465///
1466void RAGreedy::calcGapWeights(unsigned PhysReg,
1467 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001468 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1469 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001470 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001471 const unsigned NumGaps = Uses.size()-1;
1472
1473 // Start and end points for the interference check.
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001474 SlotIndex StartIdx =
1475 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1476 SlotIndex StopIdx =
1477 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001478
1479 GapWeight.assign(NumGaps, 0.0f);
1480
1481 // Add interference from each overlapping register.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001482 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1483 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1484 .checkInterference())
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001485 continue;
1486
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001487 // We know that VirtReg is a continuous interval from FirstInstr to
1488 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001489 //
1490 // Interference that overlaps an instruction is counted in both gaps
1491 // surrounding the instruction. The exception is interference before
1492 // StartIdx and after StopIdx.
1493 //
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001494 LiveIntervalUnion::SegmentIter IntI =
1495 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001496 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1497 // Skip the gaps before IntI.
1498 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1499 if (++Gap == NumGaps)
1500 break;
1501 if (Gap == NumGaps)
1502 break;
1503
1504 // Update the gaps covered by IntI.
1505 const float weight = IntI.value()->weight;
1506 for (; Gap != NumGaps; ++Gap) {
1507 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1508 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1509 break;
1510 }
1511 if (Gap == NumGaps)
1512 break;
1513 }
1514 }
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001515
1516 // Add fixed interference.
1517 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001518 const LiveRange &LR = LIS->getRegUnit(*Units);
1519 LiveRange::const_iterator I = LR.find(StartIdx);
1520 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001521
1522 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1523 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1524 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1525 if (++Gap == NumGaps)
1526 break;
1527 if (Gap == NumGaps)
1528 break;
1529
1530 for (; Gap != NumGaps; ++Gap) {
Aaron Ballman04999042013-11-13 00:15:44 +00001531 GapWeight[Gap] = llvm::huge_valf;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001532 if (Uses[Gap+1].getBaseIndex() >= I->end)
1533 break;
1534 }
1535 if (Gap == NumGaps)
1536 break;
1537 }
1538 }
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001539}
1540
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001541/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1542/// basic block.
1543///
1544unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001545 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001546 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1547 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001548
1549 // Note that it is possible to have an interval that is live-in or live-out
1550 // while only covering a single block - A phi-def can use undef values from
1551 // predecessors, and the block could be a single-block loop.
1552 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001553 // that the interval is continuous from FirstInstr to LastInstr. We should
1554 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001555
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001556 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001557 if (Uses.size() <= 2)
1558 return 0;
1559 const unsigned NumGaps = Uses.size()-1;
1560
1561 DEBUG({
1562 dbgs() << "tryLocalSplit: ";
1563 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001564 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001565 dbgs() << '\n';
1566 });
1567
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001568 // If VirtReg is live across any register mask operands, compute a list of
1569 // gaps with register masks.
1570 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001571 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001572 // Get regmask slots for the whole block.
1573 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001574 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001575 // Constrain to VirtReg's live range.
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001576 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1577 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001578 unsigned re = RMS.size();
1579 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001580 // Look for Uses[i] <= RMS <= Uses[i+1].
1581 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1582 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001583 continue;
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001584 // Skip a regmask on the same instruction as the last use. It doesn't
1585 // overlap the live range.
1586 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1587 break;
1588 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001589 RegMaskGaps.push_back(i);
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001590 // Advance ri to the next gap. A regmask on one of the uses counts in
1591 // both gaps.
1592 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1593 ++ri;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001594 }
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001595 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001596 }
1597
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001598 // Since we allow local split results to be split again, there is a risk of
1599 // creating infinite loops. It is tempting to require that the new live
1600 // ranges have less instructions than the original. That would guarantee
1601 // convergence, but it is too strict. A live range with 3 instructions can be
1602 // split 2+3 (including the COPY), and we want to allow that.
1603 //
1604 // Instead we use these rules:
1605 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001606 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001607 // noop split, of course).
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001608 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001609 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001610 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001611 // smaller ranges are marked RS_New.
1612 //
1613 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1614 // excessive splitting and infinite loops.
1615 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001616 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001617
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001618 // Best split candidate.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001619 unsigned BestBefore = NumGaps;
1620 unsigned BestAfter = 0;
1621 float BestDiff = 0;
1622
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001623 const float blockFreq =
1624 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
Michael Gottesman5e985ee2013-12-14 02:37:38 +00001625 (1.0f / MBFI->getEntryFreq());
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001626 SmallVector<float, 8> GapWeight;
1627
1628 Order.rewind();
1629 while (unsigned PhysReg = Order.next()) {
1630 // Keep track of the largest spill weight that would need to be evicted in
1631 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1632 calcGapWeights(PhysReg, GapWeight);
1633
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001634 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001635 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001636 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Aaron Ballman04999042013-11-13 00:15:44 +00001637 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001638
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001639 // Try to find the best sequence of gaps to close.
1640 // The new spill weight must be larger than any gap interference.
1641
1642 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001643 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001644
1645 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1646 // It is the spill weight that needs to be evicted.
1647 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001648
1649 for (;;) {
1650 // Live before/after split?
1651 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1652 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1653
1654 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1655 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1656 << " i=" << MaxGap);
1657
1658 // Stop before the interval gets so big we wouldn't be making progress.
1659 if (!LiveBefore && !LiveAfter) {
1660 DEBUG(dbgs() << " all\n");
1661 break;
1662 }
1663 // Should the interval be extended or shrunk?
1664 bool Shrink = true;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001665
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001666 // How many gaps would the new range have?
1667 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1668
1669 // Legally, without causing looping?
1670 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1671
Aaron Ballman04999042013-11-13 00:15:44 +00001672 if (Legal && MaxGap < llvm::huge_valf) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001673 // Estimate the new spill weight. Each instruction reads or writes the
1674 // register. Conservatively assume there are no read-modify-write
1675 // instructions.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001676 //
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001677 // Try to guess the size of the new interval.
1678 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1679 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1680 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001681 // Would this split be possible to allocate?
1682 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001683 DEBUG(dbgs() << " w=" << EstWeight);
1684 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001685 Shrink = false;
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001686 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001687 if (Diff > BestDiff) {
1688 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001689 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001690 BestBefore = SplitBefore;
1691 BestAfter = SplitAfter;
1692 }
1693 }
1694 }
1695
1696 // Try to shrink.
1697 if (Shrink) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001698 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001699 DEBUG(dbgs() << " shrink\n");
1700 // Recompute the max when necessary.
1701 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1702 MaxGap = GapWeight[SplitBefore];
1703 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1704 MaxGap = std::max(MaxGap, GapWeight[i]);
1705 }
1706 continue;
1707 }
1708 MaxGap = 0;
1709 }
1710
1711 // Try to extend the interval.
1712 if (SplitAfter >= NumGaps) {
1713 DEBUG(dbgs() << " end\n");
1714 break;
1715 }
1716
1717 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001718 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001719 }
1720 }
1721
1722 // Didn't find any candidates?
1723 if (BestBefore == NumGaps)
1724 return 0;
1725
1726 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1727 << '-' << Uses[BestAfter] << ", " << BestDiff
1728 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1729
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001730 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001731 SE->reset(LREdit);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001732
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001733 SE->openIntv();
1734 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1735 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1736 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001737 SmallVector<unsigned, 8> IntvMap;
1738 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001739 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001740
1741 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001742 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001743 // leave the new intervals as RS_New so they can compete.
1744 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1745 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1746 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1747 if (NewGaps >= NumGaps) {
1748 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1749 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001750 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1751 if (IntvMap[i] == 1) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001752 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1753 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001754 }
1755 DEBUG(dbgs() << '\n');
1756 }
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001757 ++NumLocalSplits;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001758
1759 return 0;
1760}
1761
1762//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001763// Live Range Splitting
1764//===----------------------------------------------------------------------===//
1765
1766/// trySplit - Try to split VirtReg or one of its interferences, making it
1767/// assignable.
1768/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1769unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001770 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesend4bb1d42011-08-05 23:50:33 +00001771 // Ranges must be Split2 or less.
1772 if (getStage(VirtReg) >= RS_Spill)
1773 return 0;
1774
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001775 // Local intervals are handled separately.
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001776 if (LIS->intervalIsInOneMBB(VirtReg)) {
1777 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001778 SA->analyze(&VirtReg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001779 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1780 if (PhysReg || !NewVRegs.empty())
1781 return PhysReg;
1782 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001783 }
1784
1785 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001786
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001787 SA->analyze(&VirtReg);
1788
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00001789 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1790 // coalescer. That may cause the range to become allocatable which means that
1791 // tryRegionSplit won't be making progress. This check should be replaced with
1792 // an assertion when the coalescer is fixed.
1793 if (SA->didRepairRange()) {
1794 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001795 Matrix->invalidateVirtRegs();
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00001796 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1797 return PhysReg;
1798 }
1799
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001800 // First try to split around a region spanning multiple blocks. RS_Split2
1801 // ranges already made dubious progress with region splitting, so they go
1802 // straight to single block splitting.
1803 if (getStage(VirtReg) < RS_Split2) {
1804 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1805 if (PhysReg || !NewVRegs.empty())
1806 return PhysReg;
1807 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001808
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001809 // Then isolate blocks.
1810 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001811}
1812
1813
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001814//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001815// Main Entry Point
1816//===----------------------------------------------------------------------===//
1817
1818unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001819 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001820 // First try assigning a free register.
Jakob Stoklund Olesenb8bf3c02011-06-03 20:34:53 +00001821 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001822 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1823 return PhysReg;
Andrew Trickccef0982010-12-09 18:15:21 +00001824
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00001825 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001826 DEBUG(dbgs() << StageName[Stage]
1827 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00001828
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001829 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001830 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001831 // get a second chance until they have been split.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001832 if (Stage != RS_Split)
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001833 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1834 return PhysReg;
Andrew Trickccef0982010-12-09 18:15:21 +00001835
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001836 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1837
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00001838 // The first time we see a live range, don't try to split or spill.
1839 // Wait until the second time, when all smaller ranges have been allocated.
1840 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001841 if (Stage < RS_Split) {
1842 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesen86985072011-03-19 23:02:47 +00001843 DEBUG(dbgs() << "wait for second round\n");
Mark Laceyf9ea8852013-08-14 23:50:04 +00001844 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00001845 return 0;
1846 }
1847
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00001848 // If we couldn't allocate a register from spilling, there is probably some
1849 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001850 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00001851 return ~0u;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001852
Jakob Stoklund Olesen903b6d32010-12-14 00:37:49 +00001853 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001854 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1855 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +00001856 return PhysReg;
1857
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001858 // Finally spill VirtReg itself.
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +00001859 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001860 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen4d6eafa2011-03-10 01:51:42 +00001861 spiller().spill(LRE);
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001862 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001863
Jakob Stoklund Olesen557a82c2011-03-16 22:56:08 +00001864 if (VerifyEnabled)
1865 MF->verify(this, "After spilling");
1866
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001867 // The live virtual register requesting allocation was spilled, so tell
1868 // the caller not to allocate anything during this round.
1869 return 0;
1870}
1871
1872bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1873 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikiec8c29202012-08-22 17:18:53 +00001874 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001875
1876 MF = &mf;
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001877 TRI = MF->getTarget().getRegisterInfo();
1878 TII = MF->getTarget().getInstrInfo();
1879 RCI.runOnMachineFunction(mf);
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00001880 if (VerifyEnabled)
Jakob Stoklund Olesenbf4550e2010-12-18 00:06:56 +00001881 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00001882
Jakob Stoklund Olesen2d2dec92012-06-20 22:52:29 +00001883 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1884 getAnalysis<LiveIntervals>(),
1885 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001886 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +00001887 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +00001888 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenadecb5e2010-12-10 22:54:44 +00001889 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00001890 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001891 Bundles = &getAnalysis<EdgeBundles>();
1892 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001893 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001894
Arnaud A. de Grandmaisonea3ac162013-11-11 19:04:45 +00001895 calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +00001896
Andrew Trick97064962013-07-25 07:26:26 +00001897 DEBUG(LIS->dump());
1898
Jakob Stoklund Olesenf1a60a62011-02-19 00:53:42 +00001899 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramere2a1d892013-06-17 19:00:36 +00001900 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001901 ExtraRegInfo.clear();
1902 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1903 NextCascade = 1;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001904 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001905 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00001906
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001907 allocatePhysRegs();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001908 releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001909 return true;
1910}