blob: 6a623b820024394371b56f3416ccf014c2bfc2c6 [file] [log] [blame]
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001//===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the RAGreedy function pass for register allocation in
11// optimized builds.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000017#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000018#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000019#include "LiveDebugVariables.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000020#include "RegAllocBase.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "Spiller.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000025#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000026#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000027#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000028#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000029#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000030#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramer4eed7562013-06-17 19:00:36 +000032#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000033#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineLoopInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000037#include "llvm/CodeGen/RegAllocRegistry.h"
Stephen Hines36b56882014-04-23 16:57:46 -070038#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000039#include "llvm/CodeGen/VirtRegMap.h"
40#include "llvm/PassAnalysisSupport.h"
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000041#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000042#include "llvm/Support/Debug.h"
43#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000044#include "llvm/Support/Timer.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000045#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000046#include <queue>
47
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000048using namespace llvm;
49
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000050STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000052STATISTIC(NumEvicted, "Number of interferences evicted");
53
Jakob Stoklund Olesen708d06f2011-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
Stephen Hines36b56882014-04-23 16:57:46 -070063static cl::opt<unsigned>
64LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
65 cl::desc("Last chance recoloring max depth"),
66 cl::init(5));
67
68static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
69 "lcr-max-interf", cl::Hidden,
70 cl::desc("Last chance recoloring maximum number of considered"
71 " interference at a time"),
72 cl::init(8));
73
74// FIXME: Find a good default for this flag and remove the flag.
75static cl::opt<unsigned>
76CSRFirstTimeCost("regalloc-csr-first-time-cost",
77 cl::desc("Cost for first time use of callee-saved register."),
78 cl::init(0), cl::Hidden);
79
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000080static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
81 createGreedyRegisterAllocator);
82
83namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000084class RAGreedy : public MachineFunctionPass,
85 public RegAllocBase,
86 private LiveRangeEdit::Delegate {
Stephen Hines36b56882014-04-23 16:57:46 -070087 // Convenient shortcuts.
88 typedef std::priority_queue<std::pair<unsigned, unsigned> > PQueue;
89 typedef SmallPtrSet<LiveInterval *, 4> SmallLISet;
90 typedef SmallSet<unsigned, 16> SmallVirtRegSet;
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000091
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000092 // context
93 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000094
Stephen Hines36b56882014-04-23 16:57:46 -070095 // Shortcuts to some useful interface.
96 const TargetInstrInfo *TII;
97 const TargetRegisterInfo *TRI;
98 RegisterClassInfo RCI;
99
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000100 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000101 SlotIndexes *Indexes;
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000102 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000103 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000104 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000105 EdgeBundles *Bundles;
106 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000107 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000108
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000109 // state
Stephen Hines36b56882014-04-23 16:57:46 -0700110 std::unique_ptr<Spiller> SpillerInstance;
111 PQueue Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000112 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000113
114 // Live ranges pass through a number of stages as we try to allocate them.
115 // Some of the stages may also create new live ranges:
116 //
117 // - Region splitting.
118 // - Per-block splitting.
119 // - Local splitting.
120 // - Spilling.
121 //
122 // Ranges produced by one of the stages skip the previous stages when they are
123 // dequeued. This improves performance because we can skip interference checks
124 // that are unlikely to give any results. It also guarantees that the live
125 // range splitting algorithm terminates, something that is otherwise hard to
126 // ensure.
127 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000128 /// Newly created live range that has never been queued.
129 RS_New,
130
131 /// Only attempt assignment and eviction. Then requeue as RS_Split.
132 RS_Assign,
133
134 /// Attempt live range splitting if assignment is impossible.
135 RS_Split,
136
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000137 /// Attempt more aggressive live range splitting that is guaranteed to make
138 /// progress. This is used for split products that may not be making
139 /// progress.
140 RS_Split2,
141
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000142 /// Live range will be spilled. No more splitting will be attempted.
143 RS_Spill,
144
145 /// There is nothing more we can do to this live range. Abort compilation
146 /// if it can't be assigned.
147 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000148 };
149
Eli Friedmanae43dac2013-09-10 23:18:14 +0000150#ifndef NDEBUG
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000151 static const char *const StageName[];
Eli Friedmanae43dac2013-09-10 23:18:14 +0000152#endif
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000153
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000154 // RegInfo - Keep additional information about each live range.
155 struct RegInfo {
156 LiveRangeStage Stage;
157
158 // Cascade - Eviction loop prevention. See canEvictInterference().
159 unsigned Cascade;
160
161 RegInfo() : Stage(RS_New), Cascade(0) {}
162 };
163
164 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000165
166 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000167 return ExtraRegInfo[VirtReg.reg].Stage;
168 }
169
170 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
171 ExtraRegInfo.resize(MRI->getNumVirtRegs());
172 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000173 }
174
175 template<typename Iterator>
176 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000177 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000178 for (;Begin != End; ++Begin) {
Mark Lacey1feb5852013-08-14 23:50:04 +0000179 unsigned Reg = *Begin;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000180 if (ExtraRegInfo[Reg].Stage == RS_New)
181 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000182 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000183 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000184
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000185 /// Cost of evicting interference.
186 struct EvictionCost {
187 unsigned BrokenHints; ///< Total number of broken hints.
188 float MaxWeight; ///< Maximum spill weight evicted.
189
Stephen Hines36b56882014-04-23 16:57:46 -0700190 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000191
Andrew Trick6ea2b962013-07-25 18:35:14 +0000192 bool isMax() const { return BrokenHints == ~0u; }
193
Stephen Hines36b56882014-04-23 16:57:46 -0700194 void setMax() { BrokenHints = ~0u; }
195
196 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
197
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000198 bool operator<(const EvictionCost &O) const {
Stephen Hines36b56882014-04-23 16:57:46 -0700199 return std::tie(BrokenHints, MaxWeight) <
200 std::tie(O.BrokenHints, O.MaxWeight);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000201 }
202 };
203
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000204 // splitting state.
Stephen Hines36b56882014-04-23 16:57:46 -0700205 std::unique_ptr<SplitAnalysis> SA;
206 std::unique_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000207
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000208 /// Cached per-block interference maps
209 InterferenceCache IntfCache;
210
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000211 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000212 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000213
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000214 /// Global live range splitting candidate info.
215 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000216 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000217 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000218
219 // SplitKit interval index for this candidate.
220 unsigned IntvIdx;
221
222 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000223 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000224
225 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000226 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000227 SmallVector<unsigned, 8> ActiveBlocks;
228
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000229 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000230 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000231 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000232 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000233 LiveBundles.clear();
234 ActiveBlocks.clear();
235 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000236
237 // Set B[i] = C for every live bundle where B[i] was NoCand.
238 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
239 unsigned Count = 0;
240 for (int i = LiveBundles.find_first(); i >= 0;
241 i = LiveBundles.find_next(i))
242 if (B[i] == NoCand) {
243 B[i] = C;
244 Count++;
245 }
246 return Count;
247 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000248 };
249
Stephen Hines36b56882014-04-23 16:57:46 -0700250 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000251 /// This vector never shrinks, but grows to the size of the largest register
252 /// class.
253 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
254
Stephen Hines36b56882014-04-23 16:57:46 -0700255 enum : unsigned { NoCand = ~0u };
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000256
257 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
258 /// NoCand which indicates the stack interval.
259 SmallVector<unsigned, 32> BundleCand;
260
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000261public:
262 RAGreedy();
263
264 /// Return the pass name.
Stephen Hines36b56882014-04-23 16:57:46 -0700265 const char* getPassName() const override {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000266 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000267 }
268
269 /// RAGreedy analysis usage.
Stephen Hines36b56882014-04-23 16:57:46 -0700270 void getAnalysisUsage(AnalysisUsage &AU) const override;
271 void releaseMemory() override;
272 Spiller &spiller() override { return *SpillerInstance; }
273 void enqueue(LiveInterval *LI) override;
274 LiveInterval *dequeue() override;
275 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000276
277 /// Perform register allocation.
Stephen Hines36b56882014-04-23 16:57:46 -0700278 bool runOnMachineFunction(MachineFunction &mf) override;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000279
280 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000281
282private:
Stephen Hines36b56882014-04-23 16:57:46 -0700283 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
284 SmallVirtRegSet &, unsigned = 0);
285
286 bool LRE_CanEraseVirtReg(unsigned) override;
287 void LRE_WillShrinkVirtReg(unsigned) override;
288 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
289 void enqueue(PQueue &CurQueue, LiveInterval *LI);
290 LiveInterval *dequeue(PQueue &CurQueue);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000291
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000292 BlockFrequency calcSpillCost();
293 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000294 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000295 void growRegion(GlobalSplitCandidate &Cand);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000296 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000297 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000298 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000299 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8adae962013-07-25 18:35:19 +0000300 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000301 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
302 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
303 void evictInterference(LiveInterval&, unsigned,
Mark Lacey1feb5852013-08-14 23:50:04 +0000304 SmallVectorImpl<unsigned>&);
Stephen Hines36b56882014-04-23 16:57:46 -0700305 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
306 SmallLISet &RecoloringCandidates,
307 const SmallVirtRegSet &FixedRegisters);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000308
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000309 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000310 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000311 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000312 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000313 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000314 SmallVectorImpl<unsigned>&);
Stephen Hines36b56882014-04-23 16:57:46 -0700315 /// Calculate cost of region splitting.
316 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
317 AllocationOrder &Order,
318 BlockFrequency &BestCost,
319 unsigned &NumCands, bool IgnoreCSR);
320 /// Perform region splitting.
321 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
322 bool HasCompact,
323 SmallVectorImpl<unsigned> &NewVRegs);
324 /// Check other options before using a callee-saved register for the first
325 /// time.
326 unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
327 unsigned PhysReg, unsigned &CostPerUseLimit,
328 SmallVectorImpl<unsigned> &NewVRegs);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000329 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000330 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +0000331 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000332 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000333 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000334 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000335 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000336 SmallVectorImpl<unsigned>&);
Stephen Hines36b56882014-04-23 16:57:46 -0700337 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
338 SmallVectorImpl<unsigned> &,
339 SmallVirtRegSet &, unsigned);
340 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
341 SmallVirtRegSet &, unsigned);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000342};
343} // end anonymous namespace
344
345char RAGreedy::ID = 0;
346
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000347#ifndef NDEBUG
348const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000349 "RS_New",
350 "RS_Assign",
351 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000352 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000353 "RS_Spill",
354 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000355};
356#endif
357
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000358// Hysteresis to use when comparing floats.
359// This helps stabilize decisions based on float comparisons.
Stephen Hines36b56882014-04-23 16:57:46 -0700360const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000361
362
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000363FunctionPass* llvm::createGreedyRegisterAllocator() {
364 return new RAGreedy();
365}
366
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000367RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000368 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000369 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000370 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
371 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000372 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000373 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000374 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
375 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
376 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
377 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000378 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000379 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
380 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000381}
382
383void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
384 AU.setPreservesCFG();
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000385 AU.addRequired<MachineBlockFrequencyInfo>();
386 AU.addPreserved<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000387 AU.addRequired<AliasAnalysis>();
388 AU.addPreserved<AliasAnalysis>();
389 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000390 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000391 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000392 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000393 AU.addRequired<LiveDebugVariables>();
394 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000395 AU.addRequired<LiveStacks>();
396 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000397 AU.addRequired<MachineDominatorTree>();
398 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000399 AU.addRequired<MachineLoopInfo>();
400 AU.addPreserved<MachineLoopInfo>();
401 AU.addRequired<VirtRegMap>();
402 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000403 AU.addRequired<LiveRegMatrix>();
404 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000405 AU.addRequired<EdgeBundles>();
406 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000407 MachineFunctionPass::getAnalysisUsage(AU);
408}
409
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000410
411//===----------------------------------------------------------------------===//
412// LiveRangeEdit delegate methods
413//===----------------------------------------------------------------------===//
414
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000415bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000416 if (VRM->hasPhys(VirtReg)) {
417 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000418 return true;
419 }
420 // Unassigned virtreg is probably in the priority queue.
421 // RegAllocBase will erase it after dequeueing.
422 return false;
423}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000424
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000425void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000426 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000427 return;
428
429 // Register is assigned, put it back on the queue for reassignment.
430 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000431 Matrix->unassign(LI);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000432 enqueue(&LI);
433}
434
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000435void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000436 // Cloning a register we haven't even heard about yet? Just ignore it.
437 if (!ExtraRegInfo.inBounds(Old))
438 return;
439
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000440 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000441 // be split into connected components. The new components are much smaller
442 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000443 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000444 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000445 ExtraRegInfo.grow(New);
446 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000447}
448
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000449void RAGreedy::releaseMemory() {
450 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000451 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000452 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000453}
454
Stephen Hines36b56882014-04-23 16:57:46 -0700455void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
456
457void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000458 // Prioritize live ranges by size, assigning larger ranges first.
459 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000460 const unsigned Size = LI->getSize();
461 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000462 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
463 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000464 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000465
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000466 ExtraRegInfo.grow(Reg);
467 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000468 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000469
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000470 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000471 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000472 // everything else has been allocated.
473 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000474 } else {
Stephen Hines36b56882014-04-23 16:57:46 -0700475 // Giant live ranges fall back to the global assignment heuristic, which
476 // prevents excessive spilling in pathological cases.
477 bool ReverseLocal = TRI->reverseLocalAssignment();
478 bool ForceGlobal = !ReverseLocal && TRI->mayOverrideLocalAssignment() &&
479 (Size / SlotIndex::InstrDist) > (2 * MRI->getRegClass(Reg)->getNumRegs());
480
481 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
Andrew Trick6ea2b962013-07-25 18:35:14 +0000482 LIS->intervalIsInOneMBB(*LI)) {
483 // Allocate original local ranges in linear instruction order. Since they
484 // are singly defined, this produces optimal coloring in the absence of
485 // global interference and other constraints.
Stephen Hines36b56882014-04-23 16:57:46 -0700486 if (!ReverseLocal)
487 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
488 else {
489 // Allocating bottom up may allow many short LRGs to be assigned first
490 // to one of the cheap registers. This could be much faster for very
491 // large blocks on targets with many physical registers.
492 Prio = Indexes->getZeroIndex().getInstrDistance(LI->beginIndex());
493 }
Andrew Trick6ea2b962013-07-25 18:35:14 +0000494 }
495 else {
496 // Allocate global and split ranges in long->short order. Long ranges that
497 // don't fit should be spilled (or split) ASAP so they don't create
498 // interference. Mark a bit to prioritize global above local ranges.
499 Prio = (1u << 29) + Size;
500 }
501 // Mark a higher bit to prioritize global and local above RS_Split.
502 Prio |= (1u << 31);
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000503
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000504 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesenfc637442012-12-03 23:23:50 +0000505 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000506 Prio |= (1u << 30);
507 }
Andrew Trickbef4c3e2013-07-25 18:35:22 +0000508 // The virtual register number is a tie breaker for same-sized ranges.
509 // Give lower vreg numbers higher priority to assign them first.
Stephen Hines36b56882014-04-23 16:57:46 -0700510 CurQueue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000511}
512
Stephen Hines36b56882014-04-23 16:57:46 -0700513LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
514
515LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
516 if (CurQueue.empty())
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000517 return 0;
Stephen Hines36b56882014-04-23 16:57:46 -0700518 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
519 CurQueue.pop();
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000520 return LI;
521}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000522
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000523
524//===----------------------------------------------------------------------===//
525// Direct Assignment
526//===----------------------------------------------------------------------===//
527
528/// tryAssign - Try to assign VirtReg to an available register.
529unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
530 AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +0000531 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000532 Order.rewind();
533 unsigned PhysReg;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000534 while ((PhysReg = Order.next()))
535 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000536 break;
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000537 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000538 return PhysReg;
539
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000540 // PhysReg is available, but there may be a better choice.
541
542 // If we missed a simple hint, try to cheaply evict interference from the
543 // preferred register.
544 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000545 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000546 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
Stephen Hines36b56882014-04-23 16:57:46 -0700547 EvictionCost MaxCost;
548 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000549 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
550 evictInterference(VirtReg, Hint, NewVRegs);
551 return Hint;
552 }
553 }
554
555 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000556 unsigned Cost = TRI->getCostPerUse(PhysReg);
557
558 // Most registers have 0 additional cost.
559 if (!Cost)
560 return PhysReg;
561
562 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
563 << '\n');
564 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
565 return CheapReg ? CheapReg : PhysReg;
566}
567
568
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000569//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000570// Interference eviction
571//===----------------------------------------------------------------------===//
572
Andrew Trick8adae962013-07-25 18:35:19 +0000573unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
574 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
575 unsigned PhysReg;
576 while ((PhysReg = Order.next())) {
577 if (PhysReg == PrevReg)
578 continue;
579
580 MCRegUnitIterator Units(PhysReg, TRI);
581 for (; Units.isValid(); ++Units) {
582 // Instantiate a "subquery", not to be confused with the Queries array.
583 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
584 if (subQ.checkInterference())
585 break;
586 }
587 // If no units have interference, break out with the current PhysReg.
588 if (!Units.isValid())
589 break;
590 }
591 if (PhysReg)
592 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
593 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
594 << '\n');
595 return PhysReg;
596}
597
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000598/// shouldEvict - determine if A should evict the assigned live range B. The
599/// eviction policy defined by this function together with the allocation order
600/// defined by enqueue() decides which registers ultimately end up being split
601/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000602///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000603/// Cascade numbers are used to prevent infinite loops if this function is a
604/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000605///
606/// @param A The live range to be assigned.
607/// @param IsHint True when A is about to be assigned to its preferred
608/// register.
609/// @param B The live range to be evicted.
610/// @param BreaksHint True when B is already assigned to its preferred register.
611bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
612 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000613 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000614
615 // Be fairly aggressive about following hints as long as the evictee can be
616 // split.
617 if (CanSplit && IsHint && !BreaksHint)
618 return true;
619
Stephen Hines36b56882014-04-23 16:57:46 -0700620 if (A.weight > B.weight) {
621 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
622 return true;
623 }
624 return false;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000625}
626
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000627/// canEvictInterference - Return true if all interferences between VirtReg and
Stephen Hines36b56882014-04-23 16:57:46 -0700628/// PhysReg can be evicted.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000629///
630/// @param VirtReg Live range that is about to be assigned.
631/// @param PhysReg Desired register for assignment.
Dmitri Gribenko67c89782012-09-12 16:59:47 +0000632/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000633/// @param MaxCost Only look for cheaper candidates and update with new cost
634/// when returning true.
635/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000636bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000637 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000638 // It is only possible to evict virtual register interference.
639 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
640 return false;
641
Andrew Trick6ea2b962013-07-25 18:35:14 +0000642 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
643
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000644 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
645 // involved in an eviction before. If a cascade number was assigned, deny
646 // evicting anything with the same or a newer cascade number. This prevents
647 // infinite eviction loops.
648 //
649 // This works out so a register without a cascade number is allowed to evict
650 // anything, and it can be evicted by anything.
651 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
652 if (!Cascade)
653 Cascade = NextCascade;
654
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000655 EvictionCost Cost;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000656 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
657 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000658 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000659 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000660 return false;
661
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000662 // Check if any interfering live range is heavier than MaxWeight.
663 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
664 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000665 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
666 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000667 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000668 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000669 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000670 // Once a live range becomes small enough, it is urgent that we find a
671 // register for it. This is indicated by an infinite spill weight. These
672 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000673 //
674 // Also allow urgent evictions of unspillable ranges from a strictly
675 // larger allocation order.
676 bool Urgent = !VirtReg.isSpillable() &&
677 (Intf->isSpillable() ||
678 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
679 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000680 // Only evict older cascades or live ranges without a cascade.
681 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
682 if (Cascade <= IntfCascade) {
683 if (!Urgent)
684 return false;
685 // We permit breaking cascades for urgent evictions. It should be the
686 // last resort, though, so make it really expensive.
687 Cost.BrokenHints += 10;
688 }
689 // Would this break a satisfied hint?
690 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
691 // Update eviction cost.
692 Cost.BrokenHints += BreaksHint;
693 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
694 // Abort if this would be too expensive.
695 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000696 return false;
Andrew Trick6ea2b962013-07-25 18:35:14 +0000697 if (Urgent)
698 continue;
Stephen Hines36b56882014-04-23 16:57:46 -0700699 // Apply the eviction policy for non-urgent evictions.
700 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
701 return false;
Andrew Trick6ea2b962013-07-25 18:35:14 +0000702 // If !MaxCost.isMax(), then we're just looking for a cheap register.
703 // Evicting another local live range in this case could lead to suboptimal
704 // coloring.
Andrew Trick8adae962013-07-25 18:35:19 +0000705 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
706 !canReassign(*Intf, PhysReg)) {
Andrew Trick6ea2b962013-07-25 18:35:14 +0000707 return false;
Andrew Trick8adae962013-07-25 18:35:19 +0000708 }
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000709 }
710 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000711 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000712 return true;
713}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000714
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000715/// evictInterference - Evict any interferring registers that prevent VirtReg
716/// from being assigned to Physreg. This assumes that canEvictInterference
717/// returned true.
718void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Lacey1feb5852013-08-14 23:50:04 +0000719 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000720 // Make sure that VirtReg has a cascade number, and assign that cascade
721 // number to every evicted register. These live ranges than then only be
722 // evicted by a newer cascade, preventing infinite loops.
723 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
724 if (!Cascade)
725 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
726
727 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
728 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000729
730 // Collect all interfering virtregs first.
731 SmallVector<LiveInterval*, 8> Intfs;
732 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
733 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000734 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000735 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
736 Intfs.append(IVR.begin(), IVR.end());
737 }
738
739 // Evict them second. This will invalidate the queries.
740 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
741 LiveInterval *Intf = Intfs[i];
742 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
743 if (!VRM->hasPhys(Intf->reg))
744 continue;
745 Matrix->unassign(*Intf);
746 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
747 VirtReg.isSpillable() < Intf->isSpillable()) &&
748 "Cannot decrease cascade number, illegal eviction");
749 ExtraRegInfo[Intf->reg].Cascade = Cascade;
750 ++NumEvicted;
Mark Lacey1feb5852013-08-14 23:50:04 +0000751 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000752 }
753}
754
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000755/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000756/// @param VirtReg Currently unassigned virtual register.
757/// @param Order Physregs to try.
758/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000759unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
760 AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +0000761 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000762 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000763 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
764
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000765 // Keep track of the cheapest interference seen so far.
Stephen Hines36b56882014-04-23 16:57:46 -0700766 EvictionCost BestCost;
767 BestCost.setMax();
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000768 unsigned BestPhys = 0;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000769 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000770
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000771 // When we are just looking for a reduced cost per use, don't break any
772 // hints, and only evict smaller spill weights.
773 if (CostPerUseLimit < ~0u) {
774 BestCost.BrokenHints = 0;
775 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000776
777 // Check of any registers in RC are below CostPerUseLimit.
778 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
779 unsigned MinCost = RegClassInfo.getMinCost(RC);
780 if (MinCost >= CostPerUseLimit) {
781 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
782 << ", no cheaper registers to be found.\n");
783 return 0;
784 }
785
786 // It is normal for register classes to have a long tail of registers with
787 // the same cost. We don't need to look at them if they're too expensive.
788 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
789 OrderLimit = RegClassInfo.getLastCostChange(RC);
790 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
791 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000792 }
793
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000794 Order.rewind();
Stephen Hines36b56882014-04-23 16:57:46 -0700795 while (unsigned PhysReg = Order.next(OrderLimit)) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000796 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
797 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000798 // The first use of a callee-saved register in a function has cost 1.
799 // Don't start using a CSR when the CostPerUseLimit is low.
800 if (CostPerUseLimit == 1)
801 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
802 if (!MRI->isPhysRegUsed(CSR)) {
803 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
804 << PrintReg(CSR, TRI) << '\n');
805 continue;
806 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000807
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000808 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000809 continue;
810
811 // Best so far.
812 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000813
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000814 // Stop if the hint can be used.
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000815 if (Order.isHint())
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000816 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000817 }
818
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000819 if (!BestPhys)
820 return 0;
821
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000822 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000823 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000824}
825
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000826
827//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000828// Region Splitting
829//===----------------------------------------------------------------------===//
830
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000831/// addSplitConstraints - Fill out the SplitConstraints vector based on the
832/// interference pattern in Physreg and its aliases. Add the constraints to
833/// SpillPlacement and return the static cost of this split in Cost, assuming
834/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000835/// Return false if there are no bundles with positive bias.
836bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000837 BlockFrequency &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000838 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000839
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000840 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000841 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000842 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000843 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
844 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000845 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000846
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000847 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000848 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000849 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
850 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie453f4f02013-05-15 07:36:59 +0000851 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000852
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000853 if (!Intf.hasInterference())
854 continue;
855
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000856 // Number of spill code instructions to insert.
857 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000858
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000859 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000860 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000861 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000862 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000863 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000864 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000865 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000866 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000867 }
868
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000869 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000870 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000871 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000872 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000873 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000874 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000875 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000876 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000877 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000878
879 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000880 while (Ins--)
881 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000882 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000883 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000884
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000885 // Add constraints for use-blocks. Note that these are the only constraints
886 // that may add a positive bias, it is downhill from here.
887 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000888 return SpillPlacer->scanActiveBundles();
889}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000890
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000891
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000892/// addThroughConstraints - Add constraints and links to SpillPlacer from the
893/// live-through blocks in Blocks.
894void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
895 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000896 const unsigned GroupSize = 8;
897 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000898 unsigned TBS[GroupSize];
899 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000900
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000901 for (unsigned i = 0; i != Blocks.size(); ++i) {
902 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000903 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000904
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000905 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000906 assert(T < GroupSize && "Array overflow");
907 TBS[T] = Number;
908 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000909 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000910 T = 0;
911 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000912 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000913 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000914
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000915 assert(B < GroupSize && "Array overflow");
916 BCS[B].Number = Number;
917
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000918 // Interference for the live-in value.
919 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
920 BCS[B].Entry = SpillPlacement::MustSpill;
921 else
922 BCS[B].Entry = SpillPlacement::PrefSpill;
923
924 // Interference for the live-out value.
925 if (Intf.last() >= SA->getLastSplitPoint(Number))
926 BCS[B].Exit = SpillPlacement::MustSpill;
927 else
928 BCS[B].Exit = SpillPlacement::PrefSpill;
929
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000930 if (++B == GroupSize) {
931 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
932 SpillPlacer->addConstraints(Array);
933 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000934 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000935 }
936
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000937 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
938 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000939 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000940}
941
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000942void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000943 // Keep track of through blocks that have not been added to SpillPlacer.
944 BitVector Todo = SA->getThroughBlocks();
945 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
946 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000947#ifndef NDEBUG
948 unsigned Visited = 0;
949#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000950
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000951 for (;;) {
952 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000953 // Find new through blocks in the periphery of PrefRegBundles.
954 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
955 unsigned Bundle = NewBundles[i];
956 // Look at all blocks connected to Bundle in the full graph.
957 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
958 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
959 I != E; ++I) {
960 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000961 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000962 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000963 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000964 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000965 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000966#ifndef NDEBUG
967 ++Visited;
968#endif
969 }
970 }
971 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000972 if (ActiveBlocks.size() == AddedTo)
973 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000974
975 // Compute through constraints from the interference, or assume that all
976 // through blocks prefer spilling when forming compact regions.
977 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
978 if (Cand.PhysReg)
979 addThroughConstraints(Cand.Intf, NewBlocks);
980 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000981 // Provide a strong negative bias on through blocks to prevent unwanted
982 // liveness on loop backedges.
983 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000984 AddedTo = ActiveBlocks.size();
985
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000986 // Perhaps iterating can enable more bundles?
987 SpillPlacer->iterate();
988 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000989 DEBUG(dbgs() << ", v=" << Visited);
990}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000991
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000992/// calcCompactRegion - Compute the set of edge bundles that should be live
993/// when splitting the current live range into compact regions. Compact
994/// regions can be computed without looking at interference. They are the
995/// regions formed by removing all the live-through blocks from the live range.
996///
997/// Returns false if the current live range is already compact, or if the
998/// compact regions would form single block regions anyway.
999bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1000 // Without any through blocks, the live range is already compact.
1001 if (!SA->getNumThroughBlocks())
1002 return false;
1003
1004 // Compact regions don't correspond to any physreg.
1005 Cand.reset(IntfCache, 0);
1006
1007 DEBUG(dbgs() << "Compact region bundles");
1008
1009 // Use the spill placer to determine the live bundles. GrowRegion pretends
1010 // that all the through blocks have interference when PhysReg is unset.
1011 SpillPlacer->prepare(Cand.LiveBundles);
1012
1013 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001014 BlockFrequency Cost;
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +00001015 if (!addSplitConstraints(Cand.Intf, Cost)) {
1016 DEBUG(dbgs() << ", none.\n");
1017 return false;
1018 }
1019
1020 growRegion(Cand);
1021 SpillPlacer->finish();
1022
1023 if (!Cand.LiveBundles.any()) {
1024 DEBUG(dbgs() << ", none.\n");
1025 return false;
1026 }
1027
1028 DEBUG({
1029 for (int i = Cand.LiveBundles.find_first(); i>=0;
1030 i = Cand.LiveBundles.find_next(i))
1031 dbgs() << " EB#" << i;
1032 dbgs() << ".\n";
1033 });
1034 return true;
1035}
1036
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001037/// calcSpillCost - Compute how expensive it would be to split the live range in
1038/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001039BlockFrequency RAGreedy::calcSpillCost() {
1040 BlockFrequency Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001041 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1042 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1043 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1044 unsigned Number = BI.MBB->getNumber();
1045 // We normally only need one spill instruction - a load or a store.
1046 Cost += SpillPlacer->getBlockFrequency(Number);
1047
1048 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +00001049 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1050 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001051 }
1052 return Cost;
1053}
1054
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001055/// calcGlobalSplitCost - Return the global split cost of following the split
1056/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001057/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001058///
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001059BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1060 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001061 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001062 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1063 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1064 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001065 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001066 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
1067 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
1068 unsigned Ins = 0;
1069
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001070 if (BI.LiveIn)
1071 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1072 if (BI.LiveOut)
1073 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001074 while (Ins--)
1075 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001076 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001077
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001078 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1079 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001080 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1081 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +00001082 if (!RegIn && !RegOut)
1083 continue;
1084 if (RegIn && RegOut) {
1085 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001086 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001087 if (Cand.Intf.hasInterference()) {
1088 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1089 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1090 }
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +00001091 continue;
1092 }
1093 // live-in / stack-out or stack-in live-out.
1094 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001095 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001096 return GlobalCost;
1097}
1098
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001099/// splitAroundRegion - Split the current live range around the regions
1100/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001101///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001102/// Before calling this function, GlobalCand and BundleCand must be initialized
1103/// so each bundle is assigned to a valid candidate, or NoCand for the
1104/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1105/// objects must be initialized for the current live range, and intervals
1106/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001107///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001108/// @param LREdit The LiveRangeEdit object handling the current split.
1109/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1110/// must appear in this list.
1111void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1112 ArrayRef<unsigned> UsedCands) {
1113 // These are the intervals created for new global ranges. We may create more
1114 // intervals for local ranges.
1115 const unsigned NumGlobalIntvs = LREdit.size();
1116 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1117 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001118
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001119 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +00001120 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001121 // is all copies.
1122 unsigned Reg = SA->getParent().reg;
1123 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1124
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001125 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001126 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1127 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1128 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001129 unsigned Number = BI.MBB->getNumber();
1130 unsigned IntvIn = 0, IntvOut = 0;
1131 SlotIndex IntfIn, IntfOut;
1132 if (BI.LiveIn) {
1133 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1134 if (CandIn != NoCand) {
1135 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1136 IntvIn = Cand.IntvIdx;
1137 Cand.Intf.moveToBlock(Number);
1138 IntfIn = Cand.Intf.first();
1139 }
1140 }
1141 if (BI.LiveOut) {
1142 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1143 if (CandOut != NoCand) {
1144 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1145 IntvOut = Cand.IntvIdx;
1146 Cand.Intf.moveToBlock(Number);
1147 IntfOut = Cand.Intf.last();
1148 }
1149 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001150
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001151 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001152 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001153 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001154 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001155 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001156 continue;
1157 }
1158
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001159 if (IntvIn && IntvOut)
1160 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1161 else if (IntvIn)
1162 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001163 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001164 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001165 }
1166
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001167 // Handle live-through blocks. The relevant live-through blocks are stored in
1168 // the ActiveBlocks list with each candidate. We need to filter out
1169 // duplicates.
1170 BitVector Todo = SA->getThroughBlocks();
1171 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1172 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1173 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1174 unsigned Number = Blocks[i];
1175 if (!Todo.test(Number))
1176 continue;
1177 Todo.reset(Number);
1178
1179 unsigned IntvIn = 0, IntvOut = 0;
1180 SlotIndex IntfIn, IntfOut;
1181
1182 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1183 if (CandIn != NoCand) {
1184 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1185 IntvIn = Cand.IntvIdx;
1186 Cand.Intf.moveToBlock(Number);
1187 IntfIn = Cand.Intf.first();
1188 }
1189
1190 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1191 if (CandOut != NoCand) {
1192 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1193 IntvOut = Cand.IntvIdx;
1194 Cand.Intf.moveToBlock(Number);
1195 IntfOut = Cand.Intf.last();
1196 }
1197 if (!IntvIn && !IntvOut)
1198 continue;
1199 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1200 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001201 }
1202
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001203 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001204
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001205 SmallVector<unsigned, 8> IntvMap;
1206 SE->finish(&IntvMap);
Mark Lacey1feb5852013-08-14 23:50:04 +00001207 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001208
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001209 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001210 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001211
1212 // Sort out the new intervals created by splitting. We get four kinds:
1213 // - Remainder intervals should not be split again.
1214 // - Candidate intervals can be assigned to Cand.PhysReg.
1215 // - Block-local splits are candidates for local splitting.
1216 // - DCE leftovers should go back on the queue.
1217 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Lacey1feb5852013-08-14 23:50:04 +00001218 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001219
1220 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001221 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001222 continue;
1223
1224 // Remainder interval. Don't try splitting again, spill if it doesn't
1225 // allocate.
1226 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001227 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001228 continue;
1229 }
1230
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001231 // Global intervals. Allow repeated splitting as long as the number of live
1232 // blocks is strictly decreasing.
1233 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001234 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001235 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1236 << " blocks as original.\n");
1237 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001238 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001239 }
1240 continue;
1241 }
1242
1243 // Other intervals are treated as new. This includes local intervals created
1244 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001245 }
1246
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001247 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001248 MF->verify(this, "After splitting live range around region");
1249}
1250
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001251unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001252 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001253 unsigned NumCands = 0;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001254 BlockFrequency BestCost;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001255
1256 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001257 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001258 if (HasCompact) {
1259 // Yes, keep GlobalCand[0] as the compact region candidate.
1260 NumCands = 1;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001261 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001262 } else {
1263 // No benefit from the compact region, our fallback will be per-block
1264 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001265 BestCost = calcSpillCost();
Stephen Hines36b56882014-04-23 16:57:46 -07001266 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1267 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001268 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001269
Stephen Hines36b56882014-04-23 16:57:46 -07001270 unsigned BestCand =
1271 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1272 false/*IgnoreCSR*/);
1273
1274 // No solutions found, fall back to single block splitting.
1275 if (!HasCompact && BestCand == NoCand)
1276 return 0;
1277
1278 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1279}
1280
1281unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1282 AllocationOrder &Order,
1283 BlockFrequency &BestCost,
1284 unsigned &NumCands,
1285 bool IgnoreCSR) {
1286 unsigned BestCand = NoCand;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001287 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001288 while (unsigned PhysReg = Order.next()) {
Stephen Hines36b56882014-04-23 16:57:46 -07001289 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
1290 if (IgnoreCSR && !MRI->isPhysRegUsed(CSR))
1291 continue;
1292
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001293 // Discard bad candidates before we run out of interference cache cursors.
1294 // This will only affect register classes with a lot of registers (>32).
1295 if (NumCands == IntfCache.getMaxCursors()) {
1296 unsigned WorstCount = ~0u;
1297 unsigned Worst = 0;
1298 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001299 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001300 continue;
1301 unsigned Count = GlobalCand[i].LiveBundles.count();
1302 if (Count < WorstCount)
1303 Worst = i, WorstCount = Count;
1304 }
1305 --NumCands;
1306 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001307 if (BestCand == NumCands)
1308 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001309 }
1310
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001311 if (GlobalCand.size() <= NumCands)
1312 GlobalCand.resize(NumCands+1);
1313 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1314 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001315
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001316 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001317 BlockFrequency Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001318 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001319 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001320 continue;
1321 }
Stephen Hines36b56882014-04-23 16:57:46 -07001322 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1323 MBFI->printBlockFreq(dbgs(), Cost));
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001324 if (Cost >= BestCost) {
1325 DEBUG({
1326 if (BestCand == NoCand)
1327 dbgs() << " worse than no bundles\n";
1328 else
1329 dbgs() << " worse than "
1330 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1331 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001332 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001333 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001334 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001335
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001336 SpillPlacer->finish();
1337
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001338 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001339 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001340 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001341 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001342 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001343
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001344 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001345 DEBUG({
Stephen Hines36b56882014-04-23 16:57:46 -07001346 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1347 << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001348 for (int i = Cand.LiveBundles.find_first(); i>=0;
1349 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001350 dbgs() << " EB#" << i;
1351 dbgs() << ".\n";
1352 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001353 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001354 BestCand = NumCands;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001355 BestCost = Cost;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001356 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001357 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001358 }
Stephen Hines36b56882014-04-23 16:57:46 -07001359 return BestCand;
1360}
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001361
Stephen Hines36b56882014-04-23 16:57:46 -07001362unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1363 bool HasCompact,
1364 SmallVectorImpl<unsigned> &NewVRegs) {
1365 SmallVector<unsigned, 8> UsedCands;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001366 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001367 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001368 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001369
1370 // Assign all edge bundles to the preferred candidate, or NoCand.
1371 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1372
1373 // Assign bundles for the best candidate region.
1374 if (BestCand != NoCand) {
1375 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1376 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1377 UsedCands.push_back(BestCand);
1378 Cand.IntvIdx = SE->openIntv();
1379 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1380 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001381 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001382 }
1383 }
1384
1385 // Assign bundles for the compact region.
1386 if (HasCompact) {
1387 GlobalSplitCandidate &Cand = GlobalCand.front();
1388 assert(!Cand.PhysReg && "Compact region has no physreg");
1389 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1390 UsedCands.push_back(0);
1391 Cand.IntvIdx = SE->openIntv();
1392 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1393 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001394 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001395 }
1396 }
1397
1398 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001399 return 0;
1400}
1401
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001402
1403//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001404// Per-Block Splitting
1405//===----------------------------------------------------------------------===//
1406
1407/// tryBlockSplit - Split a global live range around every block with uses. This
1408/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1409/// they don't allocate.
1410unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001411 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001412 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1413 unsigned Reg = VirtReg.reg;
1414 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001415 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001416 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001417 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1418 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1419 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1420 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1421 SE->splitSingleBlock(BI);
1422 }
1423 // No blocks were split.
1424 if (LREdit.empty())
1425 return 0;
1426
1427 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001428 SmallVector<unsigned, 8> IntvMap;
1429 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001430
1431 // Tell LiveDebugVariables about the new ranges.
Mark Lacey1feb5852013-08-14 23:50:04 +00001432 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001433
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001434 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1435
1436 // Sort out the new intervals created by splitting. The remainder interval
1437 // goes straight to spilling, the new local ranges get to stay RS_New.
1438 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Lacey1feb5852013-08-14 23:50:04 +00001439 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001440 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1441 setStage(LI, RS_Spill);
1442 }
1443
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001444 if (VerifyEnabled)
1445 MF->verify(this, "After splitting live range around basic blocks");
1446 return 0;
1447}
1448
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001449
1450//===----------------------------------------------------------------------===//
1451// Per-Instruction Splitting
1452//===----------------------------------------------------------------------===//
1453
Stephen Hines36b56882014-04-23 16:57:46 -07001454/// Get the number of allocatable registers that match the constraints of \p Reg
1455/// on \p MI and that are also in \p SuperRC.
1456static unsigned getNumAllocatableRegsForConstraints(
1457 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1458 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1459 const RegisterClassInfo &RCI) {
1460 assert(SuperRC && "Invalid register class");
1461
1462 const TargetRegisterClass *ConstrainedRC =
1463 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1464 /* ExploreBundle */ true);
1465 if (!ConstrainedRC)
1466 return 0;
1467 return RCI.getNumAllocatableRegs(ConstrainedRC);
1468}
1469
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001470/// tryInstructionSplit - Split a live range around individual instructions.
1471/// This is normally not worthwhile since the spiller is doing essentially the
1472/// same thing. However, when the live range is in a constrained register
1473/// class, it may help to insert copies such that parts of the live range can
1474/// be moved to a larger register class.
1475///
1476/// This is similar to spilling to a larger register class.
1477unsigned
1478RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001479 SmallVectorImpl<unsigned> &NewVRegs) {
Stephen Hines36b56882014-04-23 16:57:46 -07001480 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001481 // There is no point to this if there are no larger sub-classes.
Stephen Hines36b56882014-04-23 16:57:46 -07001482 if (!RegClassInfo.isProperSubClass(CurRC))
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001483 return 0;
1484
1485 // Always enable split spill mode, since we're effectively spilling to a
1486 // register.
1487 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1488 SE->reset(LREdit, SplitEditor::SM_Size);
1489
1490 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1491 if (Uses.size() <= 1)
1492 return 0;
1493
1494 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1495
Stephen Hines36b56882014-04-23 16:57:46 -07001496 const TargetRegisterClass *SuperRC = TRI->getLargestLegalSuperClass(CurRC);
1497 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1498 // Split around every non-copy instruction if this split will relax
1499 // the constraints on the virtual register.
1500 // Otherwise, splitting just inserts uncoalescable copies that do not help
1501 // the allocation.
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001502 for (unsigned i = 0; i != Uses.size(); ++i) {
1503 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
Stephen Hines36b56882014-04-23 16:57:46 -07001504 if (MI->isFullCopy() ||
1505 SuperRCNumAllocatableRegs ==
1506 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1507 TRI, RCI)) {
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001508 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1509 continue;
1510 }
1511 SE->openIntv();
1512 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1513 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1514 SE->useIntv(SegStart, SegStop);
1515 }
1516
1517 if (LREdit.empty()) {
1518 DEBUG(dbgs() << "All uses were copies.\n");
1519 return 0;
1520 }
1521
1522 SmallVector<unsigned, 8> IntvMap;
1523 SE->finish(&IntvMap);
Mark Lacey1feb5852013-08-14 23:50:04 +00001524 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001525 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1526
1527 // Assign all new registers to RS_Spill. This was the last chance.
1528 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1529 return 0;
1530}
1531
1532
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001533//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001534// Local Splitting
1535//===----------------------------------------------------------------------===//
1536
1537
1538/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1539/// in order to use PhysReg between two entries in SA->UseSlots.
1540///
1541/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1542///
1543void RAGreedy::calcGapWeights(unsigned PhysReg,
1544 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001545 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1546 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001547 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001548 const unsigned NumGaps = Uses.size()-1;
1549
1550 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001551 SlotIndex StartIdx =
1552 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1553 SlotIndex StopIdx =
1554 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001555
1556 GapWeight.assign(NumGaps, 0.0f);
1557
1558 // Add interference from each overlapping register.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001559 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1560 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1561 .checkInterference())
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001562 continue;
1563
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001564 // We know that VirtReg is a continuous interval from FirstInstr to
1565 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001566 //
1567 // Interference that overlaps an instruction is counted in both gaps
1568 // surrounding the instruction. The exception is interference before
1569 // StartIdx and after StopIdx.
1570 //
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001571 LiveIntervalUnion::SegmentIter IntI =
1572 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001573 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1574 // Skip the gaps before IntI.
1575 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1576 if (++Gap == NumGaps)
1577 break;
1578 if (Gap == NumGaps)
1579 break;
1580
1581 // Update the gaps covered by IntI.
1582 const float weight = IntI.value()->weight;
1583 for (; Gap != NumGaps; ++Gap) {
1584 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1585 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1586 break;
1587 }
1588 if (Gap == NumGaps)
1589 break;
1590 }
1591 }
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001592
1593 // Add fixed interference.
1594 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun4f3b5e82013-10-10 21:29:02 +00001595 const LiveRange &LR = LIS->getRegUnit(*Units);
1596 LiveRange::const_iterator I = LR.find(StartIdx);
1597 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001598
1599 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1600 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1601 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1602 if (++Gap == NumGaps)
1603 break;
1604 if (Gap == NumGaps)
1605 break;
1606
1607 for (; Gap != NumGaps; ++Gap) {
Aaron Ballmaneb360242013-11-13 00:15:44 +00001608 GapWeight[Gap] = llvm::huge_valf;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001609 if (Uses[Gap+1].getBaseIndex() >= I->end)
1610 break;
1611 }
1612 if (Gap == NumGaps)
1613 break;
1614 }
1615 }
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001616}
1617
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001618/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1619/// basic block.
1620///
1621unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001622 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001623 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1624 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001625
1626 // Note that it is possible to have an interval that is live-in or live-out
1627 // while only covering a single block - A phi-def can use undef values from
1628 // predecessors, and the block could be a single-block loop.
1629 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001630 // that the interval is continuous from FirstInstr to LastInstr. We should
1631 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001632
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001633 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001634 if (Uses.size() <= 2)
1635 return 0;
1636 const unsigned NumGaps = Uses.size()-1;
1637
1638 DEBUG({
1639 dbgs() << "tryLocalSplit: ";
1640 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001641 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001642 dbgs() << '\n';
1643 });
1644
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001645 // If VirtReg is live across any register mask operands, compute a list of
1646 // gaps with register masks.
1647 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001648 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001649 // Get regmask slots for the whole block.
1650 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001651 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001652 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001653 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1654 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001655 unsigned re = RMS.size();
1656 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001657 // Look for Uses[i] <= RMS <= Uses[i+1].
1658 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1659 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001660 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001661 // Skip a regmask on the same instruction as the last use. It doesn't
1662 // overlap the live range.
1663 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1664 break;
1665 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001666 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001667 // Advance ri to the next gap. A regmask on one of the uses counts in
1668 // both gaps.
1669 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1670 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001671 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001672 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001673 }
1674
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001675 // Since we allow local split results to be split again, there is a risk of
1676 // creating infinite loops. It is tempting to require that the new live
1677 // ranges have less instructions than the original. That would guarantee
1678 // convergence, but it is too strict. A live range with 3 instructions can be
1679 // split 2+3 (including the COPY), and we want to allow that.
1680 //
1681 // Instead we use these rules:
1682 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001683 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001684 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001685 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001686 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001687 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001688 // smaller ranges are marked RS_New.
1689 //
1690 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1691 // excessive splitting and infinite loops.
1692 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001693 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001694
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001695 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001696 unsigned BestBefore = NumGaps;
1697 unsigned BestAfter = 0;
1698 float BestDiff = 0;
1699
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001700 const float blockFreq =
1701 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
Stephen Hines36b56882014-04-23 16:57:46 -07001702 (1.0f / MBFI->getEntryFreq());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001703 SmallVector<float, 8> GapWeight;
1704
1705 Order.rewind();
1706 while (unsigned PhysReg = Order.next()) {
1707 // Keep track of the largest spill weight that would need to be evicted in
1708 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1709 calcGapWeights(PhysReg, GapWeight);
1710
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001711 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001712 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001713 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Aaron Ballmaneb360242013-11-13 00:15:44 +00001714 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001715
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001716 // Try to find the best sequence of gaps to close.
1717 // The new spill weight must be larger than any gap interference.
1718
1719 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001720 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001721
1722 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1723 // It is the spill weight that needs to be evicted.
1724 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001725
1726 for (;;) {
1727 // Live before/after split?
1728 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1729 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1730
1731 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1732 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1733 << " i=" << MaxGap);
1734
1735 // Stop before the interval gets so big we wouldn't be making progress.
1736 if (!LiveBefore && !LiveAfter) {
1737 DEBUG(dbgs() << " all\n");
1738 break;
1739 }
1740 // Should the interval be extended or shrunk?
1741 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001742
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001743 // How many gaps would the new range have?
1744 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1745
1746 // Legally, without causing looping?
1747 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1748
Aaron Ballmaneb360242013-11-13 00:15:44 +00001749 if (Legal && MaxGap < llvm::huge_valf) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001750 // Estimate the new spill weight. Each instruction reads or writes the
1751 // register. Conservatively assume there are no read-modify-write
1752 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001753 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001754 // Try to guess the size of the new interval.
1755 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1756 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1757 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001758 // Would this split be possible to allocate?
1759 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001760 DEBUG(dbgs() << " w=" << EstWeight);
1761 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001762 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001763 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001764 if (Diff > BestDiff) {
1765 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001766 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001767 BestBefore = SplitBefore;
1768 BestAfter = SplitAfter;
1769 }
1770 }
1771 }
1772
1773 // Try to shrink.
1774 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001775 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001776 DEBUG(dbgs() << " shrink\n");
1777 // Recompute the max when necessary.
1778 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1779 MaxGap = GapWeight[SplitBefore];
1780 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1781 MaxGap = std::max(MaxGap, GapWeight[i]);
1782 }
1783 continue;
1784 }
1785 MaxGap = 0;
1786 }
1787
1788 // Try to extend the interval.
1789 if (SplitAfter >= NumGaps) {
1790 DEBUG(dbgs() << " end\n");
1791 break;
1792 }
1793
1794 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001795 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001796 }
1797 }
1798
1799 // Didn't find any candidates?
1800 if (BestBefore == NumGaps)
1801 return 0;
1802
1803 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1804 << '-' << Uses[BestAfter] << ", " << BestDiff
1805 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1806
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001807 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001808 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001809
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001810 SE->openIntv();
1811 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1812 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1813 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001814 SmallVector<unsigned, 8> IntvMap;
1815 SE->finish(&IntvMap);
Mark Lacey1feb5852013-08-14 23:50:04 +00001816 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001817
1818 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001819 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001820 // leave the new intervals as RS_New so they can compete.
1821 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1822 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1823 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1824 if (NewGaps >= NumGaps) {
1825 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1826 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001827 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1828 if (IntvMap[i] == 1) {
Mark Lacey1feb5852013-08-14 23:50:04 +00001829 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1830 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001831 }
1832 DEBUG(dbgs() << '\n');
1833 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001834 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001835
1836 return 0;
1837}
1838
1839//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001840// Live Range Splitting
1841//===----------------------------------------------------------------------===//
1842
1843/// trySplit - Try to split VirtReg or one of its interferences, making it
1844/// assignable.
1845/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1846unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001847 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001848 // Ranges must be Split2 or less.
1849 if (getStage(VirtReg) >= RS_Spill)
1850 return 0;
1851
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001852 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001853 if (LIS->intervalIsInOneMBB(VirtReg)) {
1854 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001855 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001856 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1857 if (PhysReg || !NewVRegs.empty())
1858 return PhysReg;
1859 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001860 }
1861
1862 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001863
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001864 SA->analyze(&VirtReg);
1865
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001866 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1867 // coalescer. That may cause the range to become allocatable which means that
1868 // tryRegionSplit won't be making progress. This check should be replaced with
1869 // an assertion when the coalescer is fixed.
1870 if (SA->didRepairRange()) {
1871 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001872 Matrix->invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001873 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1874 return PhysReg;
1875 }
1876
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001877 // First try to split around a region spanning multiple blocks. RS_Split2
1878 // ranges already made dubious progress with region splitting, so they go
1879 // straight to single block splitting.
1880 if (getStage(VirtReg) < RS_Split2) {
1881 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1882 if (PhysReg || !NewVRegs.empty())
1883 return PhysReg;
1884 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001885
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001886 // Then isolate blocks.
1887 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001888}
1889
Stephen Hines36b56882014-04-23 16:57:46 -07001890//===----------------------------------------------------------------------===//
1891// Last Chance Recoloring
1892//===----------------------------------------------------------------------===//
1893
1894/// mayRecolorAllInterferences - Check if the virtual registers that
1895/// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
1896/// recolored to free \p PhysReg.
1897/// When true is returned, \p RecoloringCandidates has been augmented with all
1898/// the live intervals that need to be recolored in order to free \p PhysReg
1899/// for \p VirtReg.
1900/// \p FixedRegisters contains all the virtual registers that cannot be
1901/// recolored.
1902bool
1903RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
1904 SmallLISet &RecoloringCandidates,
1905 const SmallVirtRegSet &FixedRegisters) {
1906 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
1907
1908 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1909 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1910 // If there is LastChanceRecoloringMaxInterference or more interferences,
1911 // chances are one would not be recolorable.
1912 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
1913 LastChanceRecoloringMaxInterference) {
1914 DEBUG(dbgs() << "Early abort: too many interferences.\n");
1915 return false;
1916 }
1917 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
1918 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
1919 // If Intf is done and sit on the same register class as VirtReg,
1920 // it would not be recolorable as it is in the same state as VirtReg.
1921 if ((getStage(*Intf) == RS_Done &&
1922 MRI->getRegClass(Intf->reg) == CurRC) ||
1923 FixedRegisters.count(Intf->reg)) {
1924 DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
1925 return false;
1926 }
1927 RecoloringCandidates.insert(Intf);
1928 }
1929 }
1930 return true;
1931}
1932
1933/// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
1934/// its interferences.
1935/// Last chance recoloring chooses a color for \p VirtReg and recolors every
1936/// virtual register that was using it. The recoloring process may recursively
1937/// use the last chance recoloring. Therefore, when a virtual register has been
1938/// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
1939/// be last-chance-recolored again during this recoloring "session".
1940/// E.g.,
1941/// Let
1942/// vA can use {R1, R2 }
1943/// vB can use { R2, R3}
1944/// vC can use {R1 }
1945/// Where vA, vB, and vC cannot be split anymore (they are reloads for
1946/// instance) and they all interfere.
1947///
1948/// vA is assigned R1
1949/// vB is assigned R2
1950/// vC tries to evict vA but vA is already done.
1951/// Regular register allocation fails.
1952///
1953/// Last chance recoloring kicks in:
1954/// vC does as if vA was evicted => vC uses R1.
1955/// vC is marked as fixed.
1956/// vA needs to find a color.
1957/// None are available.
1958/// vA cannot evict vC: vC is a fixed virtual register now.
1959/// vA does as if vB was evicted => vA uses R2.
1960/// vB needs to find a color.
1961/// R3 is available.
1962/// Recoloring => vC = R1, vA = R2, vB = R3
1963///
1964/// \p Order defines the preferred allocation order for \p VirtReg.
1965/// \p NewRegs will contain any new virtual register that have been created
1966/// (split, spill) during the process and that must be assigned.
1967/// \p FixedRegisters contains all the virtual registers that cannot be
1968/// recolored.
1969/// \p Depth gives the current depth of the last chance recoloring.
1970/// \return a physical register that can be used for VirtReg or ~0u if none
1971/// exists.
1972unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
1973 AllocationOrder &Order,
1974 SmallVectorImpl<unsigned> &NewVRegs,
1975 SmallVirtRegSet &FixedRegisters,
1976 unsigned Depth) {
1977 DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
1978 // Ranges must be Done.
1979 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
1980 "Last chance recoloring should really be last chance");
1981 // Set the max depth to LastChanceRecoloringMaxDepth.
1982 // We may want to reconsider that if we end up with a too large search space
1983 // for target with hundreds of registers.
1984 // Indeed, in that case we may want to cut the search space earlier.
1985 if (Depth >= LastChanceRecoloringMaxDepth) {
1986 DEBUG(dbgs() << "Abort because max depth has been reached.\n");
1987 return ~0u;
1988 }
1989
1990 // Set of Live intervals that will need to be recolored.
1991 SmallLISet RecoloringCandidates;
1992 // Record the original mapping virtual register to physical register in case
1993 // the recoloring fails.
1994 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
1995 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
1996 // this recoloring "session".
1997 FixedRegisters.insert(VirtReg.reg);
1998
1999 Order.rewind();
2000 while (unsigned PhysReg = Order.next()) {
2001 DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2002 << PrintReg(PhysReg, TRI) << '\n');
2003 RecoloringCandidates.clear();
2004 VirtRegToPhysReg.clear();
2005
2006 // It is only possible to recolor virtual register interference.
2007 if (Matrix->checkInterference(VirtReg, PhysReg) >
2008 LiveRegMatrix::IK_VirtReg) {
2009 DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
2010
2011 continue;
2012 }
2013
2014 // Early give up on this PhysReg if it is obvious we cannot recolor all
2015 // the interferences.
2016 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2017 FixedRegisters)) {
2018 DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
2019 continue;
2020 }
2021
2022 // RecoloringCandidates contains all the virtual registers that interfer
2023 // with VirtReg on PhysReg (or one of its aliases).
2024 // Enqueue them for recoloring and perform the actual recoloring.
2025 PQueue RecoloringQueue;
2026 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2027 EndIt = RecoloringCandidates.end();
2028 It != EndIt; ++It) {
2029 unsigned ItVirtReg = (*It)->reg;
2030 enqueue(RecoloringQueue, *It);
2031 assert(VRM->hasPhys(ItVirtReg) &&
2032 "Interferences are supposed to be with allocated vairables");
2033
2034 // Record the current allocation.
2035 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2036 // unset the related struct.
2037 Matrix->unassign(**It);
2038 }
2039
2040 // Do as if VirtReg was assigned to PhysReg so that the underlying
2041 // recoloring has the right information about the interferes and
2042 // available colors.
2043 Matrix->assign(VirtReg, PhysReg);
2044
2045 // Save the current recoloring state.
2046 // If we cannot recolor all the interferences, we will have to start again
2047 // at this point for the next physical register.
2048 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2049 if (tryRecoloringCandidates(RecoloringQueue, NewVRegs, FixedRegisters,
2050 Depth)) {
2051 // Do not mess up with the global assignment process.
2052 // I.e., VirtReg must be unassigned.
2053 Matrix->unassign(VirtReg);
2054 return PhysReg;
2055 }
2056
2057 DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2058 << PrintReg(PhysReg, TRI) << '\n');
2059
2060 // The recoloring attempt failed, undo the changes.
2061 FixedRegisters = SaveFixedRegisters;
2062 Matrix->unassign(VirtReg);
2063
2064 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2065 EndIt = RecoloringCandidates.end();
2066 It != EndIt; ++It) {
2067 unsigned ItVirtReg = (*It)->reg;
2068 if (VRM->hasPhys(ItVirtReg))
2069 Matrix->unassign(**It);
2070 Matrix->assign(**It, VirtRegToPhysReg[ItVirtReg]);
2071 }
2072 }
2073
2074 // Last chance recoloring did not worked either, give up.
2075 return ~0u;
2076}
2077
2078/// tryRecoloringCandidates - Try to assign a new color to every register
2079/// in \RecoloringQueue.
2080/// \p NewRegs will contain any new virtual register created during the
2081/// recoloring process.
2082/// \p FixedRegisters[in/out] contains all the registers that have been
2083/// recolored.
2084/// \return true if all virtual registers in RecoloringQueue were successfully
2085/// recolored, false otherwise.
2086bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2087 SmallVectorImpl<unsigned> &NewVRegs,
2088 SmallVirtRegSet &FixedRegisters,
2089 unsigned Depth) {
2090 while (!RecoloringQueue.empty()) {
2091 LiveInterval *LI = dequeue(RecoloringQueue);
2092 DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2093 unsigned PhysReg;
2094 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2095 if (PhysReg == ~0u || !PhysReg)
2096 return false;
2097 DEBUG(dbgs() << "Recoloring of " << *LI
2098 << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
2099 Matrix->assign(*LI, PhysReg);
2100 FixedRegisters.insert(LI->reg);
2101 }
2102 return true;
2103}
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00002104
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00002105//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00002106// Main Entry Point
2107//===----------------------------------------------------------------------===//
2108
2109unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Lacey1feb5852013-08-14 23:50:04 +00002110 SmallVectorImpl<unsigned> &NewVRegs) {
Stephen Hines36b56882014-04-23 16:57:46 -07002111 SmallVirtRegSet FixedRegisters;
2112 return selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2113}
2114
2115/// Using a CSR for the first time has a cost because it causes push|pop
2116/// to be added to prologue|epilogue. Splitting a cold section of the live
2117/// range can have lower cost than using the CSR for the first time;
2118/// Spilling a live range in the cold path can have lower cost than using
2119/// the CSR for the first time. Returns the physical register if we decide
2120/// to use the CSR; otherwise return 0.
2121unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2122 AllocationOrder &Order,
2123 unsigned PhysReg,
2124 unsigned &CostPerUseLimit,
2125 SmallVectorImpl<unsigned> &NewVRegs) {
2126 // We use the larger one out of the command-line option and the value report
2127 // by TRI.
2128 BlockFrequency CSRCost(std::max((unsigned)CSRFirstTimeCost,
2129 TRI->getCSRFirstUseCost()));
2130 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2131 // We choose spill over using the CSR for the first time if the spill cost
2132 // is lower than CSRCost.
2133 SA->analyze(&VirtReg);
2134 if (calcSpillCost() >= CSRCost)
2135 return PhysReg;
2136
2137 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2138 // we will not use a callee-saved register in tryEvict.
2139 CostPerUseLimit = 1;
2140 return 0;
2141 }
2142 if (getStage(VirtReg) < RS_Split) {
2143 // We choose pre-splitting over using the CSR for the first time if
2144 // the cost of splitting is lower than CSRCost.
2145 SA->analyze(&VirtReg);
2146 unsigned NumCands = 0;
2147 unsigned BestCand =
2148 calculateRegionSplitCost(VirtReg, Order, CSRCost, NumCands,
2149 true/*IgnoreCSR*/);
2150 if (BestCand == NoCand)
2151 // Use the CSR if we can't find a region split below CSRCost.
2152 return PhysReg;
2153
2154 // Perform the actual pre-splitting.
2155 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2156 return 0;
2157 }
2158 return PhysReg;
2159}
2160
2161unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2162 SmallVectorImpl<unsigned> &NewVRegs,
2163 SmallVirtRegSet &FixedRegisters,
2164 unsigned Depth) {
2165 unsigned CostPerUseLimit = ~0u;
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00002166 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00002167 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Stephen Hines36b56882014-04-23 16:57:46 -07002168 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
2169 // We check other options if we are using a CSR for the first time.
2170 bool CSRFirstUse = false;
2171 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
2172 if (!MRI->isPhysRegUsed(CSR))
2173 CSRFirstUse = true;
2174
2175 // When NewVRegs is not empty, we may have made decisions such as evicting
2176 // a virtual register, go with the earlier decisions and use the physical
2177 // register.
2178 if ((CSRFirstTimeCost || TRI->getCSRFirstUseCost()) &&
2179 CSRFirstUse && NewVRegs.empty()) {
2180 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2181 CostPerUseLimit, NewVRegs);
2182 if (CSRReg || !NewVRegs.empty())
2183 // Return now if we decide to use a CSR or create new vregs due to
2184 // pre-splitting.
2185 return CSRReg;
2186 } else
2187 return PhysReg;
2188 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00002189
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00002190 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00002191 DEBUG(dbgs() << StageName[Stage]
2192 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00002193
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00002194 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00002195 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00002196 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00002197 if (Stage != RS_Split)
Stephen Hines36b56882014-04-23 16:57:46 -07002198 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit))
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00002199 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00002200
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00002201 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
2202
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00002203 // The first time we see a live range, don't try to split or spill.
2204 // Wait until the second time, when all smaller ranges have been allocated.
2205 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00002206 if (Stage < RS_Split) {
2207 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00002208 DEBUG(dbgs() << "wait for second round\n");
Mark Lacey1feb5852013-08-14 23:50:04 +00002209 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00002210 return 0;
2211 }
2212
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00002213 // If we couldn't allocate a register from spilling, there is probably some
2214 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00002215 if (Stage >= RS_Done || !VirtReg.isSpillable())
Stephen Hines36b56882014-04-23 16:57:46 -07002216 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2217 Depth);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00002218
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00002219 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00002220 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
2221 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00002222 return PhysReg;
2223
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00002224 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00002225 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00002226 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00002227 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00002228 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002229
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00002230 if (VerifyEnabled)
2231 MF->verify(this, "After spilling");
2232
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002233 // The live virtual register requesting allocation was spilled, so tell
2234 // the caller not to allocate anything during this round.
2235 return 0;
2236}
2237
2238bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2239 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikie986d76d2012-08-22 17:18:53 +00002240 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002241
2242 MF = &mf;
Stephen Hines36b56882014-04-23 16:57:46 -07002243 TRI = MF->getTarget().getRegisterInfo();
2244 TII = MF->getTarget().getInstrInfo();
2245 RCI.runOnMachineFunction(mf);
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00002246 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00002247 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00002248
Jakob Stoklund Olesend4348a22012-06-20 22:52:29 +00002249 RegAllocBase::init(getAnalysis<VirtRegMap>(),
2250 getAnalysis<LiveIntervals>(),
2251 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00002252 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramer4eed7562013-06-17 19:00:36 +00002253 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00002254 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00002255 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00002256 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00002257 Bundles = &getAnalysis<EdgeBundles>();
2258 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00002259 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00002260
Arnaud A. de Grandmaison095f9942013-11-11 19:04:45 +00002261 calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
Arnaud A. de Grandmaisona77da052013-11-10 17:46:31 +00002262
Andrew Trick5dca6132013-07-25 07:26:26 +00002263 DEBUG(LIS->dump());
2264
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00002265 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramer4eed7562013-06-17 19:00:36 +00002266 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00002267 ExtraRegInfo.clear();
2268 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2269 NextCascade = 1;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00002270 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00002271 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00002272
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002273 allocatePhysRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002274 releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002275 return true;
2276}