blob: f54a2c85d1006dc802d450af2dbc880851f65f7a [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
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000054static cl::opt<SplitEditor::ComplementSpillMode>
55SplitSpillMode("split-spill-mode", cl::Hidden,
56 cl::desc("Spill mode for splitting live ranges"),
57 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
58 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
59 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
60 clEnumValEnd),
61 cl::init(SplitEditor::SM_Partition));
62
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000063static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
64 createGreedyRegisterAllocator);
65
66namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000067class RAGreedy : public MachineFunctionPass,
68 public RegAllocBase,
69 private LiveRangeEdit::Delegate {
70
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000071 // context
72 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000073
74 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000075 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000076 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000077 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000078 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000079 EdgeBundles *Bundles;
80 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000081 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000082
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000083 // state
84 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000085 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000086 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000087
88 // Live ranges pass through a number of stages as we try to allocate them.
89 // Some of the stages may also create new live ranges:
90 //
91 // - Region splitting.
92 // - Per-block splitting.
93 // - Local splitting.
94 // - Spilling.
95 //
96 // Ranges produced by one of the stages skip the previous stages when they are
97 // dequeued. This improves performance because we can skip interference checks
98 // that are unlikely to give any results. It also guarantees that the live
99 // range splitting algorithm terminates, something that is otherwise hard to
100 // ensure.
101 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000102 /// Newly created live range that has never been queued.
103 RS_New,
104
105 /// Only attempt assignment and eviction. Then requeue as RS_Split.
106 RS_Assign,
107
108 /// Attempt live range splitting if assignment is impossible.
109 RS_Split,
110
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000111 /// Attempt more aggressive live range splitting that is guaranteed to make
112 /// progress. This is used for split products that may not be making
113 /// progress.
114 RS_Split2,
115
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000116 /// Live range will be spilled. No more splitting will be attempted.
117 RS_Spill,
118
119 /// There is nothing more we can do to this live range. Abort compilation
120 /// if it can't be assigned.
121 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000122 };
123
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000124 static const char *const StageName[];
125
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000126 // RegInfo - Keep additional information about each live range.
127 struct RegInfo {
128 LiveRangeStage Stage;
129
130 // Cascade - Eviction loop prevention. See canEvictInterference().
131 unsigned Cascade;
132
133 RegInfo() : Stage(RS_New), Cascade(0) {}
134 };
135
136 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000137
138 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000139 return ExtraRegInfo[VirtReg.reg].Stage;
140 }
141
142 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
143 ExtraRegInfo.resize(MRI->getNumVirtRegs());
144 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000145 }
146
147 template<typename Iterator>
148 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000149 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000150 for (;Begin != End; ++Begin) {
151 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000152 if (ExtraRegInfo[Reg].Stage == RS_New)
153 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000154 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000155 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000156
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000157 /// Cost of evicting interference.
158 struct EvictionCost {
159 unsigned BrokenHints; ///< Total number of broken hints.
160 float MaxWeight; ///< Maximum spill weight evicted.
161
162 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
163
164 bool operator<(const EvictionCost &O) const {
165 if (BrokenHints != O.BrokenHints)
166 return BrokenHints < O.BrokenHints;
167 return MaxWeight < O.MaxWeight;
168 }
169 };
170
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000171 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000172 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000173 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000174
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000175 /// Cached per-block interference maps
176 InterferenceCache IntfCache;
177
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000178 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000179 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000180
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000181 /// Global live range splitting candidate info.
182 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000183 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000184 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000185
186 // SplitKit interval index for this candidate.
187 unsigned IntvIdx;
188
189 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000190 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000191
192 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000193 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000194 SmallVector<unsigned, 8> ActiveBlocks;
195
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000196 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000197 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000198 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000199 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000200 LiveBundles.clear();
201 ActiveBlocks.clear();
202 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000203
204 // Set B[i] = C for every live bundle where B[i] was NoCand.
205 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
206 unsigned Count = 0;
207 for (int i = LiveBundles.find_first(); i >= 0;
208 i = LiveBundles.find_next(i))
209 if (B[i] == NoCand) {
210 B[i] = C;
211 Count++;
212 }
213 return Count;
214 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000215 };
216
217 /// Candidate info for for each PhysReg in AllocationOrder.
218 /// This vector never shrinks, but grows to the size of the largest register
219 /// class.
220 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
221
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000222 enum { NoCand = ~0u };
223
224 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
225 /// NoCand which indicates the stack interval.
226 SmallVector<unsigned, 32> BundleCand;
227
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000228public:
229 RAGreedy();
230
231 /// Return the pass name.
232 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000233 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000234 }
235
236 /// RAGreedy analysis usage.
237 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000238 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000239 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000240 virtual void enqueue(LiveInterval *LI);
241 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000242 virtual unsigned selectOrSplit(LiveInterval&,
243 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000244
245 /// Perform register allocation.
246 virtual bool runOnMachineFunction(MachineFunction &mf);
247
248 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000249
250private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000251 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000252 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000253 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000254 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000255
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000256 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000257 bool addSplitConstraints(InterferenceCache::Cursor, float&);
258 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000259 void growRegion(GlobalSplitCandidate &Cand);
260 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000261 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000262 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000263 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000264 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
265 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
266 void evictInterference(LiveInterval&, unsigned,
267 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000268
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000269 unsigned tryAssign(LiveInterval&, AllocationOrder&,
270 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000271 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000272 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000273 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
274 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000275 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000277 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
278 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000279 unsigned trySplit(LiveInterval&, AllocationOrder&,
280 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000281};
282} // end anonymous namespace
283
284char RAGreedy::ID = 0;
285
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000286#ifndef NDEBUG
287const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000288 "RS_New",
289 "RS_Assign",
290 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000291 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000292 "RS_Spill",
293 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000294};
295#endif
296
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000297// Hysteresis to use when comparing floats.
298// This helps stabilize decisions based on float comparisons.
299const float Hysteresis = 0.98f;
300
301
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000302FunctionPass* llvm::createGreedyRegisterAllocator() {
303 return new RAGreedy();
304}
305
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000306RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000307 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000308 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000309 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
310 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
311 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000312 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000313 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
314 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
315 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
316 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
317 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000318 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
319 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000320}
321
322void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
323 AU.setPreservesCFG();
324 AU.addRequired<AliasAnalysis>();
325 AU.addPreserved<AliasAnalysis>();
326 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000327 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000328 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000329 AU.addRequired<LiveDebugVariables>();
330 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000331 if (StrongPHIElim)
332 AU.addRequiredID(StrongPHIEliminationID);
Jakob Stoklund Olesen27215672011-08-09 00:29:53 +0000333 AU.addRequiredTransitiveID(RegisterCoalescerPassID);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000334 AU.addRequired<CalculateSpillWeights>();
335 AU.addRequired<LiveStacks>();
336 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000337 AU.addRequired<MachineDominatorTree>();
338 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000339 AU.addRequired<MachineLoopInfo>();
340 AU.addPreserved<MachineLoopInfo>();
341 AU.addRequired<VirtRegMap>();
342 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000343 AU.addRequired<EdgeBundles>();
344 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000345 MachineFunctionPass::getAnalysisUsage(AU);
346}
347
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000348
349//===----------------------------------------------------------------------===//
350// LiveRangeEdit delegate methods
351//===----------------------------------------------------------------------===//
352
353void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
354 // LRE itself will remove from SlotIndexes and parent basic block.
355 VRM->RemoveMachineInstrFromMaps(MI);
356}
357
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000358bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
359 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
360 unassign(LIS->getInterval(VirtReg), PhysReg);
361 return true;
362 }
363 // Unassigned virtreg is probably in the priority queue.
364 // RegAllocBase will erase it after dequeueing.
365 return false;
366}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000367
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000368void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
369 unsigned PhysReg = VRM->getPhys(VirtReg);
370 if (!PhysReg)
371 return;
372
373 // Register is assigned, put it back on the queue for reassignment.
374 LiveInterval &LI = LIS->getInterval(VirtReg);
375 unassign(LI, PhysReg);
376 enqueue(&LI);
377}
378
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000379void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000380 // Cloning a register we haven't even heard about yet? Just ignore it.
381 if (!ExtraRegInfo.inBounds(Old))
382 return;
383
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000384 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000385 // be split into connected components. The new components are much smaller
386 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000387 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000388 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000389 ExtraRegInfo.grow(New);
390 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000391}
392
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000393void RAGreedy::releaseMemory() {
394 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000395 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000396 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000397 RegAllocBase::releaseMemory();
398}
399
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000400void RAGreedy::enqueue(LiveInterval *LI) {
401 // Prioritize live ranges by size, assigning larger ranges first.
402 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000403 const unsigned Size = LI->getSize();
404 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000405 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
406 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000407 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000408
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000409 ExtraRegInfo.grow(Reg);
410 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000411 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000412
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000413 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000414 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000415 // everything else has been allocated.
416 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000417 } else {
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000418 // Everything is allocated in long->short order. Long ranges that don't fit
419 // should be spilled (or split) ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000420 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000421
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000422 // Boost ranges that have a physical register hint.
423 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
424 Prio |= (1u << 30);
425 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000426
427 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000428}
429
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000430LiveInterval *RAGreedy::dequeue() {
431 if (Queue.empty())
432 return 0;
433 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
434 Queue.pop();
435 return LI;
436}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000437
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000438
439//===----------------------------------------------------------------------===//
440// Direct Assignment
441//===----------------------------------------------------------------------===//
442
443/// tryAssign - Try to assign VirtReg to an available register.
444unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
445 AllocationOrder &Order,
446 SmallVectorImpl<LiveInterval*> &NewVRegs) {
447 Order.rewind();
448 unsigned PhysReg;
449 while ((PhysReg = Order.next()))
450 if (!checkPhysRegInterference(VirtReg, PhysReg))
451 break;
452 if (!PhysReg || Order.isHint(PhysReg))
453 return PhysReg;
454
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000455 // PhysReg is available, but there may be a better choice.
456
457 // If we missed a simple hint, try to cheaply evict interference from the
458 // preferred register.
459 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
460 if (Order.isHint(Hint)) {
461 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
462 EvictionCost MaxCost(1);
463 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
464 evictInterference(VirtReg, Hint, NewVRegs);
465 return Hint;
466 }
467 }
468
469 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000470 unsigned Cost = TRI->getCostPerUse(PhysReg);
471
472 // Most registers have 0 additional cost.
473 if (!Cost)
474 return PhysReg;
475
476 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
477 << '\n');
478 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
479 return CheapReg ? CheapReg : PhysReg;
480}
481
482
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000483//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000484// Interference eviction
485//===----------------------------------------------------------------------===//
486
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000487/// shouldEvict - determine if A should evict the assigned live range B. The
488/// eviction policy defined by this function together with the allocation order
489/// defined by enqueue() decides which registers ultimately end up being split
490/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000491///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000492/// Cascade numbers are used to prevent infinite loops if this function is a
493/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000494///
495/// @param A The live range to be assigned.
496/// @param IsHint True when A is about to be assigned to its preferred
497/// register.
498/// @param B The live range to be evicted.
499/// @param BreaksHint True when B is already assigned to its preferred register.
500bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
501 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000502 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000503
504 // Be fairly aggressive about following hints as long as the evictee can be
505 // split.
506 if (CanSplit && IsHint && !BreaksHint)
507 return true;
508
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000509 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000510}
511
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000512/// canEvictInterference - Return true if all interferences between VirtReg and
513/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
514///
515/// @param VirtReg Live range that is about to be assigned.
516/// @param PhysReg Desired register for assignment.
517/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
518/// @param MaxCost Only look for cheaper candidates and update with new cost
519/// when returning true.
520/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000521bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000522 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000523 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
524 // involved in an eviction before. If a cascade number was assigned, deny
525 // evicting anything with the same or a newer cascade number. This prevents
526 // infinite eviction loops.
527 //
528 // This works out so a register without a cascade number is allowed to evict
529 // anything, and it can be evicted by anything.
530 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
531 if (!Cascade)
532 Cascade = NextCascade;
533
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000534 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000535 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
536 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000537 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000538 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000539 return false;
540
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000541 // Check if any interfering live range is heavier than MaxWeight.
542 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
543 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000544 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
545 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000546 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000547 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000548 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000549 // Once a live range becomes small enough, it is urgent that we find a
550 // register for it. This is indicated by an infinite spill weight. These
551 // urgent live ranges get to evict almost anything.
552 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
553 // Only evict older cascades or live ranges without a cascade.
554 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
555 if (Cascade <= IntfCascade) {
556 if (!Urgent)
557 return false;
558 // We permit breaking cascades for urgent evictions. It should be the
559 // last resort, though, so make it really expensive.
560 Cost.BrokenHints += 10;
561 }
562 // Would this break a satisfied hint?
563 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
564 // Update eviction cost.
565 Cost.BrokenHints += BreaksHint;
566 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
567 // Abort if this would be too expensive.
568 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000569 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000570 // Finally, apply the eviction policy for non-urgent evictions.
571 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000572 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000573 }
574 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000575 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000576 return true;
577}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000578
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000579/// evictInterference - Evict any interferring registers that prevent VirtReg
580/// from being assigned to Physreg. This assumes that canEvictInterference
581/// returned true.
582void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
583 SmallVectorImpl<LiveInterval*> &NewVRegs) {
584 // Make sure that VirtReg has a cascade number, and assign that cascade
585 // number to every evicted register. These live ranges than then only be
586 // evicted by a newer cascade, preventing infinite loops.
587 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
588 if (!Cascade)
589 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
590
591 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
592 << " interference: Cascade " << Cascade << '\n');
593 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
594 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
595 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
596 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
597 LiveInterval *Intf = Q.interferingVRegs()[i];
598 unassign(*Intf, VRM->getPhys(Intf->reg));
599 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
600 VirtReg.isSpillable() < Intf->isSpillable()) &&
601 "Cannot decrease cascade number, illegal eviction");
602 ExtraRegInfo[Intf->reg].Cascade = Cascade;
603 ++NumEvicted;
604 NewVRegs.push_back(Intf);
605 }
606 }
607}
608
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000609/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000610/// @param VirtReg Currently unassigned virtual register.
611/// @param Order Physregs to try.
612/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000613unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
614 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000615 SmallVectorImpl<LiveInterval*> &NewVRegs,
616 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000617 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
618
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000619 // Keep track of the cheapest interference seen so far.
620 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000621 unsigned BestPhys = 0;
622
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000623 // When we are just looking for a reduced cost per use, don't break any
624 // hints, and only evict smaller spill weights.
625 if (CostPerUseLimit < ~0u) {
626 BestCost.BrokenHints = 0;
627 BestCost.MaxWeight = VirtReg.weight;
628 }
629
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000630 Order.rewind();
631 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000632 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
633 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000634 // The first use of a callee-saved register in a function has cost 1.
635 // Don't start using a CSR when the CostPerUseLimit is low.
636 if (CostPerUseLimit == 1)
637 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
638 if (!MRI->isPhysRegUsed(CSR)) {
639 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
640 << PrintReg(CSR, TRI) << '\n');
641 continue;
642 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000643
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000644 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000645 continue;
646
647 // Best so far.
648 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000649
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000650 // Stop if the hint can be used.
651 if (Order.isHint(PhysReg))
652 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000653 }
654
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000655 if (!BestPhys)
656 return 0;
657
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000658 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000659 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000660}
661
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000662
663//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000664// Region Splitting
665//===----------------------------------------------------------------------===//
666
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000667/// addSplitConstraints - Fill out the SplitConstraints vector based on the
668/// interference pattern in Physreg and its aliases. Add the constraints to
669/// SpillPlacement and return the static cost of this split in Cost, assuming
670/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000671/// Return false if there are no bundles with positive bias.
672bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
673 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000674 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000675
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000676 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000677 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000678 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000679 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
680 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000681 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000682
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000683 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000684 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000685 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
686 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000687 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000688
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000689 if (!Intf.hasInterference())
690 continue;
691
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000692 // Number of spill code instructions to insert.
693 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000694
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000695 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000696 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000697 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000698 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000699 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000700 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000701 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000702 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000703 }
704
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000705 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000706 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000707 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000708 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000709 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000710 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000711 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000712 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000713 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000714
715 // Accumulate the total frequency of inserted spill code.
716 if (Ins)
717 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000718 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000719 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000720
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000721 // Add constraints for use-blocks. Note that these are the only constraints
722 // that may add a positive bias, it is downhill from here.
723 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000724 return SpillPlacer->scanActiveBundles();
725}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000726
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000727
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000728/// addThroughConstraints - Add constraints and links to SpillPlacer from the
729/// live-through blocks in Blocks.
730void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
731 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000732 const unsigned GroupSize = 8;
733 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000734 unsigned TBS[GroupSize];
735 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000736
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000737 for (unsigned i = 0; i != Blocks.size(); ++i) {
738 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000739 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000740
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000741 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000742 assert(T < GroupSize && "Array overflow");
743 TBS[T] = Number;
744 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000745 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000746 T = 0;
747 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000748 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000749 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000750
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000751 assert(B < GroupSize && "Array overflow");
752 BCS[B].Number = Number;
753
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000754 // Interference for the live-in value.
755 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
756 BCS[B].Entry = SpillPlacement::MustSpill;
757 else
758 BCS[B].Entry = SpillPlacement::PrefSpill;
759
760 // Interference for the live-out value.
761 if (Intf.last() >= SA->getLastSplitPoint(Number))
762 BCS[B].Exit = SpillPlacement::MustSpill;
763 else
764 BCS[B].Exit = SpillPlacement::PrefSpill;
765
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000766 if (++B == GroupSize) {
767 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
768 SpillPlacer->addConstraints(Array);
769 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000770 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000771 }
772
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000773 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
774 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000775 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000776}
777
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000778void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000779 // Keep track of through blocks that have not been added to SpillPlacer.
780 BitVector Todo = SA->getThroughBlocks();
781 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
782 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000783#ifndef NDEBUG
784 unsigned Visited = 0;
785#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000786
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000787 for (;;) {
788 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000789 // Find new through blocks in the periphery of PrefRegBundles.
790 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
791 unsigned Bundle = NewBundles[i];
792 // Look at all blocks connected to Bundle in the full graph.
793 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
794 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
795 I != E; ++I) {
796 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000797 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000798 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000799 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000800 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000801 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000802#ifndef NDEBUG
803 ++Visited;
804#endif
805 }
806 }
807 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000808 if (ActiveBlocks.size() == AddedTo)
809 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000810
811 // Compute through constraints from the interference, or assume that all
812 // through blocks prefer spilling when forming compact regions.
813 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
814 if (Cand.PhysReg)
815 addThroughConstraints(Cand.Intf, NewBlocks);
816 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000817 // Provide a strong negative bias on through blocks to prevent unwanted
818 // liveness on loop backedges.
819 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000820 AddedTo = ActiveBlocks.size();
821
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000822 // Perhaps iterating can enable more bundles?
823 SpillPlacer->iterate();
824 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000825 DEBUG(dbgs() << ", v=" << Visited);
826}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000827
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000828/// calcCompactRegion - Compute the set of edge bundles that should be live
829/// when splitting the current live range into compact regions. Compact
830/// regions can be computed without looking at interference. They are the
831/// regions formed by removing all the live-through blocks from the live range.
832///
833/// Returns false if the current live range is already compact, or if the
834/// compact regions would form single block regions anyway.
835bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
836 // Without any through blocks, the live range is already compact.
837 if (!SA->getNumThroughBlocks())
838 return false;
839
840 // Compact regions don't correspond to any physreg.
841 Cand.reset(IntfCache, 0);
842
843 DEBUG(dbgs() << "Compact region bundles");
844
845 // Use the spill placer to determine the live bundles. GrowRegion pretends
846 // that all the through blocks have interference when PhysReg is unset.
847 SpillPlacer->prepare(Cand.LiveBundles);
848
849 // The static split cost will be zero since Cand.Intf reports no interference.
850 float Cost;
851 if (!addSplitConstraints(Cand.Intf, Cost)) {
852 DEBUG(dbgs() << ", none.\n");
853 return false;
854 }
855
856 growRegion(Cand);
857 SpillPlacer->finish();
858
859 if (!Cand.LiveBundles.any()) {
860 DEBUG(dbgs() << ", none.\n");
861 return false;
862 }
863
864 DEBUG({
865 for (int i = Cand.LiveBundles.find_first(); i>=0;
866 i = Cand.LiveBundles.find_next(i))
867 dbgs() << " EB#" << i;
868 dbgs() << ".\n";
869 });
870 return true;
871}
872
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000873/// calcSpillCost - Compute how expensive it would be to split the live range in
874/// SA around all use blocks instead of forming bundle regions.
875float RAGreedy::calcSpillCost() {
876 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000877 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
878 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
879 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
880 unsigned Number = BI.MBB->getNumber();
881 // We normally only need one spill instruction - a load or a store.
882 Cost += SpillPlacer->getBlockFrequency(Number);
883
884 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000885 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
886 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000887 }
888 return Cost;
889}
890
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000891/// calcGlobalSplitCost - Return the global split cost of following the split
892/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000893/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000894///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000895float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000896 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000897 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000898 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
899 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
900 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000901 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000902 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
903 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
904 unsigned Ins = 0;
905
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000906 if (BI.LiveIn)
907 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
908 if (BI.LiveOut)
909 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000910 if (Ins)
911 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000912 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000913
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000914 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
915 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000916 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
917 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000918 if (!RegIn && !RegOut)
919 continue;
920 if (RegIn && RegOut) {
921 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000922 Cand.Intf.moveToBlock(Number);
923 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000924 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
925 continue;
926 }
927 // live-in / stack-out or stack-in live-out.
928 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000929 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000930 return GlobalCost;
931}
932
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000933/// splitAroundRegion - Split the current live range around the regions
934/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000935///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000936/// Before calling this function, GlobalCand and BundleCand must be initialized
937/// so each bundle is assigned to a valid candidate, or NoCand for the
938/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
939/// objects must be initialized for the current live range, and intervals
940/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000941///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000942/// @param LREdit The LiveRangeEdit object handling the current split.
943/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
944/// must appear in this list.
945void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
946 ArrayRef<unsigned> UsedCands) {
947 // These are the intervals created for new global ranges. We may create more
948 // intervals for local ranges.
949 const unsigned NumGlobalIntvs = LREdit.size();
950 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
951 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000952
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000953 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +0000954 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000955 // is all copies.
956 unsigned Reg = SA->getParent().reg;
957 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
958
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000959 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000960 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
961 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
962 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000963 unsigned Number = BI.MBB->getNumber();
964 unsigned IntvIn = 0, IntvOut = 0;
965 SlotIndex IntfIn, IntfOut;
966 if (BI.LiveIn) {
967 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
968 if (CandIn != NoCand) {
969 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
970 IntvIn = Cand.IntvIdx;
971 Cand.Intf.moveToBlock(Number);
972 IntfIn = Cand.Intf.first();
973 }
974 }
975 if (BI.LiveOut) {
976 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
977 if (CandOut != NoCand) {
978 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
979 IntvOut = Cand.IntvIdx;
980 Cand.Intf.moveToBlock(Number);
981 IntfOut = Cand.Intf.last();
982 }
983 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000984
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000985 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000986 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000987 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000988 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000989 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000990 continue;
991 }
992
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000993 if (IntvIn && IntvOut)
994 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
995 else if (IntvIn)
996 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000997 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000998 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000999 }
1000
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001001 // Handle live-through blocks. The relevant live-through blocks are stored in
1002 // the ActiveBlocks list with each candidate. We need to filter out
1003 // duplicates.
1004 BitVector Todo = SA->getThroughBlocks();
1005 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1006 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1007 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1008 unsigned Number = Blocks[i];
1009 if (!Todo.test(Number))
1010 continue;
1011 Todo.reset(Number);
1012
1013 unsigned IntvIn = 0, IntvOut = 0;
1014 SlotIndex IntfIn, IntfOut;
1015
1016 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1017 if (CandIn != NoCand) {
1018 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1019 IntvIn = Cand.IntvIdx;
1020 Cand.Intf.moveToBlock(Number);
1021 IntfIn = Cand.Intf.first();
1022 }
1023
1024 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1025 if (CandOut != NoCand) {
1026 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1027 IntvOut = Cand.IntvIdx;
1028 Cand.Intf.moveToBlock(Number);
1029 IntfOut = Cand.Intf.last();
1030 }
1031 if (!IntvIn && !IntvOut)
1032 continue;
1033 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1034 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001035 }
1036
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001037 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001038
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001039 SmallVector<unsigned, 8> IntvMap;
1040 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001041 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001042
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001043 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001044 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001045
1046 // Sort out the new intervals created by splitting. We get four kinds:
1047 // - Remainder intervals should not be split again.
1048 // - Candidate intervals can be assigned to Cand.PhysReg.
1049 // - Block-local splits are candidates for local splitting.
1050 // - DCE leftovers should go back on the queue.
1051 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001052 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001053
1054 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001055 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001056 continue;
1057
1058 // Remainder interval. Don't try splitting again, spill if it doesn't
1059 // allocate.
1060 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001061 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001062 continue;
1063 }
1064
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001065 // Global intervals. Allow repeated splitting as long as the number of live
1066 // blocks is strictly decreasing.
1067 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001068 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001069 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1070 << " blocks as original.\n");
1071 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001072 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001073 }
1074 continue;
1075 }
1076
1077 // Other intervals are treated as new. This includes local intervals created
1078 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001079 }
1080
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001081 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001082 MF->verify(this, "After splitting live range around region");
1083}
1084
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001085unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1086 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001087 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001088 unsigned BestCand = NoCand;
1089 float BestCost;
1090 SmallVector<unsigned, 8> UsedCands;
1091
1092 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001093 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001094 if (HasCompact) {
1095 // Yes, keep GlobalCand[0] as the compact region candidate.
1096 NumCands = 1;
1097 BestCost = HUGE_VALF;
1098 } else {
1099 // No benefit from the compact region, our fallback will be per-block
1100 // splitting. Make sure we find a solution that is cheaper than spilling.
1101 BestCost = Hysteresis * calcSpillCost();
1102 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1103 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001104
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001105 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001106 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001107 // Discard bad candidates before we run out of interference cache cursors.
1108 // This will only affect register classes with a lot of registers (>32).
1109 if (NumCands == IntfCache.getMaxCursors()) {
1110 unsigned WorstCount = ~0u;
1111 unsigned Worst = 0;
1112 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001113 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001114 continue;
1115 unsigned Count = GlobalCand[i].LiveBundles.count();
1116 if (Count < WorstCount)
1117 Worst = i, WorstCount = Count;
1118 }
1119 --NumCands;
1120 GlobalCand[Worst] = GlobalCand[NumCands];
1121 }
1122
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001123 if (GlobalCand.size() <= NumCands)
1124 GlobalCand.resize(NumCands+1);
1125 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1126 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001127
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001128 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001129 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001130 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001131 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001132 continue;
1133 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001134 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001135 if (Cost >= BestCost) {
1136 DEBUG({
1137 if (BestCand == NoCand)
1138 dbgs() << " worse than no bundles\n";
1139 else
1140 dbgs() << " worse than "
1141 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1142 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001143 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001144 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001145 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001146
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001147 SpillPlacer->finish();
1148
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001149 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001150 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001151 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001152 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001153 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001154
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001155 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001156 DEBUG({
1157 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001158 for (int i = Cand.LiveBundles.find_first(); i>=0;
1159 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001160 dbgs() << " EB#" << i;
1161 dbgs() << ".\n";
1162 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001163 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001164 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001165 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001166 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001167 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001168 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001169
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001170 // No solutions found, fall back to single block splitting.
1171 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001172 return 0;
1173
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001174 // Prepare split editor.
1175 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001176 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001177
1178 // Assign all edge bundles to the preferred candidate, or NoCand.
1179 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1180
1181 // Assign bundles for the best candidate region.
1182 if (BestCand != NoCand) {
1183 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1184 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1185 UsedCands.push_back(BestCand);
1186 Cand.IntvIdx = SE->openIntv();
1187 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1188 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001189 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001190 }
1191 }
1192
1193 // Assign bundles for the compact region.
1194 if (HasCompact) {
1195 GlobalSplitCandidate &Cand = GlobalCand.front();
1196 assert(!Cand.PhysReg && "Compact region has no physreg");
1197 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1198 UsedCands.push_back(0);
1199 Cand.IntvIdx = SE->openIntv();
1200 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1201 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001202 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001203 }
1204 }
1205
1206 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001207 return 0;
1208}
1209
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001210
1211//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001212// Per-Block Splitting
1213//===----------------------------------------------------------------------===//
1214
1215/// tryBlockSplit - Split a global live range around every block with uses. This
1216/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1217/// they don't allocate.
1218unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1219 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1220 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1221 unsigned Reg = VirtReg.reg;
1222 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1223 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001224 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001225 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1226 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1227 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1228 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1229 SE->splitSingleBlock(BI);
1230 }
1231 // No blocks were split.
1232 if (LREdit.empty())
1233 return 0;
1234
1235 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001236 SmallVector<unsigned, 8> IntvMap;
1237 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001238
1239 // Tell LiveDebugVariables about the new ranges.
1240 DebugVars->splitRegister(Reg, LREdit.regs());
1241
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001242 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1243
1244 // Sort out the new intervals created by splitting. The remainder interval
1245 // goes straight to spilling, the new local ranges get to stay RS_New.
1246 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1247 LiveInterval &LI = *LREdit.get(i);
1248 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1249 setStage(LI, RS_Spill);
1250 }
1251
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001252 if (VerifyEnabled)
1253 MF->verify(this, "After splitting live range around basic blocks");
1254 return 0;
1255}
1256
1257//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001258// Local Splitting
1259//===----------------------------------------------------------------------===//
1260
1261
1262/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1263/// in order to use PhysReg between two entries in SA->UseSlots.
1264///
1265/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1266///
1267void RAGreedy::calcGapWeights(unsigned PhysReg,
1268 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001269 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1270 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001271 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1272 const unsigned NumGaps = Uses.size()-1;
1273
1274 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001275 SlotIndex StartIdx =
1276 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1277 SlotIndex StopIdx =
1278 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001279
1280 GapWeight.assign(NumGaps, 0.0f);
1281
1282 // Add interference from each overlapping register.
1283 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1284 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1285 .checkInterference())
1286 continue;
1287
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001288 // We know that VirtReg is a continuous interval from FirstInstr to
1289 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001290 //
1291 // Interference that overlaps an instruction is counted in both gaps
1292 // surrounding the instruction. The exception is interference before
1293 // StartIdx and after StopIdx.
1294 //
1295 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1296 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1297 // Skip the gaps before IntI.
1298 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1299 if (++Gap == NumGaps)
1300 break;
1301 if (Gap == NumGaps)
1302 break;
1303
1304 // Update the gaps covered by IntI.
1305 const float weight = IntI.value()->weight;
1306 for (; Gap != NumGaps; ++Gap) {
1307 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1308 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1309 break;
1310 }
1311 if (Gap == NumGaps)
1312 break;
1313 }
1314 }
1315}
1316
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001317/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1318/// basic block.
1319///
1320unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1321 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001322 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1323 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001324
1325 // Note that it is possible to have an interval that is live-in or live-out
1326 // while only covering a single block - A phi-def can use undef values from
1327 // predecessors, and the block could be a single-block loop.
1328 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001329 // that the interval is continuous from FirstInstr to LastInstr. We should
1330 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001331
1332 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1333 if (Uses.size() <= 2)
1334 return 0;
1335 const unsigned NumGaps = Uses.size()-1;
1336
1337 DEBUG({
1338 dbgs() << "tryLocalSplit: ";
1339 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1340 dbgs() << ' ' << SA->UseSlots[i];
1341 dbgs() << '\n';
1342 });
1343
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001344 // Since we allow local split results to be split again, there is a risk of
1345 // creating infinite loops. It is tempting to require that the new live
1346 // ranges have less instructions than the original. That would guarantee
1347 // convergence, but it is too strict. A live range with 3 instructions can be
1348 // split 2+3 (including the COPY), and we want to allow that.
1349 //
1350 // Instead we use these rules:
1351 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001352 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001353 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001354 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001355 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001356 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001357 // smaller ranges are marked RS_New.
1358 //
1359 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1360 // excessive splitting and infinite loops.
1361 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001362 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001363
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001364 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001365 unsigned BestBefore = NumGaps;
1366 unsigned BestAfter = 0;
1367 float BestDiff = 0;
1368
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001369 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001370 SmallVector<float, 8> GapWeight;
1371
1372 Order.rewind();
1373 while (unsigned PhysReg = Order.next()) {
1374 // Keep track of the largest spill weight that would need to be evicted in
1375 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1376 calcGapWeights(PhysReg, GapWeight);
1377
1378 // Try to find the best sequence of gaps to close.
1379 // The new spill weight must be larger than any gap interference.
1380
1381 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001382 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001383
1384 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1385 // It is the spill weight that needs to be evicted.
1386 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001387
1388 for (;;) {
1389 // Live before/after split?
1390 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1391 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1392
1393 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1394 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1395 << " i=" << MaxGap);
1396
1397 // Stop before the interval gets so big we wouldn't be making progress.
1398 if (!LiveBefore && !LiveAfter) {
1399 DEBUG(dbgs() << " all\n");
1400 break;
1401 }
1402 // Should the interval be extended or shrunk?
1403 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001404
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001405 // How many gaps would the new range have?
1406 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1407
1408 // Legally, without causing looping?
1409 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1410
1411 if (Legal && MaxGap < HUGE_VALF) {
1412 // Estimate the new spill weight. Each instruction reads or writes the
1413 // register. Conservatively assume there are no read-modify-write
1414 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001415 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001416 // Try to guess the size of the new interval.
1417 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1418 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1419 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001420 // Would this split be possible to allocate?
1421 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001422 DEBUG(dbgs() << " w=" << EstWeight);
1423 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001424 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001425 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001426 if (Diff > BestDiff) {
1427 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001428 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001429 BestBefore = SplitBefore;
1430 BestAfter = SplitAfter;
1431 }
1432 }
1433 }
1434
1435 // Try to shrink.
1436 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001437 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001438 DEBUG(dbgs() << " shrink\n");
1439 // Recompute the max when necessary.
1440 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1441 MaxGap = GapWeight[SplitBefore];
1442 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1443 MaxGap = std::max(MaxGap, GapWeight[i]);
1444 }
1445 continue;
1446 }
1447 MaxGap = 0;
1448 }
1449
1450 // Try to extend the interval.
1451 if (SplitAfter >= NumGaps) {
1452 DEBUG(dbgs() << " end\n");
1453 break;
1454 }
1455
1456 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001457 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001458 }
1459 }
1460
1461 // Didn't find any candidates?
1462 if (BestBefore == NumGaps)
1463 return 0;
1464
1465 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1466 << '-' << Uses[BestAfter] << ", " << BestDiff
1467 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1468
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001469 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001470 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001471
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001472 SE->openIntv();
1473 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1474 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1475 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001476 SmallVector<unsigned, 8> IntvMap;
1477 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001478 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001479
1480 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001481 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001482 // leave the new intervals as RS_New so they can compete.
1483 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1484 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1485 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1486 if (NewGaps >= NumGaps) {
1487 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1488 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001489 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1490 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001491 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001492 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1493 }
1494 DEBUG(dbgs() << '\n');
1495 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001496 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001497
1498 return 0;
1499}
1500
1501//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001502// Live Range Splitting
1503//===----------------------------------------------------------------------===//
1504
1505/// trySplit - Try to split VirtReg or one of its interferences, making it
1506/// assignable.
1507/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1508unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1509 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001510 // Ranges must be Split2 or less.
1511 if (getStage(VirtReg) >= RS_Spill)
1512 return 0;
1513
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001514 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001515 if (LIS->intervalIsInOneMBB(VirtReg)) {
1516 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001517 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001518 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001519 }
1520
1521 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001522
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001523 SA->analyze(&VirtReg);
1524
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001525 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1526 // coalescer. That may cause the range to become allocatable which means that
1527 // tryRegionSplit won't be making progress. This check should be replaced with
1528 // an assertion when the coalescer is fixed.
1529 if (SA->didRepairRange()) {
1530 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001531 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001532 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1533 return PhysReg;
1534 }
1535
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001536 // First try to split around a region spanning multiple blocks. RS_Split2
1537 // ranges already made dubious progress with region splitting, so they go
1538 // straight to single block splitting.
1539 if (getStage(VirtReg) < RS_Split2) {
1540 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1541 if (PhysReg || !NewVRegs.empty())
1542 return PhysReg;
1543 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001544
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001545 // Then isolate blocks.
1546 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001547}
1548
1549
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001550//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001551// Main Entry Point
1552//===----------------------------------------------------------------------===//
1553
1554unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001555 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001556 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001557 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001558 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1559 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001560
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001561 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001562 DEBUG(dbgs() << StageName[Stage]
1563 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001564
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001565 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001566 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001567 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001568 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001569 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1570 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001571
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001572 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1573
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001574 // The first time we see a live range, don't try to split or spill.
1575 // Wait until the second time, when all smaller ranges have been allocated.
1576 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001577 if (Stage < RS_Split) {
1578 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001579 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001580 NewVRegs.push_back(&VirtReg);
1581 return 0;
1582 }
1583
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001584 // If we couldn't allocate a register from spilling, there is probably some
1585 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001586 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001587 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001588
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001589 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001590 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1591 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001592 return PhysReg;
1593
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001594 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001595 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001596 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1597 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001598 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001599
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001600 if (VerifyEnabled)
1601 MF->verify(this, "After spilling");
1602
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001603 // The live virtual register requesting allocation was spilled, so tell
1604 // the caller not to allocate anything during this round.
1605 return 0;
1606}
1607
1608bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1609 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1610 << "********** Function: "
1611 << ((Value*)mf.getFunction())->getName() << '\n');
1612
1613 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001614 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001615 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001616
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001617 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001618 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001619 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001620 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001621 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001622 Bundles = &getAnalysis<EdgeBundles>();
1623 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001624 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001625
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001626 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001627 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001628 ExtraRegInfo.clear();
1629 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1630 NextCascade = 1;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001631 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001632 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001633
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001634 allocatePhysRegs();
1635 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001636 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001637
1638 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001639 {
1640 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001641 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001642 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001643
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001644 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenc4769022011-07-31 03:53:42 +00001645 {
1646 NamedRegionTimer T("Emit Debug Info", TimerGroupName, TimePassesIsEnabled);
1647 DebugVars->emitDebugValues(VRM);
1648 }
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001649
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001650 // The pass output is in VirtRegMap. Release all the transient data.
1651 releaseMemory();
1652
1653 return true;
1654}