blob: 474594e796561a19f89e1e7d69b03b66a50f85af [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
Benjamin Kramera67f14b2011-08-19 01:42:18 +000054static cl::opt<bool> CompactRegions("compact-regions", cl::init(true));
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000055
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000056static cl::opt<SplitEditor::ComplementSpillMode>
57SplitSpillMode("split-spill-mode", cl::Hidden,
58 cl::desc("Spill mode for splitting live ranges"),
59 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
60 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
61 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
62 clEnumValEnd),
63 cl::init(SplitEditor::SM_Partition));
64
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000065static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
66 createGreedyRegisterAllocator);
67
68namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000069class RAGreedy : public MachineFunctionPass,
70 public RegAllocBase,
71 private LiveRangeEdit::Delegate {
72
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000073 // context
74 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000075
76 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000077 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000078 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000079 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000080 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000081 EdgeBundles *Bundles;
82 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000083 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000084
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000085 // state
86 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000087 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000088 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000089
90 // Live ranges pass through a number of stages as we try to allocate them.
91 // Some of the stages may also create new live ranges:
92 //
93 // - Region splitting.
94 // - Per-block splitting.
95 // - Local splitting.
96 // - Spilling.
97 //
98 // Ranges produced by one of the stages skip the previous stages when they are
99 // dequeued. This improves performance because we can skip interference checks
100 // that are unlikely to give any results. It also guarantees that the live
101 // range splitting algorithm terminates, something that is otherwise hard to
102 // ensure.
103 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000104 /// Newly created live range that has never been queued.
105 RS_New,
106
107 /// Only attempt assignment and eviction. Then requeue as RS_Split.
108 RS_Assign,
109
110 /// Attempt live range splitting if assignment is impossible.
111 RS_Split,
112
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000113 /// Attempt more aggressive live range splitting that is guaranteed to make
114 /// progress. This is used for split products that may not be making
115 /// progress.
116 RS_Split2,
117
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000118 /// Live range will be spilled. No more splitting will be attempted.
119 RS_Spill,
120
121 /// There is nothing more we can do to this live range. Abort compilation
122 /// if it can't be assigned.
123 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000124 };
125
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000126 static const char *const StageName[];
127
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000128 // RegInfo - Keep additional information about each live range.
129 struct RegInfo {
130 LiveRangeStage Stage;
131
132 // Cascade - Eviction loop prevention. See canEvictInterference().
133 unsigned Cascade;
134
135 RegInfo() : Stage(RS_New), Cascade(0) {}
136 };
137
138 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000139
140 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000141 return ExtraRegInfo[VirtReg.reg].Stage;
142 }
143
144 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
145 ExtraRegInfo.resize(MRI->getNumVirtRegs());
146 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000147 }
148
149 template<typename Iterator>
150 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000151 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000152 for (;Begin != End; ++Begin) {
153 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000154 if (ExtraRegInfo[Reg].Stage == RS_New)
155 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000156 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000157 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000158
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000159 /// Cost of evicting interference.
160 struct EvictionCost {
161 unsigned BrokenHints; ///< Total number of broken hints.
162 float MaxWeight; ///< Maximum spill weight evicted.
163
164 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
165
166 bool operator<(const EvictionCost &O) const {
167 if (BrokenHints != O.BrokenHints)
168 return BrokenHints < O.BrokenHints;
169 return MaxWeight < O.MaxWeight;
170 }
171 };
172
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000173 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000174 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000175 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000176
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000177 /// Cached per-block interference maps
178 InterferenceCache IntfCache;
179
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000180 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000181 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000182
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000183 /// Global live range splitting candidate info.
184 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000185 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000186 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000187
188 // SplitKit interval index for this candidate.
189 unsigned IntvIdx;
190
191 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000192 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000193
194 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000195 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000196 SmallVector<unsigned, 8> ActiveBlocks;
197
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000198 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000199 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000200 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000201 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000202 LiveBundles.clear();
203 ActiveBlocks.clear();
204 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000205
206 // Set B[i] = C for every live bundle where B[i] was NoCand.
207 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
208 unsigned Count = 0;
209 for (int i = LiveBundles.find_first(); i >= 0;
210 i = LiveBundles.find_next(i))
211 if (B[i] == NoCand) {
212 B[i] = C;
213 Count++;
214 }
215 return Count;
216 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000217 };
218
219 /// Candidate info for for each PhysReg in AllocationOrder.
220 /// This vector never shrinks, but grows to the size of the largest register
221 /// class.
222 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
223
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000224 enum { NoCand = ~0u };
225
226 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
227 /// NoCand which indicates the stack interval.
228 SmallVector<unsigned, 32> BundleCand;
229
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000230public:
231 RAGreedy();
232
233 /// Return the pass name.
234 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000235 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000236 }
237
238 /// RAGreedy analysis usage.
239 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000240 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000241 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000242 virtual void enqueue(LiveInterval *LI);
243 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000244 virtual unsigned selectOrSplit(LiveInterval&,
245 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000246
247 /// Perform register allocation.
248 virtual bool runOnMachineFunction(MachineFunction &mf);
249
250 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000251
252private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000253 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000254 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000255 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000256 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000257
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000258 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000259 bool addSplitConstraints(InterferenceCache::Cursor, float&);
260 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000261 void growRegion(GlobalSplitCandidate &Cand);
262 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000263 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000264 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000265 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000266 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
267 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
268 void evictInterference(LiveInterval&, unsigned,
269 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000270
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000271 unsigned tryAssign(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000273 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000274 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000275 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000277 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
278 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000279 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
280 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000281 unsigned trySplit(LiveInterval&, AllocationOrder&,
282 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000283};
284} // end anonymous namespace
285
286char RAGreedy::ID = 0;
287
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000288#ifndef NDEBUG
289const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000290 "RS_New",
291 "RS_Assign",
292 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000293 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000294 "RS_Spill",
295 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000296};
297#endif
298
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000299// Hysteresis to use when comparing floats.
300// This helps stabilize decisions based on float comparisons.
301const float Hysteresis = 0.98f;
302
303
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000304FunctionPass* llvm::createGreedyRegisterAllocator() {
305 return new RAGreedy();
306}
307
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000308RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000309 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000310 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000311 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
312 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
313 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000314 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000315 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
316 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
317 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
318 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
319 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000320 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
321 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000322}
323
324void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
325 AU.setPreservesCFG();
326 AU.addRequired<AliasAnalysis>();
327 AU.addPreserved<AliasAnalysis>();
328 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000329 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000330 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000331 AU.addRequired<LiveDebugVariables>();
332 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000333 if (StrongPHIElim)
334 AU.addRequiredID(StrongPHIEliminationID);
Jakob Stoklund Olesen27215672011-08-09 00:29:53 +0000335 AU.addRequiredTransitiveID(RegisterCoalescerPassID);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000336 AU.addRequired<CalculateSpillWeights>();
337 AU.addRequired<LiveStacks>();
338 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000339 AU.addRequired<MachineDominatorTree>();
340 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000341 AU.addRequired<MachineLoopInfo>();
342 AU.addPreserved<MachineLoopInfo>();
343 AU.addRequired<VirtRegMap>();
344 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000345 AU.addRequired<EdgeBundles>();
346 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000347 MachineFunctionPass::getAnalysisUsage(AU);
348}
349
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000350
351//===----------------------------------------------------------------------===//
352// LiveRangeEdit delegate methods
353//===----------------------------------------------------------------------===//
354
355void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
356 // LRE itself will remove from SlotIndexes and parent basic block.
357 VRM->RemoveMachineInstrFromMaps(MI);
358}
359
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000360bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
361 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
362 unassign(LIS->getInterval(VirtReg), PhysReg);
363 return true;
364 }
365 // Unassigned virtreg is probably in the priority queue.
366 // RegAllocBase will erase it after dequeueing.
367 return false;
368}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000369
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000370void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
371 unsigned PhysReg = VRM->getPhys(VirtReg);
372 if (!PhysReg)
373 return;
374
375 // Register is assigned, put it back on the queue for reassignment.
376 LiveInterval &LI = LIS->getInterval(VirtReg);
377 unassign(LI, PhysReg);
378 enqueue(&LI);
379}
380
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000381void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
382 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000383 // be split into connected components. The new components are much smaller
384 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000385 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000386 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000387 ExtraRegInfo.grow(New);
388 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000389}
390
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000391void RAGreedy::releaseMemory() {
392 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000393 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000394 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000395 RegAllocBase::releaseMemory();
396}
397
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000398void RAGreedy::enqueue(LiveInterval *LI) {
399 // Prioritize live ranges by size, assigning larger ranges first.
400 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000401 const unsigned Size = LI->getSize();
402 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000403 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
404 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000405 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000406
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000407 ExtraRegInfo.grow(Reg);
408 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000409 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000410
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000411 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000412 // Unsplit ranges that couldn't be allocated immediately are deferred until
413 // everything else has been allocated. Long ranges are allocated last so
414 // they are split against realistic interference.
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000415 if (CompactRegions)
416 Prio = Size;
417 else
418 Prio = (1u << 31) - Size;
419 } else {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000420 // Everything else is allocated in long->short order. Long ranges that don't
421 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000422 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000423
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000424 // Boost ranges that have a physical register hint.
425 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
426 Prio |= (1u << 30);
427 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000428
429 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000430}
431
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000432LiveInterval *RAGreedy::dequeue() {
433 if (Queue.empty())
434 return 0;
435 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
436 Queue.pop();
437 return LI;
438}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000439
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000440
441//===----------------------------------------------------------------------===//
442// Direct Assignment
443//===----------------------------------------------------------------------===//
444
445/// tryAssign - Try to assign VirtReg to an available register.
446unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
447 AllocationOrder &Order,
448 SmallVectorImpl<LiveInterval*> &NewVRegs) {
449 Order.rewind();
450 unsigned PhysReg;
451 while ((PhysReg = Order.next()))
452 if (!checkPhysRegInterference(VirtReg, PhysReg))
453 break;
454 if (!PhysReg || Order.isHint(PhysReg))
455 return PhysReg;
456
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000457 // PhysReg is available, but there may be a better choice.
458
459 // If we missed a simple hint, try to cheaply evict interference from the
460 // preferred register.
461 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
462 if (Order.isHint(Hint)) {
463 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
464 EvictionCost MaxCost(1);
465 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
466 evictInterference(VirtReg, Hint, NewVRegs);
467 return Hint;
468 }
469 }
470
471 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000472 unsigned Cost = TRI->getCostPerUse(PhysReg);
473
474 // Most registers have 0 additional cost.
475 if (!Cost)
476 return PhysReg;
477
478 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
479 << '\n');
480 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
481 return CheapReg ? CheapReg : PhysReg;
482}
483
484
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000485//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000486// Interference eviction
487//===----------------------------------------------------------------------===//
488
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000489/// shouldEvict - determine if A should evict the assigned live range B. The
490/// eviction policy defined by this function together with the allocation order
491/// defined by enqueue() decides which registers ultimately end up being split
492/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000493///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000494/// Cascade numbers are used to prevent infinite loops if this function is a
495/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000496///
497/// @param A The live range to be assigned.
498/// @param IsHint True when A is about to be assigned to its preferred
499/// register.
500/// @param B The live range to be evicted.
501/// @param BreaksHint True when B is already assigned to its preferred register.
502bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
503 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000504 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000505
506 // Be fairly aggressive about following hints as long as the evictee can be
507 // split.
508 if (CanSplit && IsHint && !BreaksHint)
509 return true;
510
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000511 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000512}
513
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000514/// canEvictInterference - Return true if all interferences between VirtReg and
515/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
516///
517/// @param VirtReg Live range that is about to be assigned.
518/// @param PhysReg Desired register for assignment.
519/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
520/// @param MaxCost Only look for cheaper candidates and update with new cost
521/// when returning true.
522/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000523bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000524 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000525 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
526 // involved in an eviction before. If a cascade number was assigned, deny
527 // evicting anything with the same or a newer cascade number. This prevents
528 // infinite eviction loops.
529 //
530 // This works out so a register without a cascade number is allowed to evict
531 // anything, and it can be evicted by anything.
532 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
533 if (!Cascade)
534 Cascade = NextCascade;
535
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000536 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000537 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
538 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000539 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000540 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000541 return false;
542
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000543 // Check if any interfering live range is heavier than MaxWeight.
544 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
545 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000546 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
547 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000548 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000549 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000550 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000551 // Once a live range becomes small enough, it is urgent that we find a
552 // register for it. This is indicated by an infinite spill weight. These
553 // urgent live ranges get to evict almost anything.
554 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
555 // Only evict older cascades or live ranges without a cascade.
556 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
557 if (Cascade <= IntfCascade) {
558 if (!Urgent)
559 return false;
560 // We permit breaking cascades for urgent evictions. It should be the
561 // last resort, though, so make it really expensive.
562 Cost.BrokenHints += 10;
563 }
564 // Would this break a satisfied hint?
565 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
566 // Update eviction cost.
567 Cost.BrokenHints += BreaksHint;
568 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
569 // Abort if this would be too expensive.
570 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000571 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000572 // Finally, apply the eviction policy for non-urgent evictions.
573 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000574 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000575 }
576 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000577 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000578 return true;
579}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000580
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000581/// evictInterference - Evict any interferring registers that prevent VirtReg
582/// from being assigned to Physreg. This assumes that canEvictInterference
583/// returned true.
584void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
585 SmallVectorImpl<LiveInterval*> &NewVRegs) {
586 // Make sure that VirtReg has a cascade number, and assign that cascade
587 // number to every evicted register. These live ranges than then only be
588 // evicted by a newer cascade, preventing infinite loops.
589 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
590 if (!Cascade)
591 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
592
593 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
594 << " interference: Cascade " << Cascade << '\n');
595 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
596 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
597 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
598 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
599 LiveInterval *Intf = Q.interferingVRegs()[i];
600 unassign(*Intf, VRM->getPhys(Intf->reg));
601 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
602 VirtReg.isSpillable() < Intf->isSpillable()) &&
603 "Cannot decrease cascade number, illegal eviction");
604 ExtraRegInfo[Intf->reg].Cascade = Cascade;
605 ++NumEvicted;
606 NewVRegs.push_back(Intf);
607 }
608 }
609}
610
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000611/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000612/// @param VirtReg Currently unassigned virtual register.
613/// @param Order Physregs to try.
614/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000615unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
616 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000617 SmallVectorImpl<LiveInterval*> &NewVRegs,
618 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000619 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
620
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000621 // Keep track of the cheapest interference seen so far.
622 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000623 unsigned BestPhys = 0;
624
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000625 // When we are just looking for a reduced cost per use, don't break any
626 // hints, and only evict smaller spill weights.
627 if (CostPerUseLimit < ~0u) {
628 BestCost.BrokenHints = 0;
629 BestCost.MaxWeight = VirtReg.weight;
630 }
631
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000632 Order.rewind();
633 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000634 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
635 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000636 // The first use of a callee-saved register in a function has cost 1.
637 // Don't start using a CSR when the CostPerUseLimit is low.
638 if (CostPerUseLimit == 1)
639 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
640 if (!MRI->isPhysRegUsed(CSR)) {
641 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
642 << PrintReg(CSR, TRI) << '\n');
643 continue;
644 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000645
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000646 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000647 continue;
648
649 // Best so far.
650 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000651
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000652 // Stop if the hint can be used.
653 if (Order.isHint(PhysReg))
654 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000655 }
656
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000657 if (!BestPhys)
658 return 0;
659
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000660 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000661 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000662}
663
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000664
665//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000666// Region Splitting
667//===----------------------------------------------------------------------===//
668
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000669/// addSplitConstraints - Fill out the SplitConstraints vector based on the
670/// interference pattern in Physreg and its aliases. Add the constraints to
671/// SpillPlacement and return the static cost of this split in Cost, assuming
672/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000673/// Return false if there are no bundles with positive bias.
674bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
675 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000676 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000677
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000678 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000679 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000680 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000681 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
682 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000683 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000684
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000685 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000686 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000687 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
688 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000689 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000690
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000691 if (!Intf.hasInterference())
692 continue;
693
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000694 // Number of spill code instructions to insert.
695 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000696
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000697 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000698 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000699 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000700 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000701 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000702 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000703 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000704 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000705 }
706
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000707 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000708 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000709 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000710 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000711 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000712 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000713 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000714 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000715 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000716
717 // Accumulate the total frequency of inserted spill code.
718 if (Ins)
719 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000720 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000721 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000722
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000723 // Add constraints for use-blocks. Note that these are the only constraints
724 // that may add a positive bias, it is downhill from here.
725 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000726 return SpillPlacer->scanActiveBundles();
727}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000728
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000729
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000730/// addThroughConstraints - Add constraints and links to SpillPlacer from the
731/// live-through blocks in Blocks.
732void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
733 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000734 const unsigned GroupSize = 8;
735 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000736 unsigned TBS[GroupSize];
737 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000738
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000739 for (unsigned i = 0; i != Blocks.size(); ++i) {
740 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000741 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000742
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000743 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000744 assert(T < GroupSize && "Array overflow");
745 TBS[T] = Number;
746 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000747 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000748 T = 0;
749 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000750 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000751 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000752
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000753 assert(B < GroupSize && "Array overflow");
754 BCS[B].Number = Number;
755
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000756 // Interference for the live-in value.
757 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
758 BCS[B].Entry = SpillPlacement::MustSpill;
759 else
760 BCS[B].Entry = SpillPlacement::PrefSpill;
761
762 // Interference for the live-out value.
763 if (Intf.last() >= SA->getLastSplitPoint(Number))
764 BCS[B].Exit = SpillPlacement::MustSpill;
765 else
766 BCS[B].Exit = SpillPlacement::PrefSpill;
767
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000768 if (++B == GroupSize) {
769 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
770 SpillPlacer->addConstraints(Array);
771 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000772 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000773 }
774
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000775 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
776 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000777 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000778}
779
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000780void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000781 // Keep track of through blocks that have not been added to SpillPlacer.
782 BitVector Todo = SA->getThroughBlocks();
783 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
784 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000785#ifndef NDEBUG
786 unsigned Visited = 0;
787#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000788
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000789 for (;;) {
790 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000791 // Find new through blocks in the periphery of PrefRegBundles.
792 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
793 unsigned Bundle = NewBundles[i];
794 // Look at all blocks connected to Bundle in the full graph.
795 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
796 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
797 I != E; ++I) {
798 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000799 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000800 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000801 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000802 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000803 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000804#ifndef NDEBUG
805 ++Visited;
806#endif
807 }
808 }
809 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000810 if (ActiveBlocks.size() == AddedTo)
811 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000812
813 // Compute through constraints from the interference, or assume that all
814 // through blocks prefer spilling when forming compact regions.
815 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
816 if (Cand.PhysReg)
817 addThroughConstraints(Cand.Intf, NewBlocks);
818 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000819 // Provide a strong negative bias on through blocks to prevent unwanted
820 // liveness on loop backedges.
821 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000822 AddedTo = ActiveBlocks.size();
823
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000824 // Perhaps iterating can enable more bundles?
825 SpillPlacer->iterate();
826 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000827 DEBUG(dbgs() << ", v=" << Visited);
828}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000829
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000830/// calcCompactRegion - Compute the set of edge bundles that should be live
831/// when splitting the current live range into compact regions. Compact
832/// regions can be computed without looking at interference. They are the
833/// regions formed by removing all the live-through blocks from the live range.
834///
835/// Returns false if the current live range is already compact, or if the
836/// compact regions would form single block regions anyway.
837bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
838 // Without any through blocks, the live range is already compact.
839 if (!SA->getNumThroughBlocks())
840 return false;
841
842 // Compact regions don't correspond to any physreg.
843 Cand.reset(IntfCache, 0);
844
845 DEBUG(dbgs() << "Compact region bundles");
846
847 // Use the spill placer to determine the live bundles. GrowRegion pretends
848 // that all the through blocks have interference when PhysReg is unset.
849 SpillPlacer->prepare(Cand.LiveBundles);
850
851 // The static split cost will be zero since Cand.Intf reports no interference.
852 float Cost;
853 if (!addSplitConstraints(Cand.Intf, Cost)) {
854 DEBUG(dbgs() << ", none.\n");
855 return false;
856 }
857
858 growRegion(Cand);
859 SpillPlacer->finish();
860
861 if (!Cand.LiveBundles.any()) {
862 DEBUG(dbgs() << ", none.\n");
863 return false;
864 }
865
866 DEBUG({
867 for (int i = Cand.LiveBundles.find_first(); i>=0;
868 i = Cand.LiveBundles.find_next(i))
869 dbgs() << " EB#" << i;
870 dbgs() << ".\n";
871 });
872 return true;
873}
874
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000875/// calcSpillCost - Compute how expensive it would be to split the live range in
876/// SA around all use blocks instead of forming bundle regions.
877float RAGreedy::calcSpillCost() {
878 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000879 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
880 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
881 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
882 unsigned Number = BI.MBB->getNumber();
883 // We normally only need one spill instruction - a load or a store.
884 Cost += SpillPlacer->getBlockFrequency(Number);
885
886 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000887 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
888 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000889 }
890 return Cost;
891}
892
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000893/// calcGlobalSplitCost - Return the global split cost of following the split
894/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000895/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000896///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000897float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000898 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000899 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000900 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
901 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
902 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000903 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000904 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
905 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
906 unsigned Ins = 0;
907
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000908 if (BI.LiveIn)
909 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
910 if (BI.LiveOut)
911 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000912 if (Ins)
913 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000914 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000915
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000916 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
917 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000918 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
919 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000920 if (!RegIn && !RegOut)
921 continue;
922 if (RegIn && RegOut) {
923 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000924 Cand.Intf.moveToBlock(Number);
925 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000926 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
927 continue;
928 }
929 // live-in / stack-out or stack-in live-out.
930 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000931 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000932 return GlobalCost;
933}
934
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000935/// splitAroundRegion - Split the current live range around the regions
936/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000937///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000938/// Before calling this function, GlobalCand and BundleCand must be initialized
939/// so each bundle is assigned to a valid candidate, or NoCand for the
940/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
941/// objects must be initialized for the current live range, and intervals
942/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000943///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000944/// @param LREdit The LiveRangeEdit object handling the current split.
945/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
946/// must appear in this list.
947void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
948 ArrayRef<unsigned> UsedCands) {
949 // These are the intervals created for new global ranges. We may create more
950 // intervals for local ranges.
951 const unsigned NumGlobalIntvs = LREdit.size();
952 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
953 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000954
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000955 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +0000956 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000957 // is all copies.
958 unsigned Reg = SA->getParent().reg;
959 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
960
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000961 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000962 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
963 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
964 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000965 unsigned Number = BI.MBB->getNumber();
966 unsigned IntvIn = 0, IntvOut = 0;
967 SlotIndex IntfIn, IntfOut;
968 if (BI.LiveIn) {
969 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
970 if (CandIn != NoCand) {
971 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
972 IntvIn = Cand.IntvIdx;
973 Cand.Intf.moveToBlock(Number);
974 IntfIn = Cand.Intf.first();
975 }
976 }
977 if (BI.LiveOut) {
978 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
979 if (CandOut != NoCand) {
980 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
981 IntvOut = Cand.IntvIdx;
982 Cand.Intf.moveToBlock(Number);
983 IntfOut = Cand.Intf.last();
984 }
985 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000986
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000987 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000988 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000989 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000990 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000991 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000992 continue;
993 }
994
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000995 if (IntvIn && IntvOut)
996 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
997 else if (IntvIn)
998 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000999 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001000 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001001 }
1002
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001003 // Handle live-through blocks. The relevant live-through blocks are stored in
1004 // the ActiveBlocks list with each candidate. We need to filter out
1005 // duplicates.
1006 BitVector Todo = SA->getThroughBlocks();
1007 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1008 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1009 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1010 unsigned Number = Blocks[i];
1011 if (!Todo.test(Number))
1012 continue;
1013 Todo.reset(Number);
1014
1015 unsigned IntvIn = 0, IntvOut = 0;
1016 SlotIndex IntfIn, IntfOut;
1017
1018 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1019 if (CandIn != NoCand) {
1020 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1021 IntvIn = Cand.IntvIdx;
1022 Cand.Intf.moveToBlock(Number);
1023 IntfIn = Cand.Intf.first();
1024 }
1025
1026 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1027 if (CandOut != NoCand) {
1028 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1029 IntvOut = Cand.IntvIdx;
1030 Cand.Intf.moveToBlock(Number);
1031 IntfOut = Cand.Intf.last();
1032 }
1033 if (!IntvIn && !IntvOut)
1034 continue;
1035 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1036 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001037 }
1038
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001039 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001040
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001041 SmallVector<unsigned, 8> IntvMap;
1042 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001043 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001044
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001045 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001046 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001047
1048 // Sort out the new intervals created by splitting. We get four kinds:
1049 // - Remainder intervals should not be split again.
1050 // - Candidate intervals can be assigned to Cand.PhysReg.
1051 // - Block-local splits are candidates for local splitting.
1052 // - DCE leftovers should go back on the queue.
1053 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001054 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001055
1056 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001057 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001058 continue;
1059
1060 // Remainder interval. Don't try splitting again, spill if it doesn't
1061 // allocate.
1062 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001063 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001064 continue;
1065 }
1066
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001067 // Global intervals. Allow repeated splitting as long as the number of live
1068 // blocks is strictly decreasing.
1069 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001070 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001071 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1072 << " blocks as original.\n");
1073 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001074 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001075 }
1076 continue;
1077 }
1078
1079 // Other intervals are treated as new. This includes local intervals created
1080 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001081 }
1082
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001083 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001084 MF->verify(this, "After splitting live range around region");
1085}
1086
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001087unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1088 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001089 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001090 unsigned BestCand = NoCand;
1091 float BestCost;
1092 SmallVector<unsigned, 8> UsedCands;
1093
1094 // Check if we can split this live range around a compact region.
1095 bool HasCompact = CompactRegions && calcCompactRegion(GlobalCand.front());
1096 if (HasCompact) {
1097 // Yes, keep GlobalCand[0] as the compact region candidate.
1098 NumCands = 1;
1099 BestCost = HUGE_VALF;
1100 } else {
1101 // No benefit from the compact region, our fallback will be per-block
1102 // splitting. Make sure we find a solution that is cheaper than spilling.
1103 BestCost = Hysteresis * calcSpillCost();
1104 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1105 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001106
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001107 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001108 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001109 // Discard bad candidates before we run out of interference cache cursors.
1110 // This will only affect register classes with a lot of registers (>32).
1111 if (NumCands == IntfCache.getMaxCursors()) {
1112 unsigned WorstCount = ~0u;
1113 unsigned Worst = 0;
1114 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001115 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001116 continue;
1117 unsigned Count = GlobalCand[i].LiveBundles.count();
1118 if (Count < WorstCount)
1119 Worst = i, WorstCount = Count;
1120 }
1121 --NumCands;
1122 GlobalCand[Worst] = GlobalCand[NumCands];
1123 }
1124
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001125 if (GlobalCand.size() <= NumCands)
1126 GlobalCand.resize(NumCands+1);
1127 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1128 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001129
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001130 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001131 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001132 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001133 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001134 continue;
1135 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001136 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001137 if (Cost >= BestCost) {
1138 DEBUG({
1139 if (BestCand == NoCand)
1140 dbgs() << " worse than no bundles\n";
1141 else
1142 dbgs() << " worse than "
1143 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1144 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001145 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001146 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001147 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001148
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001149 SpillPlacer->finish();
1150
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001151 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001152 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001153 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001154 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001155 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001156
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001157 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001158 DEBUG({
1159 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001160 for (int i = Cand.LiveBundles.find_first(); i>=0;
1161 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001162 dbgs() << " EB#" << i;
1163 dbgs() << ".\n";
1164 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001165 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001166 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001167 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001168 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001169 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001170 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001171
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001172 // No solutions found, fall back to single block splitting.
1173 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001174 return 0;
1175
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001176 // Prepare split editor.
1177 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001178 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001179
1180 // Assign all edge bundles to the preferred candidate, or NoCand.
1181 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1182
1183 // Assign bundles for the best candidate region.
1184 if (BestCand != NoCand) {
1185 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1186 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1187 UsedCands.push_back(BestCand);
1188 Cand.IntvIdx = SE->openIntv();
1189 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1190 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001191 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001192 }
1193 }
1194
1195 // Assign bundles for the compact region.
1196 if (HasCompact) {
1197 GlobalSplitCandidate &Cand = GlobalCand.front();
1198 assert(!Cand.PhysReg && "Compact region has no physreg");
1199 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1200 UsedCands.push_back(0);
1201 Cand.IntvIdx = SE->openIntv();
1202 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1203 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001204 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001205 }
1206 }
1207
1208 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001209 return 0;
1210}
1211
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001212
1213//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001214// Per-Block Splitting
1215//===----------------------------------------------------------------------===//
1216
1217/// tryBlockSplit - Split a global live range around every block with uses. This
1218/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1219/// they don't allocate.
1220unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1221 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1222 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1223 unsigned Reg = VirtReg.reg;
1224 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1225 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001226 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001227 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1228 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1229 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1230 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1231 SE->splitSingleBlock(BI);
1232 }
1233 // No blocks were split.
1234 if (LREdit.empty())
1235 return 0;
1236
1237 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001238 SmallVector<unsigned, 8> IntvMap;
1239 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001240
1241 // Tell LiveDebugVariables about the new ranges.
1242 DebugVars->splitRegister(Reg, LREdit.regs());
1243
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001244 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1245
1246 // Sort out the new intervals created by splitting. The remainder interval
1247 // goes straight to spilling, the new local ranges get to stay RS_New.
1248 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1249 LiveInterval &LI = *LREdit.get(i);
1250 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1251 setStage(LI, RS_Spill);
1252 }
1253
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001254 if (VerifyEnabled)
1255 MF->verify(this, "After splitting live range around basic blocks");
1256 return 0;
1257}
1258
1259//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001260// Local Splitting
1261//===----------------------------------------------------------------------===//
1262
1263
1264/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1265/// in order to use PhysReg between two entries in SA->UseSlots.
1266///
1267/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1268///
1269void RAGreedy::calcGapWeights(unsigned PhysReg,
1270 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001271 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1272 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001273 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1274 const unsigned NumGaps = Uses.size()-1;
1275
1276 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001277 SlotIndex StartIdx =
1278 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1279 SlotIndex StopIdx =
1280 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001281
1282 GapWeight.assign(NumGaps, 0.0f);
1283
1284 // Add interference from each overlapping register.
1285 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1286 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1287 .checkInterference())
1288 continue;
1289
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001290 // We know that VirtReg is a continuous interval from FirstInstr to
1291 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001292 //
1293 // Interference that overlaps an instruction is counted in both gaps
1294 // surrounding the instruction. The exception is interference before
1295 // StartIdx and after StopIdx.
1296 //
1297 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1298 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1299 // Skip the gaps before IntI.
1300 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1301 if (++Gap == NumGaps)
1302 break;
1303 if (Gap == NumGaps)
1304 break;
1305
1306 // Update the gaps covered by IntI.
1307 const float weight = IntI.value()->weight;
1308 for (; Gap != NumGaps; ++Gap) {
1309 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1310 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1311 break;
1312 }
1313 if (Gap == NumGaps)
1314 break;
1315 }
1316 }
1317}
1318
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001319/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1320/// basic block.
1321///
1322unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1323 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001324 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1325 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001326
1327 // Note that it is possible to have an interval that is live-in or live-out
1328 // while only covering a single block - A phi-def can use undef values from
1329 // predecessors, and the block could be a single-block loop.
1330 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001331 // that the interval is continuous from FirstInstr to LastInstr. We should
1332 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001333
1334 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1335 if (Uses.size() <= 2)
1336 return 0;
1337 const unsigned NumGaps = Uses.size()-1;
1338
1339 DEBUG({
1340 dbgs() << "tryLocalSplit: ";
1341 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1342 dbgs() << ' ' << SA->UseSlots[i];
1343 dbgs() << '\n';
1344 });
1345
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001346 // Since we allow local split results to be split again, there is a risk of
1347 // creating infinite loops. It is tempting to require that the new live
1348 // ranges have less instructions than the original. That would guarantee
1349 // convergence, but it is too strict. A live range with 3 instructions can be
1350 // split 2+3 (including the COPY), and we want to allow that.
1351 //
1352 // Instead we use these rules:
1353 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001354 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001355 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001356 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001357 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001358 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001359 // smaller ranges are marked RS_New.
1360 //
1361 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1362 // excessive splitting and infinite loops.
1363 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001364 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001365
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001366 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001367 unsigned BestBefore = NumGaps;
1368 unsigned BestAfter = 0;
1369 float BestDiff = 0;
1370
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001371 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001372 SmallVector<float, 8> GapWeight;
1373
1374 Order.rewind();
1375 while (unsigned PhysReg = Order.next()) {
1376 // Keep track of the largest spill weight that would need to be evicted in
1377 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1378 calcGapWeights(PhysReg, GapWeight);
1379
1380 // Try to find the best sequence of gaps to close.
1381 // The new spill weight must be larger than any gap interference.
1382
1383 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001384 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001385
1386 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1387 // It is the spill weight that needs to be evicted.
1388 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001389
1390 for (;;) {
1391 // Live before/after split?
1392 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1393 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1394
1395 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1396 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1397 << " i=" << MaxGap);
1398
1399 // Stop before the interval gets so big we wouldn't be making progress.
1400 if (!LiveBefore && !LiveAfter) {
1401 DEBUG(dbgs() << " all\n");
1402 break;
1403 }
1404 // Should the interval be extended or shrunk?
1405 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001406
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001407 // How many gaps would the new range have?
1408 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1409
1410 // Legally, without causing looping?
1411 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1412
1413 if (Legal && MaxGap < HUGE_VALF) {
1414 // Estimate the new spill weight. Each instruction reads or writes the
1415 // register. Conservatively assume there are no read-modify-write
1416 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001417 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001418 // Try to guess the size of the new interval.
1419 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1420 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1421 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001422 // Would this split be possible to allocate?
1423 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001424 DEBUG(dbgs() << " w=" << EstWeight);
1425 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001426 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001427 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001428 if (Diff > BestDiff) {
1429 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001430 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001431 BestBefore = SplitBefore;
1432 BestAfter = SplitAfter;
1433 }
1434 }
1435 }
1436
1437 // Try to shrink.
1438 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001439 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001440 DEBUG(dbgs() << " shrink\n");
1441 // Recompute the max when necessary.
1442 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1443 MaxGap = GapWeight[SplitBefore];
1444 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1445 MaxGap = std::max(MaxGap, GapWeight[i]);
1446 }
1447 continue;
1448 }
1449 MaxGap = 0;
1450 }
1451
1452 // Try to extend the interval.
1453 if (SplitAfter >= NumGaps) {
1454 DEBUG(dbgs() << " end\n");
1455 break;
1456 }
1457
1458 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001459 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001460 }
1461 }
1462
1463 // Didn't find any candidates?
1464 if (BestBefore == NumGaps)
1465 return 0;
1466
1467 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1468 << '-' << Uses[BestAfter] << ", " << BestDiff
1469 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1470
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001471 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001472 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001473
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001474 SE->openIntv();
1475 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1476 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1477 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001478 SmallVector<unsigned, 8> IntvMap;
1479 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001480 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001481
1482 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001483 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001484 // leave the new intervals as RS_New so they can compete.
1485 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1486 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1487 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1488 if (NewGaps >= NumGaps) {
1489 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1490 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001491 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1492 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001493 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001494 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1495 }
1496 DEBUG(dbgs() << '\n');
1497 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001498 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001499
1500 return 0;
1501}
1502
1503//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001504// Live Range Splitting
1505//===----------------------------------------------------------------------===//
1506
1507/// trySplit - Try to split VirtReg or one of its interferences, making it
1508/// assignable.
1509/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1510unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1511 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001512 // Ranges must be Split2 or less.
1513 if (getStage(VirtReg) >= RS_Spill)
1514 return 0;
1515
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001516 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001517 if (LIS->intervalIsInOneMBB(VirtReg)) {
1518 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001519 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001520 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001521 }
1522
1523 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001524
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001525 SA->analyze(&VirtReg);
1526
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001527 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1528 // coalescer. That may cause the range to become allocatable which means that
1529 // tryRegionSplit won't be making progress. This check should be replaced with
1530 // an assertion when the coalescer is fixed.
1531 if (SA->didRepairRange()) {
1532 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001533 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001534 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1535 return PhysReg;
1536 }
1537
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001538 // First try to split around a region spanning multiple blocks. RS_Split2
1539 // ranges already made dubious progress with region splitting, so they go
1540 // straight to single block splitting.
1541 if (getStage(VirtReg) < RS_Split2) {
1542 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1543 if (PhysReg || !NewVRegs.empty())
1544 return PhysReg;
1545 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001546
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001547 // Then isolate blocks.
1548 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001549}
1550
1551
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001552//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001553// Main Entry Point
1554//===----------------------------------------------------------------------===//
1555
1556unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001557 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001558 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001559 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001560 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1561 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001562
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001563 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001564 DEBUG(dbgs() << StageName[Stage]
1565 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001566
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001567 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001568 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001569 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001570 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001571 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1572 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001573
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001574 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1575
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001576 // The first time we see a live range, don't try to split or spill.
1577 // Wait until the second time, when all smaller ranges have been allocated.
1578 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001579 if (Stage < RS_Split) {
1580 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001581 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001582 NewVRegs.push_back(&VirtReg);
1583 return 0;
1584 }
1585
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001586 // If we couldn't allocate a register from spilling, there is probably some
1587 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001588 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001589 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001590
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001591 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001592 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1593 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001594 return PhysReg;
1595
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001596 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001597 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001598 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1599 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001600 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001601
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001602 if (VerifyEnabled)
1603 MF->verify(this, "After spilling");
1604
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001605 // The live virtual register requesting allocation was spilled, so tell
1606 // the caller not to allocate anything during this round.
1607 return 0;
1608}
1609
1610bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1611 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1612 << "********** Function: "
1613 << ((Value*)mf.getFunction())->getName() << '\n');
1614
1615 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001616 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001617 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001618
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001619 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001620 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001621 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001622 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001623 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001624 Bundles = &getAnalysis<EdgeBundles>();
1625 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001626 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001627
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001628 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001629 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001630 ExtraRegInfo.clear();
1631 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1632 NextCascade = 1;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001633 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001634 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001635
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001636 allocatePhysRegs();
1637 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001638 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001639
1640 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001641 {
1642 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001643 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001644 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001645
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001646 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenc4769022011-07-31 03:53:42 +00001647 {
1648 NamedRegionTimer T("Emit Debug Info", TimerGroupName, TimePassesIsEnabled);
1649 DebugVars->emitDebugValues(VRM);
1650 }
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001651
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001652 // The pass output is in VirtRegMap. Release all the transient data.
1653 releaseMemory();
1654
1655 return true;
1656}