blob: aa317b840d00b27facd394ef7877337d80d45ba3 [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"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000016#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000017#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000018#include "LiveDebugVariables.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000019#include "LiveRangeEdit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000020#include "RegAllocBase.h"
21#include "Spiller.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000022#include "SpillPlacement.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000024#include "VirtRegMap.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000025#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000026#include "llvm/Analysis/AliasAnalysis.h"
27#include "llvm/Function.h"
28#include "llvm/PassAnalysisSupport.h"
29#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000030#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveIntervalAnalysis.h"
32#include "llvm/CodeGen/LiveStackAnalysis.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"
37#include "llvm/CodeGen/Passes.h"
38#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000039#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000040#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000044#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000045
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
Andrew Trickc1b1c7b2012-01-17 06:54:59 +000054/// EnableMachineSched - temporary flag to enable the machine scheduling pass
55/// until we complete the register allocation pass configuration cleanup.
56static cl::opt<bool>
57EnableMachineSched("enable-misched",
58 cl::desc("Enable the machine instruction scheduling pass."),
59 cl::init(false), cl::Hidden);
60
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000061static cl::opt<SplitEditor::ComplementSpillMode>
62SplitSpillMode("split-spill-mode", cl::Hidden,
63 cl::desc("Spill mode for splitting live ranges"),
64 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
65 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
66 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
67 clEnumValEnd),
68 cl::init(SplitEditor::SM_Partition));
69
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000070static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
71 createGreedyRegisterAllocator);
72
73namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000074class RAGreedy : public MachineFunctionPass,
75 public RegAllocBase,
76 private LiveRangeEdit::Delegate {
77
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000078 // context
79 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000080
81 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000082 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000083 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000084 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000085 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000086 EdgeBundles *Bundles;
87 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000088 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000089
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000090 // state
91 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000092 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000093 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000094
95 // Live ranges pass through a number of stages as we try to allocate them.
96 // Some of the stages may also create new live ranges:
97 //
98 // - Region splitting.
99 // - Per-block splitting.
100 // - Local splitting.
101 // - Spilling.
102 //
103 // Ranges produced by one of the stages skip the previous stages when they are
104 // dequeued. This improves performance because we can skip interference checks
105 // that are unlikely to give any results. It also guarantees that the live
106 // range splitting algorithm terminates, something that is otherwise hard to
107 // ensure.
108 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000109 /// Newly created live range that has never been queued.
110 RS_New,
111
112 /// Only attempt assignment and eviction. Then requeue as RS_Split.
113 RS_Assign,
114
115 /// Attempt live range splitting if assignment is impossible.
116 RS_Split,
117
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000118 /// Attempt more aggressive live range splitting that is guaranteed to make
119 /// progress. This is used for split products that may not be making
120 /// progress.
121 RS_Split2,
122
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000123 /// Live range will be spilled. No more splitting will be attempted.
124 RS_Spill,
125
126 /// There is nothing more we can do to this live range. Abort compilation
127 /// if it can't be assigned.
128 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000129 };
130
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000131 static const char *const StageName[];
132
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000133 // RegInfo - Keep additional information about each live range.
134 struct RegInfo {
135 LiveRangeStage Stage;
136
137 // Cascade - Eviction loop prevention. See canEvictInterference().
138 unsigned Cascade;
139
140 RegInfo() : Stage(RS_New), Cascade(0) {}
141 };
142
143 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000144
145 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000146 return ExtraRegInfo[VirtReg.reg].Stage;
147 }
148
149 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
150 ExtraRegInfo.resize(MRI->getNumVirtRegs());
151 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000152 }
153
154 template<typename Iterator>
155 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000156 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000157 for (;Begin != End; ++Begin) {
158 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000159 if (ExtraRegInfo[Reg].Stage == RS_New)
160 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000161 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000162 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000163
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000164 /// Cost of evicting interference.
165 struct EvictionCost {
166 unsigned BrokenHints; ///< Total number of broken hints.
167 float MaxWeight; ///< Maximum spill weight evicted.
168
169 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
170
171 bool operator<(const EvictionCost &O) const {
172 if (BrokenHints != O.BrokenHints)
173 return BrokenHints < O.BrokenHints;
174 return MaxWeight < O.MaxWeight;
175 }
176 };
177
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +0000178 // Register mask interference. The current VirtReg is checked for register
179 // mask interference on entry to selectOrSplit(). If there is no
180 // interference, UsableRegs is left empty. If there is interference,
181 // UsableRegs has a bit mask of registers that can be used without register
182 // mask interference.
183 BitVector UsableRegs;
184
185 /// clobberedByRegMask - Returns true if PhysReg is not directly usable
186 /// because of register mask clobbers.
187 bool clobberedByRegMask(unsigned PhysReg) const {
188 return !UsableRegs.empty() && !UsableRegs.test(PhysReg);
189 }
190
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000191 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000192 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000193 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000194
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000195 /// Cached per-block interference maps
196 InterferenceCache IntfCache;
197
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000198 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000199 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000200
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000201 /// Global live range splitting candidate info.
202 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000203 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000204 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000205
206 // SplitKit interval index for this candidate.
207 unsigned IntvIdx;
208
209 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000210 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000211
212 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000213 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000214 SmallVector<unsigned, 8> ActiveBlocks;
215
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000216 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000217 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000218 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000219 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000220 LiveBundles.clear();
221 ActiveBlocks.clear();
222 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000223
224 // Set B[i] = C for every live bundle where B[i] was NoCand.
225 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
226 unsigned Count = 0;
227 for (int i = LiveBundles.find_first(); i >= 0;
228 i = LiveBundles.find_next(i))
229 if (B[i] == NoCand) {
230 B[i] = C;
231 Count++;
232 }
233 return Count;
234 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000235 };
236
237 /// Candidate info for for each PhysReg in AllocationOrder.
238 /// This vector never shrinks, but grows to the size of the largest register
239 /// class.
240 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
241
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000242 enum { NoCand = ~0u };
243
244 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
245 /// NoCand which indicates the stack interval.
246 SmallVector<unsigned, 32> BundleCand;
247
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000248public:
249 RAGreedy();
250
251 /// Return the pass name.
252 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000253 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000254 }
255
256 /// RAGreedy analysis usage.
257 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000258 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000259 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000260 virtual void enqueue(LiveInterval *LI);
261 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000262 virtual unsigned selectOrSplit(LiveInterval&,
263 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000264
265 /// Perform register allocation.
266 virtual bool runOnMachineFunction(MachineFunction &mf);
267
268 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000269
270private:
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000271 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000272 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000273 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000274
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000275 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000276 bool addSplitConstraints(InterferenceCache::Cursor, float&);
277 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000278 void growRegion(GlobalSplitCandidate &Cand);
279 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000280 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000281 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000282 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000283 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
284 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
285 void evictInterference(LiveInterval&, unsigned,
286 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000287
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000288 unsigned tryAssign(LiveInterval&, AllocationOrder&,
289 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000290 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000291 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000292 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
293 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000294 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
295 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000296 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
297 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000298 unsigned trySplit(LiveInterval&, AllocationOrder&,
299 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000300};
301} // end anonymous namespace
302
303char RAGreedy::ID = 0;
304
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000305#ifndef NDEBUG
306const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000307 "RS_New",
308 "RS_Assign",
309 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000310 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000311 "RS_Spill",
312 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000313};
314#endif
315
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000316// Hysteresis to use when comparing floats.
317// This helps stabilize decisions based on float comparisons.
318const float Hysteresis = 0.98f;
319
320
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000321FunctionPass* llvm::createGreedyRegisterAllocator() {
322 return new RAGreedy();
323}
324
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000325RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000326 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000327 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000328 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
329 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
330 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000331 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000332 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000333 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
334 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
335 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
336 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
337 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000338 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
339 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000340}
341
342void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
343 AU.setPreservesCFG();
344 AU.addRequired<AliasAnalysis>();
345 AU.addPreserved<AliasAnalysis>();
346 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000347 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000348 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000349 AU.addRequired<LiveDebugVariables>();
350 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000351 if (StrongPHIElim)
352 AU.addRequiredID(StrongPHIEliminationID);
Jakob Stoklund Olesen27215672011-08-09 00:29:53 +0000353 AU.addRequiredTransitiveID(RegisterCoalescerPassID);
Andrew Trick96f678f2012-01-13 06:30:30 +0000354 if (EnableMachineSched)
Andrew Trick42b7a712012-01-17 06:55:03 +0000355 AU.addRequiredID(MachineSchedulerID);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000356 AU.addRequired<CalculateSpillWeights>();
357 AU.addRequired<LiveStacks>();
358 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000359 AU.addRequired<MachineDominatorTree>();
360 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000361 AU.addRequired<MachineLoopInfo>();
362 AU.addPreserved<MachineLoopInfo>();
363 AU.addRequired<VirtRegMap>();
364 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000365 AU.addRequired<EdgeBundles>();
366 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000367 MachineFunctionPass::getAnalysisUsage(AU);
368}
369
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000370
371//===----------------------------------------------------------------------===//
372// LiveRangeEdit delegate methods
373//===----------------------------------------------------------------------===//
374
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000375bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
376 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
377 unassign(LIS->getInterval(VirtReg), PhysReg);
378 return true;
379 }
380 // Unassigned virtreg is probably in the priority queue.
381 // RegAllocBase will erase it after dequeueing.
382 return false;
383}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000384
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000385void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
386 unsigned PhysReg = VRM->getPhys(VirtReg);
387 if (!PhysReg)
388 return;
389
390 // Register is assigned, put it back on the queue for reassignment.
391 LiveInterval &LI = LIS->getInterval(VirtReg);
392 unassign(LI, PhysReg);
393 enqueue(&LI);
394}
395
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000396void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000397 // Cloning a register we haven't even heard about yet? Just ignore it.
398 if (!ExtraRegInfo.inBounds(Old))
399 return;
400
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000401 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000402 // be split into connected components. The new components are much smaller
403 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000404 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000405 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000406 ExtraRegInfo.grow(New);
407 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000408}
409
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000410void RAGreedy::releaseMemory() {
411 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000412 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000413 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000414 RegAllocBase::releaseMemory();
415}
416
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000417void RAGreedy::enqueue(LiveInterval *LI) {
418 // Prioritize live ranges by size, assigning larger ranges first.
419 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000420 const unsigned Size = LI->getSize();
421 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000422 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
423 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000424 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000425
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000426 ExtraRegInfo.grow(Reg);
427 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000428 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000429
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000430 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000431 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000432 // everything else has been allocated.
433 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000434 } else {
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000435 // Everything is allocated in long->short order. Long ranges that don't fit
436 // should be spilled (or split) ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000437 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000438
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000439 // Boost ranges that have a physical register hint.
440 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
441 Prio |= (1u << 30);
442 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000443
444 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000445}
446
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000447LiveInterval *RAGreedy::dequeue() {
448 if (Queue.empty())
449 return 0;
450 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
451 Queue.pop();
452 return LI;
453}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000454
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000455
456//===----------------------------------------------------------------------===//
457// Direct Assignment
458//===----------------------------------------------------------------------===//
459
460/// tryAssign - Try to assign VirtReg to an available register.
461unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
462 AllocationOrder &Order,
463 SmallVectorImpl<LiveInterval*> &NewVRegs) {
464 Order.rewind();
465 unsigned PhysReg;
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +0000466 while ((PhysReg = Order.next())) {
467 if (clobberedByRegMask(PhysReg))
468 continue;
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000469 if (!checkPhysRegInterference(VirtReg, PhysReg))
470 break;
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +0000471 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000472 if (!PhysReg || Order.isHint(PhysReg))
473 return PhysReg;
474
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000475 // PhysReg is available, but there may be a better choice.
476
477 // If we missed a simple hint, try to cheaply evict interference from the
478 // preferred register.
479 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +0000480 if (Order.isHint(Hint) && !clobberedByRegMask(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000481 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
482 EvictionCost MaxCost(1);
483 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
484 evictInterference(VirtReg, Hint, NewVRegs);
485 return Hint;
486 }
487 }
488
489 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000490 unsigned Cost = TRI->getCostPerUse(PhysReg);
491
492 // Most registers have 0 additional cost.
493 if (!Cost)
494 return PhysReg;
495
496 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
497 << '\n');
498 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
499 return CheapReg ? CheapReg : PhysReg;
500}
501
502
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000503//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000504// Interference eviction
505//===----------------------------------------------------------------------===//
506
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000507/// shouldEvict - determine if A should evict the assigned live range B. The
508/// eviction policy defined by this function together with the allocation order
509/// defined by enqueue() decides which registers ultimately end up being split
510/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000511///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000512/// Cascade numbers are used to prevent infinite loops if this function is a
513/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000514///
515/// @param A The live range to be assigned.
516/// @param IsHint True when A is about to be assigned to its preferred
517/// register.
518/// @param B The live range to be evicted.
519/// @param BreaksHint True when B is already assigned to its preferred register.
520bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
521 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000522 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000523
524 // Be fairly aggressive about following hints as long as the evictee can be
525 // split.
526 if (CanSplit && IsHint && !BreaksHint)
527 return true;
528
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000529 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000530}
531
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000532/// canEvictInterference - Return true if all interferences between VirtReg and
533/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
534///
535/// @param VirtReg Live range that is about to be assigned.
536/// @param PhysReg Desired register for assignment.
537/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
538/// @param MaxCost Only look for cheaper candidates and update with new cost
539/// when returning true.
540/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000541bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000542 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000543 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
544 // involved in an eviction before. If a cascade number was assigned, deny
545 // evicting anything with the same or a newer cascade number. This prevents
546 // infinite eviction loops.
547 //
548 // This works out so a register without a cascade number is allowed to evict
549 // anything, and it can be evicted by anything.
550 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
551 if (!Cascade)
552 Cascade = NextCascade;
553
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000554 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000555 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
556 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000557 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000558 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000559 return false;
560
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000561 // Check if any interfering live range is heavier than MaxWeight.
562 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
563 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000564 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
565 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000566 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000567 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000568 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000569 // Once a live range becomes small enough, it is urgent that we find a
570 // register for it. This is indicated by an infinite spill weight. These
571 // urgent live ranges get to evict almost anything.
572 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
573 // Only evict older cascades or live ranges without a cascade.
574 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
575 if (Cascade <= IntfCascade) {
576 if (!Urgent)
577 return false;
578 // We permit breaking cascades for urgent evictions. It should be the
579 // last resort, though, so make it really expensive.
580 Cost.BrokenHints += 10;
581 }
582 // Would this break a satisfied hint?
583 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
584 // Update eviction cost.
585 Cost.BrokenHints += BreaksHint;
586 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
587 // Abort if this would be too expensive.
588 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000589 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000590 // Finally, apply the eviction policy for non-urgent evictions.
591 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000592 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000593 }
594 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000595 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000596 return true;
597}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000598
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000599/// evictInterference - Evict any interferring registers that prevent VirtReg
600/// from being assigned to Physreg. This assumes that canEvictInterference
601/// returned true.
602void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
603 SmallVectorImpl<LiveInterval*> &NewVRegs) {
604 // Make sure that VirtReg has a cascade number, and assign that cascade
605 // number to every evicted register. These live ranges than then only be
606 // evicted by a newer cascade, preventing infinite loops.
607 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
608 if (!Cascade)
609 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
610
611 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
612 << " interference: Cascade " << Cascade << '\n');
613 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
614 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
615 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
616 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
617 LiveInterval *Intf = Q.interferingVRegs()[i];
618 unassign(*Intf, VRM->getPhys(Intf->reg));
619 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
620 VirtReg.isSpillable() < Intf->isSpillable()) &&
621 "Cannot decrease cascade number, illegal eviction");
622 ExtraRegInfo[Intf->reg].Cascade = Cascade;
623 ++NumEvicted;
624 NewVRegs.push_back(Intf);
625 }
626 }
627}
628
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000629/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000630/// @param VirtReg Currently unassigned virtual register.
631/// @param Order Physregs to try.
632/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000633unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
634 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000635 SmallVectorImpl<LiveInterval*> &NewVRegs,
636 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000637 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
638
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000639 // Keep track of the cheapest interference seen so far.
640 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000641 unsigned BestPhys = 0;
642
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000643 // When we are just looking for a reduced cost per use, don't break any
644 // hints, and only evict smaller spill weights.
645 if (CostPerUseLimit < ~0u) {
646 BestCost.BrokenHints = 0;
647 BestCost.MaxWeight = VirtReg.weight;
648 }
649
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000650 Order.rewind();
651 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +0000652 if (clobberedByRegMask(PhysReg))
653 continue;
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000654 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
655 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000656 // The first use of a callee-saved register in a function has cost 1.
657 // Don't start using a CSR when the CostPerUseLimit is low.
658 if (CostPerUseLimit == 1)
659 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
660 if (!MRI->isPhysRegUsed(CSR)) {
661 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
662 << PrintReg(CSR, TRI) << '\n');
663 continue;
664 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000665
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000666 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000667 continue;
668
669 // Best so far.
670 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000671
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000672 // Stop if the hint can be used.
673 if (Order.isHint(PhysReg))
674 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000675 }
676
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000677 if (!BestPhys)
678 return 0;
679
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000680 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000681 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000682}
683
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000684
685//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000686// Region Splitting
687//===----------------------------------------------------------------------===//
688
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000689/// addSplitConstraints - Fill out the SplitConstraints vector based on the
690/// interference pattern in Physreg and its aliases. Add the constraints to
691/// SpillPlacement and return the static cost of this split in Cost, assuming
692/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000693/// Return false if there are no bundles with positive bias.
694bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
695 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000696 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000697
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000698 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000699 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000700 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000701 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
702 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000703 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000704
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000705 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000706 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000707 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
708 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000709 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000710
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000711 if (!Intf.hasInterference())
712 continue;
713
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000714 // Number of spill code instructions to insert.
715 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000716
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000717 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000718 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000719 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000720 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000721 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000722 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000723 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000724 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000725 }
726
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000727 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000728 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000729 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000730 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000731 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000732 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000733 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000734 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000735 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000736
737 // Accumulate the total frequency of inserted spill code.
738 if (Ins)
739 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000740 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000741 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000742
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000743 // Add constraints for use-blocks. Note that these are the only constraints
744 // that may add a positive bias, it is downhill from here.
745 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000746 return SpillPlacer->scanActiveBundles();
747}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000748
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000749
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000750/// addThroughConstraints - Add constraints and links to SpillPlacer from the
751/// live-through blocks in Blocks.
752void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
753 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000754 const unsigned GroupSize = 8;
755 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000756 unsigned TBS[GroupSize];
757 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000758
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000759 for (unsigned i = 0; i != Blocks.size(); ++i) {
760 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000761 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000762
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000763 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000764 assert(T < GroupSize && "Array overflow");
765 TBS[T] = Number;
766 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000767 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000768 T = 0;
769 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000770 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000771 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000772
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000773 assert(B < GroupSize && "Array overflow");
774 BCS[B].Number = Number;
775
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000776 // Interference for the live-in value.
777 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
778 BCS[B].Entry = SpillPlacement::MustSpill;
779 else
780 BCS[B].Entry = SpillPlacement::PrefSpill;
781
782 // Interference for the live-out value.
783 if (Intf.last() >= SA->getLastSplitPoint(Number))
784 BCS[B].Exit = SpillPlacement::MustSpill;
785 else
786 BCS[B].Exit = SpillPlacement::PrefSpill;
787
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000788 if (++B == GroupSize) {
789 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
790 SpillPlacer->addConstraints(Array);
791 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000792 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000793 }
794
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000795 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
796 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000797 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000798}
799
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000800void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000801 // Keep track of through blocks that have not been added to SpillPlacer.
802 BitVector Todo = SA->getThroughBlocks();
803 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
804 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000805#ifndef NDEBUG
806 unsigned Visited = 0;
807#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000808
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000809 for (;;) {
810 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000811 // Find new through blocks in the periphery of PrefRegBundles.
812 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
813 unsigned Bundle = NewBundles[i];
814 // Look at all blocks connected to Bundle in the full graph.
815 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
816 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
817 I != E; ++I) {
818 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000819 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000820 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000821 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000822 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000823 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000824#ifndef NDEBUG
825 ++Visited;
826#endif
827 }
828 }
829 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000830 if (ActiveBlocks.size() == AddedTo)
831 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000832
833 // Compute through constraints from the interference, or assume that all
834 // through blocks prefer spilling when forming compact regions.
835 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
836 if (Cand.PhysReg)
837 addThroughConstraints(Cand.Intf, NewBlocks);
838 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000839 // Provide a strong negative bias on through blocks to prevent unwanted
840 // liveness on loop backedges.
841 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000842 AddedTo = ActiveBlocks.size();
843
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000844 // Perhaps iterating can enable more bundles?
845 SpillPlacer->iterate();
846 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000847 DEBUG(dbgs() << ", v=" << Visited);
848}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000849
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000850/// calcCompactRegion - Compute the set of edge bundles that should be live
851/// when splitting the current live range into compact regions. Compact
852/// regions can be computed without looking at interference. They are the
853/// regions formed by removing all the live-through blocks from the live range.
854///
855/// Returns false if the current live range is already compact, or if the
856/// compact regions would form single block regions anyway.
857bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
858 // Without any through blocks, the live range is already compact.
859 if (!SA->getNumThroughBlocks())
860 return false;
861
862 // Compact regions don't correspond to any physreg.
863 Cand.reset(IntfCache, 0);
864
865 DEBUG(dbgs() << "Compact region bundles");
866
867 // Use the spill placer to determine the live bundles. GrowRegion pretends
868 // that all the through blocks have interference when PhysReg is unset.
869 SpillPlacer->prepare(Cand.LiveBundles);
870
871 // The static split cost will be zero since Cand.Intf reports no interference.
872 float Cost;
873 if (!addSplitConstraints(Cand.Intf, Cost)) {
874 DEBUG(dbgs() << ", none.\n");
875 return false;
876 }
877
878 growRegion(Cand);
879 SpillPlacer->finish();
880
881 if (!Cand.LiveBundles.any()) {
882 DEBUG(dbgs() << ", none.\n");
883 return false;
884 }
885
886 DEBUG({
887 for (int i = Cand.LiveBundles.find_first(); i>=0;
888 i = Cand.LiveBundles.find_next(i))
889 dbgs() << " EB#" << i;
890 dbgs() << ".\n";
891 });
892 return true;
893}
894
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000895/// calcSpillCost - Compute how expensive it would be to split the live range in
896/// SA around all use blocks instead of forming bundle regions.
897float RAGreedy::calcSpillCost() {
898 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000899 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
900 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
901 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
902 unsigned Number = BI.MBB->getNumber();
903 // We normally only need one spill instruction - a load or a store.
904 Cost += SpillPlacer->getBlockFrequency(Number);
905
906 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000907 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
908 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000909 }
910 return Cost;
911}
912
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000913/// calcGlobalSplitCost - Return the global split cost of following the split
914/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000915/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000916///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000917float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000918 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000919 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000920 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
921 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
922 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000923 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000924 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
925 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
926 unsigned Ins = 0;
927
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000928 if (BI.LiveIn)
929 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
930 if (BI.LiveOut)
931 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000932 if (Ins)
933 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000934 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000935
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000936 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
937 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000938 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
939 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000940 if (!RegIn && !RegOut)
941 continue;
942 if (RegIn && RegOut) {
943 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000944 Cand.Intf.moveToBlock(Number);
945 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000946 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
947 continue;
948 }
949 // live-in / stack-out or stack-in live-out.
950 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000951 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000952 return GlobalCost;
953}
954
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000955/// splitAroundRegion - Split the current live range around the regions
956/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000957///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000958/// Before calling this function, GlobalCand and BundleCand must be initialized
959/// so each bundle is assigned to a valid candidate, or NoCand for the
960/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
961/// objects must be initialized for the current live range, and intervals
962/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000963///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000964/// @param LREdit The LiveRangeEdit object handling the current split.
965/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
966/// must appear in this list.
967void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
968 ArrayRef<unsigned> UsedCands) {
969 // These are the intervals created for new global ranges. We may create more
970 // intervals for local ranges.
971 const unsigned NumGlobalIntvs = LREdit.size();
972 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
973 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000974
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000975 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +0000976 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000977 // is all copies.
978 unsigned Reg = SA->getParent().reg;
979 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
980
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000981 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000982 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
983 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
984 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000985 unsigned Number = BI.MBB->getNumber();
986 unsigned IntvIn = 0, IntvOut = 0;
987 SlotIndex IntfIn, IntfOut;
988 if (BI.LiveIn) {
989 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
990 if (CandIn != NoCand) {
991 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
992 IntvIn = Cand.IntvIdx;
993 Cand.Intf.moveToBlock(Number);
994 IntfIn = Cand.Intf.first();
995 }
996 }
997 if (BI.LiveOut) {
998 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
999 if (CandOut != NoCand) {
1000 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1001 IntvOut = Cand.IntvIdx;
1002 Cand.Intf.moveToBlock(Number);
1003 IntfOut = Cand.Intf.last();
1004 }
1005 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001006
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001007 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001008 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001009 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001010 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001011 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001012 continue;
1013 }
1014
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001015 if (IntvIn && IntvOut)
1016 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1017 else if (IntvIn)
1018 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001019 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001020 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001021 }
1022
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001023 // Handle live-through blocks. The relevant live-through blocks are stored in
1024 // the ActiveBlocks list with each candidate. We need to filter out
1025 // duplicates.
1026 BitVector Todo = SA->getThroughBlocks();
1027 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1028 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1029 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1030 unsigned Number = Blocks[i];
1031 if (!Todo.test(Number))
1032 continue;
1033 Todo.reset(Number);
1034
1035 unsigned IntvIn = 0, IntvOut = 0;
1036 SlotIndex IntfIn, IntfOut;
1037
1038 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1039 if (CandIn != NoCand) {
1040 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1041 IntvIn = Cand.IntvIdx;
1042 Cand.Intf.moveToBlock(Number);
1043 IntfIn = Cand.Intf.first();
1044 }
1045
1046 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1047 if (CandOut != NoCand) {
1048 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1049 IntvOut = Cand.IntvIdx;
1050 Cand.Intf.moveToBlock(Number);
1051 IntfOut = Cand.Intf.last();
1052 }
1053 if (!IntvIn && !IntvOut)
1054 continue;
1055 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1056 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001057 }
1058
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001059 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001060
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001061 SmallVector<unsigned, 8> IntvMap;
1062 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001063 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001064
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001065 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001066 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001067
1068 // Sort out the new intervals created by splitting. We get four kinds:
1069 // - Remainder intervals should not be split again.
1070 // - Candidate intervals can be assigned to Cand.PhysReg.
1071 // - Block-local splits are candidates for local splitting.
1072 // - DCE leftovers should go back on the queue.
1073 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001074 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001075
1076 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001077 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001078 continue;
1079
1080 // Remainder interval. Don't try splitting again, spill if it doesn't
1081 // allocate.
1082 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001083 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001084 continue;
1085 }
1086
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001087 // Global intervals. Allow repeated splitting as long as the number of live
1088 // blocks is strictly decreasing.
1089 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001090 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001091 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1092 << " blocks as original.\n");
1093 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001094 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001095 }
1096 continue;
1097 }
1098
1099 // Other intervals are treated as new. This includes local intervals created
1100 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001101 }
1102
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001103 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001104 MF->verify(this, "After splitting live range around region");
1105}
1106
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001107unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1108 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001109 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001110 unsigned BestCand = NoCand;
1111 float BestCost;
1112 SmallVector<unsigned, 8> UsedCands;
1113
1114 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001115 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001116 if (HasCompact) {
1117 // Yes, keep GlobalCand[0] as the compact region candidate.
1118 NumCands = 1;
1119 BestCost = HUGE_VALF;
1120 } else {
1121 // No benefit from the compact region, our fallback will be per-block
1122 // splitting. Make sure we find a solution that is cheaper than spilling.
1123 BestCost = Hysteresis * calcSpillCost();
1124 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1125 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001126
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001127 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001128 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001129 // Discard bad candidates before we run out of interference cache cursors.
1130 // This will only affect register classes with a lot of registers (>32).
1131 if (NumCands == IntfCache.getMaxCursors()) {
1132 unsigned WorstCount = ~0u;
1133 unsigned Worst = 0;
1134 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001135 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001136 continue;
1137 unsigned Count = GlobalCand[i].LiveBundles.count();
1138 if (Count < WorstCount)
1139 Worst = i, WorstCount = Count;
1140 }
1141 --NumCands;
1142 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001143 if (BestCand == NumCands)
1144 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001145 }
1146
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001147 if (GlobalCand.size() <= NumCands)
1148 GlobalCand.resize(NumCands+1);
1149 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1150 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001151
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001152 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001153 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001154 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001155 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001156 continue;
1157 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001158 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001159 if (Cost >= BestCost) {
1160 DEBUG({
1161 if (BestCand == NoCand)
1162 dbgs() << " worse than no bundles\n";
1163 else
1164 dbgs() << " worse than "
1165 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1166 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001167 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001168 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001169 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001170
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001171 SpillPlacer->finish();
1172
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001173 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001174 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001175 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001176 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001177 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001178
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001179 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001180 DEBUG({
1181 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001182 for (int i = Cand.LiveBundles.find_first(); i>=0;
1183 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001184 dbgs() << " EB#" << i;
1185 dbgs() << ".\n";
1186 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001187 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001188 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001189 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001190 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001191 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001192 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001193
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001194 // No solutions found, fall back to single block splitting.
1195 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001196 return 0;
1197
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001198 // Prepare split editor.
1199 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001200 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001201
1202 // Assign all edge bundles to the preferred candidate, or NoCand.
1203 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1204
1205 // Assign bundles for the best candidate region.
1206 if (BestCand != NoCand) {
1207 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1208 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1209 UsedCands.push_back(BestCand);
1210 Cand.IntvIdx = SE->openIntv();
1211 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1212 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001213 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001214 }
1215 }
1216
1217 // Assign bundles for the compact region.
1218 if (HasCompact) {
1219 GlobalSplitCandidate &Cand = GlobalCand.front();
1220 assert(!Cand.PhysReg && "Compact region has no physreg");
1221 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1222 UsedCands.push_back(0);
1223 Cand.IntvIdx = SE->openIntv();
1224 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1225 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001226 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001227 }
1228 }
1229
1230 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001231 return 0;
1232}
1233
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001234
1235//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001236// Per-Block Splitting
1237//===----------------------------------------------------------------------===//
1238
1239/// tryBlockSplit - Split a global live range around every block with uses. This
1240/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1241/// they don't allocate.
1242unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1243 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1244 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1245 unsigned Reg = VirtReg.reg;
1246 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1247 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001248 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001249 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1250 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1251 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1252 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1253 SE->splitSingleBlock(BI);
1254 }
1255 // No blocks were split.
1256 if (LREdit.empty())
1257 return 0;
1258
1259 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001260 SmallVector<unsigned, 8> IntvMap;
1261 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001262
1263 // Tell LiveDebugVariables about the new ranges.
1264 DebugVars->splitRegister(Reg, LREdit.regs());
1265
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001266 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1267
1268 // Sort out the new intervals created by splitting. The remainder interval
1269 // goes straight to spilling, the new local ranges get to stay RS_New.
1270 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1271 LiveInterval &LI = *LREdit.get(i);
1272 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1273 setStage(LI, RS_Spill);
1274 }
1275
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001276 if (VerifyEnabled)
1277 MF->verify(this, "After splitting live range around basic blocks");
1278 return 0;
1279}
1280
1281//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001282// Local Splitting
1283//===----------------------------------------------------------------------===//
1284
1285
1286/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1287/// in order to use PhysReg between two entries in SA->UseSlots.
1288///
1289/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1290///
1291void RAGreedy::calcGapWeights(unsigned PhysReg,
1292 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001293 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1294 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001295 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001296 const unsigned NumGaps = Uses.size()-1;
1297
1298 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001299 SlotIndex StartIdx =
1300 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1301 SlotIndex StopIdx =
1302 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001303
1304 GapWeight.assign(NumGaps, 0.0f);
1305
1306 // Add interference from each overlapping register.
1307 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1308 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1309 .checkInterference())
1310 continue;
1311
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001312 // We know that VirtReg is a continuous interval from FirstInstr to
1313 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001314 //
1315 // Interference that overlaps an instruction is counted in both gaps
1316 // surrounding the instruction. The exception is interference before
1317 // StartIdx and after StopIdx.
1318 //
Jakob Stoklund Olesen93841112012-01-11 23:19:08 +00001319 LiveIntervalUnion::SegmentIter IntI = getLiveUnion(*AI).find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001320 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1321 // Skip the gaps before IntI.
1322 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1323 if (++Gap == NumGaps)
1324 break;
1325 if (Gap == NumGaps)
1326 break;
1327
1328 // Update the gaps covered by IntI.
1329 const float weight = IntI.value()->weight;
1330 for (; Gap != NumGaps; ++Gap) {
1331 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1332 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1333 break;
1334 }
1335 if (Gap == NumGaps)
1336 break;
1337 }
1338 }
1339}
1340
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001341/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1342/// basic block.
1343///
1344unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1345 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001346 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1347 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001348
1349 // Note that it is possible to have an interval that is live-in or live-out
1350 // while only covering a single block - A phi-def can use undef values from
1351 // predecessors, and the block could be a single-block loop.
1352 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001353 // that the interval is continuous from FirstInstr to LastInstr. We should
1354 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001355
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001356 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001357 if (Uses.size() <= 2)
1358 return 0;
1359 const unsigned NumGaps = Uses.size()-1;
1360
1361 DEBUG({
1362 dbgs() << "tryLocalSplit: ";
1363 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001364 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001365 dbgs() << '\n';
1366 });
1367
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001368 // Since we allow local split results to be split again, there is a risk of
1369 // creating infinite loops. It is tempting to require that the new live
1370 // ranges have less instructions than the original. That would guarantee
1371 // convergence, but it is too strict. A live range with 3 instructions can be
1372 // split 2+3 (including the COPY), and we want to allow that.
1373 //
1374 // Instead we use these rules:
1375 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001376 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001377 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001378 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001379 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001380 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001381 // smaller ranges are marked RS_New.
1382 //
1383 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1384 // excessive splitting and infinite loops.
1385 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001386 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001387
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001388 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001389 unsigned BestBefore = NumGaps;
1390 unsigned BestAfter = 0;
1391 float BestDiff = 0;
1392
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001393 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001394 SmallVector<float, 8> GapWeight;
1395
1396 Order.rewind();
1397 while (unsigned PhysReg = Order.next()) {
1398 // Keep track of the largest spill weight that would need to be evicted in
1399 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1400 calcGapWeights(PhysReg, GapWeight);
1401
1402 // Try to find the best sequence of gaps to close.
1403 // The new spill weight must be larger than any gap interference.
1404
1405 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001406 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001407
1408 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1409 // It is the spill weight that needs to be evicted.
1410 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001411
1412 for (;;) {
1413 // Live before/after split?
1414 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1415 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1416
1417 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1418 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1419 << " i=" << MaxGap);
1420
1421 // Stop before the interval gets so big we wouldn't be making progress.
1422 if (!LiveBefore && !LiveAfter) {
1423 DEBUG(dbgs() << " all\n");
1424 break;
1425 }
1426 // Should the interval be extended or shrunk?
1427 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001428
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001429 // How many gaps would the new range have?
1430 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1431
1432 // Legally, without causing looping?
1433 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1434
1435 if (Legal && MaxGap < HUGE_VALF) {
1436 // Estimate the new spill weight. Each instruction reads or writes the
1437 // register. Conservatively assume there are no read-modify-write
1438 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001439 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001440 // Try to guess the size of the new interval.
1441 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1442 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1443 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001444 // Would this split be possible to allocate?
1445 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001446 DEBUG(dbgs() << " w=" << EstWeight);
1447 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001448 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001449 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001450 if (Diff > BestDiff) {
1451 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001452 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001453 BestBefore = SplitBefore;
1454 BestAfter = SplitAfter;
1455 }
1456 }
1457 }
1458
1459 // Try to shrink.
1460 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001461 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001462 DEBUG(dbgs() << " shrink\n");
1463 // Recompute the max when necessary.
1464 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1465 MaxGap = GapWeight[SplitBefore];
1466 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1467 MaxGap = std::max(MaxGap, GapWeight[i]);
1468 }
1469 continue;
1470 }
1471 MaxGap = 0;
1472 }
1473
1474 // Try to extend the interval.
1475 if (SplitAfter >= NumGaps) {
1476 DEBUG(dbgs() << " end\n");
1477 break;
1478 }
1479
1480 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001481 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001482 }
1483 }
1484
1485 // Didn't find any candidates?
1486 if (BestBefore == NumGaps)
1487 return 0;
1488
1489 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1490 << '-' << Uses[BestAfter] << ", " << BestDiff
1491 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1492
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001493 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001494 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001495
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001496 SE->openIntv();
1497 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1498 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1499 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001500 SmallVector<unsigned, 8> IntvMap;
1501 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001502 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001503
1504 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001505 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001506 // leave the new intervals as RS_New so they can compete.
1507 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1508 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1509 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1510 if (NewGaps >= NumGaps) {
1511 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1512 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001513 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1514 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001515 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001516 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1517 }
1518 DEBUG(dbgs() << '\n');
1519 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001520 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001521
1522 return 0;
1523}
1524
1525//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001526// Live Range Splitting
1527//===----------------------------------------------------------------------===//
1528
1529/// trySplit - Try to split VirtReg or one of its interferences, making it
1530/// assignable.
1531/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1532unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1533 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001534 // Ranges must be Split2 or less.
1535 if (getStage(VirtReg) >= RS_Spill)
1536 return 0;
1537
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001538 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001539 if (LIS->intervalIsInOneMBB(VirtReg)) {
1540 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001541 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001542 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001543 }
1544
1545 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001546
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001547 SA->analyze(&VirtReg);
1548
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001549 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1550 // coalescer. That may cause the range to become allocatable which means that
1551 // tryRegionSplit won't be making progress. This check should be replaced with
1552 // an assertion when the coalescer is fixed.
1553 if (SA->didRepairRange()) {
1554 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001555 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001556 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1557 return PhysReg;
1558 }
1559
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001560 // First try to split around a region spanning multiple blocks. RS_Split2
1561 // ranges already made dubious progress with region splitting, so they go
1562 // straight to single block splitting.
1563 if (getStage(VirtReg) < RS_Split2) {
1564 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1565 if (PhysReg || !NewVRegs.empty())
1566 return PhysReg;
1567 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001568
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001569 // Then isolate blocks.
1570 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001571}
1572
1573
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001574//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001575// Main Entry Point
1576//===----------------------------------------------------------------------===//
1577
1578unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001579 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +00001580 // Check if VirtReg is live across any calls.
1581 UsableRegs.clear();
1582 if (LIS->checkRegMaskInterference(VirtReg, UsableRegs))
1583 DEBUG(dbgs() << "Live across regmasks.\n");
1584
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001585 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001586 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001587 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1588 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001589
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001590 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001591 DEBUG(dbgs() << StageName[Stage]
1592 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001593
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001594 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001595 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001596 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001597 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001598 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1599 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001600
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001601 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1602
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001603 // The first time we see a live range, don't try to split or spill.
1604 // Wait until the second time, when all smaller ranges have been allocated.
1605 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001606 if (Stage < RS_Split) {
1607 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001608 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001609 NewVRegs.push_back(&VirtReg);
1610 return 0;
1611 }
1612
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001613 // If we couldn't allocate a register from spilling, there is probably some
1614 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001615 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001616 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001617
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001618 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001619 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1620 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001621 return PhysReg;
1622
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001623 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001624 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001625 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1626 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001627 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001628
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001629 if (VerifyEnabled)
1630 MF->verify(this, "After spilling");
1631
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001632 // The live virtual register requesting allocation was spilled, so tell
1633 // the caller not to allocate anything during this round.
1634 return 0;
1635}
1636
1637bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1638 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1639 << "********** Function: "
1640 << ((Value*)mf.getFunction())->getName() << '\n');
1641
1642 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001643 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001644 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001645
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001646 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001647 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001648 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001649 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001650 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001651 Bundles = &getAnalysis<EdgeBundles>();
1652 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001653 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001654
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001655 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001656 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001657 ExtraRegInfo.clear();
1658 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1659 NextCascade = 1;
Jakob Stoklund Olesen93841112012-01-11 23:19:08 +00001660 IntfCache.init(MF, &getLiveUnion(0), Indexes, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001661 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001662
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001663 allocatePhysRegs();
1664 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001665 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001666
1667 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001668 {
1669 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001670 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001671 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001672
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001673 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenc4769022011-07-31 03:53:42 +00001674 {
1675 NamedRegionTimer T("Emit Debug Info", TimerGroupName, TimePassesIsEnabled);
1676 DebugVars->emitDebugValues(VRM);
1677 }
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001678
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001679 // The pass output is in VirtRegMap. Release all the transient data.
1680 releaseMemory();
1681
1682 return true;
1683}