blob: 63506f094b9548168a6830a532ee4bcd815d332c [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"
Rafael Espindolafdf16ca2011-06-26 21:41:06 +000025#include "RegisterCoalescer.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000026#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000027#include "llvm/Analysis/AliasAnalysis.h"
28#include "llvm/Function.h"
29#include "llvm/PassAnalysisSupport.h"
30#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000031#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000032#include "llvm/CodeGen/LiveIntervalAnalysis.h"
33#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000034#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000036#include "llvm/CodeGen/MachineLoopInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/CodeGen/Passes.h"
39#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000040#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000041#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000042#include "llvm/Support/Debug.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000045#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000046
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000047#include <queue>
48
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000049using namespace llvm;
50
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000051STATISTIC(NumGlobalSplits, "Number of split global live ranges");
52STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000053STATISTIC(NumEvicted, "Number of interferences evicted");
54
Jakob Stoklund Olesena92afc12011-08-03 23:16:09 +000055cl::opt<bool> CompactRegions("compact-regions", cl::init(true));
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000056
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000057static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
58 createGreedyRegisterAllocator);
59
60namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000061class RAGreedy : public MachineFunctionPass,
62 public RegAllocBase,
63 private LiveRangeEdit::Delegate {
64
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000065 // context
66 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000067
68 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000069 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000070 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000071 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000072 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000073 EdgeBundles *Bundles;
74 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000075 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000076
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000077 // state
78 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000079 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000080 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000081
82 // Live ranges pass through a number of stages as we try to allocate them.
83 // Some of the stages may also create new live ranges:
84 //
85 // - Region splitting.
86 // - Per-block splitting.
87 // - Local splitting.
88 // - Spilling.
89 //
90 // Ranges produced by one of the stages skip the previous stages when they are
91 // dequeued. This improves performance because we can skip interference checks
92 // that are unlikely to give any results. It also guarantees that the live
93 // range splitting algorithm terminates, something that is otherwise hard to
94 // ensure.
95 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +000096 /// Newly created live range that has never been queued.
97 RS_New,
98
99 /// Only attempt assignment and eviction. Then requeue as RS_Split.
100 RS_Assign,
101
102 /// Attempt live range splitting if assignment is impossible.
103 RS_Split,
104
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000105 /// Attempt more aggressive live range splitting that is guaranteed to make
106 /// progress. This is used for split products that may not be making
107 /// progress.
108 RS_Split2,
109
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000110 /// Live range will be spilled. No more splitting will be attempted.
111 RS_Spill,
112
113 /// There is nothing more we can do to this live range. Abort compilation
114 /// if it can't be assigned.
115 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000116 };
117
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000118 static const char *const StageName[];
119
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000120 // RegInfo - Keep additional information about each live range.
121 struct RegInfo {
122 LiveRangeStage Stage;
123
124 // Cascade - Eviction loop prevention. See canEvictInterference().
125 unsigned Cascade;
126
127 RegInfo() : Stage(RS_New), Cascade(0) {}
128 };
129
130 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000131
132 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000133 return ExtraRegInfo[VirtReg.reg].Stage;
134 }
135
136 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
137 ExtraRegInfo.resize(MRI->getNumVirtRegs());
138 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000139 }
140
141 template<typename Iterator>
142 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000143 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000144 for (;Begin != End; ++Begin) {
145 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000146 if (ExtraRegInfo[Reg].Stage == RS_New)
147 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000148 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000149 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000150
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000151 /// Cost of evicting interference.
152 struct EvictionCost {
153 unsigned BrokenHints; ///< Total number of broken hints.
154 float MaxWeight; ///< Maximum spill weight evicted.
155
156 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
157
158 bool operator<(const EvictionCost &O) const {
159 if (BrokenHints != O.BrokenHints)
160 return BrokenHints < O.BrokenHints;
161 return MaxWeight < O.MaxWeight;
162 }
163 };
164
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000165 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000166 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000167 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000168
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000169 /// Cached per-block interference maps
170 InterferenceCache IntfCache;
171
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000172 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000173 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000174
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000175 /// Global live range splitting candidate info.
176 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000177 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000178 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000179
180 // SplitKit interval index for this candidate.
181 unsigned IntvIdx;
182
183 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000184 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000185
186 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000187 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000188 SmallVector<unsigned, 8> ActiveBlocks;
189
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000190 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000191 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000192 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000193 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000194 LiveBundles.clear();
195 ActiveBlocks.clear();
196 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000197
198 // Set B[i] = C for every live bundle where B[i] was NoCand.
199 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
200 unsigned Count = 0;
201 for (int i = LiveBundles.find_first(); i >= 0;
202 i = LiveBundles.find_next(i))
203 if (B[i] == NoCand) {
204 B[i] = C;
205 Count++;
206 }
207 return Count;
208 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000209 };
210
211 /// Candidate info for for each PhysReg in AllocationOrder.
212 /// This vector never shrinks, but grows to the size of the largest register
213 /// class.
214 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
215
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000216 enum { NoCand = ~0u };
217
218 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
219 /// NoCand which indicates the stack interval.
220 SmallVector<unsigned, 32> BundleCand;
221
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000222public:
223 RAGreedy();
224
225 /// Return the pass name.
226 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000227 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000228 }
229
230 /// RAGreedy analysis usage.
231 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000232 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000233 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000234 virtual void enqueue(LiveInterval *LI);
235 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000236 virtual unsigned selectOrSplit(LiveInterval&,
237 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000238
239 /// Perform register allocation.
240 virtual bool runOnMachineFunction(MachineFunction &mf);
241
242 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000243
244private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000245 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000246 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000247 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000248 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000249
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000250 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000251 bool addSplitConstraints(InterferenceCache::Cursor, float&);
252 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000253 void growRegion(GlobalSplitCandidate &Cand);
254 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000255 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000256 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000257 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000258 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
259 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
260 void evictInterference(LiveInterval&, unsigned,
261 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000262
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000263 unsigned tryAssign(LiveInterval&, AllocationOrder&,
264 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000265 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000266 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000267 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
268 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000269 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
270 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000271 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000273 unsigned trySplit(LiveInterval&, AllocationOrder&,
274 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000275};
276} // end anonymous namespace
277
278char RAGreedy::ID = 0;
279
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000280#ifndef NDEBUG
281const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000282 "RS_New",
283 "RS_Assign",
284 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000285 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000286 "RS_Spill",
287 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000288};
289#endif
290
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000291// Hysteresis to use when comparing floats.
292// This helps stabilize decisions based on float comparisons.
293const float Hysteresis = 0.98f;
294
295
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000296FunctionPass* llvm::createGreedyRegisterAllocator() {
297 return new RAGreedy();
298}
299
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000300RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000301 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000302 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000303 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
304 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
305 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000306 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000307 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
308 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
309 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
310 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
311 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000312 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
313 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000314}
315
316void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
317 AU.setPreservesCFG();
318 AU.addRequired<AliasAnalysis>();
319 AU.addPreserved<AliasAnalysis>();
320 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000321 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000322 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000323 AU.addRequired<LiveDebugVariables>();
324 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000325 if (StrongPHIElim)
326 AU.addRequiredID(StrongPHIEliminationID);
327 AU.addRequiredTransitive<RegisterCoalescer>();
328 AU.addRequired<CalculateSpillWeights>();
329 AU.addRequired<LiveStacks>();
330 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000331 AU.addRequired<MachineDominatorTree>();
332 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000333 AU.addRequired<MachineLoopInfo>();
334 AU.addPreserved<MachineLoopInfo>();
335 AU.addRequired<VirtRegMap>();
336 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000337 AU.addRequired<EdgeBundles>();
338 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000339 MachineFunctionPass::getAnalysisUsage(AU);
340}
341
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000342
343//===----------------------------------------------------------------------===//
344// LiveRangeEdit delegate methods
345//===----------------------------------------------------------------------===//
346
347void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
348 // LRE itself will remove from SlotIndexes and parent basic block.
349 VRM->RemoveMachineInstrFromMaps(MI);
350}
351
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000352bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
353 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
354 unassign(LIS->getInterval(VirtReg), PhysReg);
355 return true;
356 }
357 // Unassigned virtreg is probably in the priority queue.
358 // RegAllocBase will erase it after dequeueing.
359 return false;
360}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000361
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000362void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
363 unsigned PhysReg = VRM->getPhys(VirtReg);
364 if (!PhysReg)
365 return;
366
367 // Register is assigned, put it back on the queue for reassignment.
368 LiveInterval &LI = LIS->getInterval(VirtReg);
369 unassign(LI, PhysReg);
370 enqueue(&LI);
371}
372
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000373void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
374 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000375 // be split into connected components. The new components are much smaller
376 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000377 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000378 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000379 ExtraRegInfo.grow(New);
380 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000381}
382
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000383void RAGreedy::releaseMemory() {
384 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000385 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000386 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000387 RegAllocBase::releaseMemory();
388}
389
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000390void RAGreedy::enqueue(LiveInterval *LI) {
391 // Prioritize live ranges by size, assigning larger ranges first.
392 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000393 const unsigned Size = LI->getSize();
394 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000395 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
396 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000397 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000398
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000399 ExtraRegInfo.grow(Reg);
400 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000401 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000402
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000403 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000404 // Unsplit ranges that couldn't be allocated immediately are deferred until
405 // everything else has been allocated. Long ranges are allocated last so
406 // they are split against realistic interference.
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000407 if (CompactRegions)
408 Prio = Size;
409 else
410 Prio = (1u << 31) - Size;
411 } else {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000412 // Everything else is allocated in long->short order. Long ranges that don't
413 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000414 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000415
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000416 // Boost ranges that have a physical register hint.
417 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
418 Prio |= (1u << 30);
419 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000420
421 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000422}
423
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000424LiveInterval *RAGreedy::dequeue() {
425 if (Queue.empty())
426 return 0;
427 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
428 Queue.pop();
429 return LI;
430}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000431
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000432
433//===----------------------------------------------------------------------===//
434// Direct Assignment
435//===----------------------------------------------------------------------===//
436
437/// tryAssign - Try to assign VirtReg to an available register.
438unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
439 AllocationOrder &Order,
440 SmallVectorImpl<LiveInterval*> &NewVRegs) {
441 Order.rewind();
442 unsigned PhysReg;
443 while ((PhysReg = Order.next()))
444 if (!checkPhysRegInterference(VirtReg, PhysReg))
445 break;
446 if (!PhysReg || Order.isHint(PhysReg))
447 return PhysReg;
448
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000449 // PhysReg is available, but there may be a better choice.
450
451 // If we missed a simple hint, try to cheaply evict interference from the
452 // preferred register.
453 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
454 if (Order.isHint(Hint)) {
455 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
456 EvictionCost MaxCost(1);
457 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
458 evictInterference(VirtReg, Hint, NewVRegs);
459 return Hint;
460 }
461 }
462
463 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000464 unsigned Cost = TRI->getCostPerUse(PhysReg);
465
466 // Most registers have 0 additional cost.
467 if (!Cost)
468 return PhysReg;
469
470 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
471 << '\n');
472 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
473 return CheapReg ? CheapReg : PhysReg;
474}
475
476
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000477//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000478// Interference eviction
479//===----------------------------------------------------------------------===//
480
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000481/// shouldEvict - determine if A should evict the assigned live range B. The
482/// eviction policy defined by this function together with the allocation order
483/// defined by enqueue() decides which registers ultimately end up being split
484/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000485///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000486/// Cascade numbers are used to prevent infinite loops if this function is a
487/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000488///
489/// @param A The live range to be assigned.
490/// @param IsHint True when A is about to be assigned to its preferred
491/// register.
492/// @param B The live range to be evicted.
493/// @param BreaksHint True when B is already assigned to its preferred register.
494bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
495 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000496 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000497
498 // Be fairly aggressive about following hints as long as the evictee can be
499 // split.
500 if (CanSplit && IsHint && !BreaksHint)
501 return true;
502
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000503 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000504}
505
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000506/// canEvictInterference - Return true if all interferences between VirtReg and
507/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
508///
509/// @param VirtReg Live range that is about to be assigned.
510/// @param PhysReg Desired register for assignment.
511/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
512/// @param MaxCost Only look for cheaper candidates and update with new cost
513/// when returning true.
514/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000515bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000516 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000517 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
518 // involved in an eviction before. If a cascade number was assigned, deny
519 // evicting anything with the same or a newer cascade number. This prevents
520 // infinite eviction loops.
521 //
522 // This works out so a register without a cascade number is allowed to evict
523 // anything, and it can be evicted by anything.
524 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
525 if (!Cascade)
526 Cascade = NextCascade;
527
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000528 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000529 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
530 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000531 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000532 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000533 return false;
534
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000535 // Check if any interfering live range is heavier than MaxWeight.
536 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
537 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000538 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
539 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000540 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000541 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000542 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000543 // Once a live range becomes small enough, it is urgent that we find a
544 // register for it. This is indicated by an infinite spill weight. These
545 // urgent live ranges get to evict almost anything.
546 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
547 // Only evict older cascades or live ranges without a cascade.
548 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
549 if (Cascade <= IntfCascade) {
550 if (!Urgent)
551 return false;
552 // We permit breaking cascades for urgent evictions. It should be the
553 // last resort, though, so make it really expensive.
554 Cost.BrokenHints += 10;
555 }
556 // Would this break a satisfied hint?
557 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
558 // Update eviction cost.
559 Cost.BrokenHints += BreaksHint;
560 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
561 // Abort if this would be too expensive.
562 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000563 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000564 // Finally, apply the eviction policy for non-urgent evictions.
565 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000566 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000567 }
568 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000569 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000570 return true;
571}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000572
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000573/// evictInterference - Evict any interferring registers that prevent VirtReg
574/// from being assigned to Physreg. This assumes that canEvictInterference
575/// returned true.
576void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
577 SmallVectorImpl<LiveInterval*> &NewVRegs) {
578 // Make sure that VirtReg has a cascade number, and assign that cascade
579 // number to every evicted register. These live ranges than then only be
580 // evicted by a newer cascade, preventing infinite loops.
581 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
582 if (!Cascade)
583 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
584
585 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
586 << " interference: Cascade " << Cascade << '\n');
587 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
588 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
589 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
590 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
591 LiveInterval *Intf = Q.interferingVRegs()[i];
592 unassign(*Intf, VRM->getPhys(Intf->reg));
593 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
594 VirtReg.isSpillable() < Intf->isSpillable()) &&
595 "Cannot decrease cascade number, illegal eviction");
596 ExtraRegInfo[Intf->reg].Cascade = Cascade;
597 ++NumEvicted;
598 NewVRegs.push_back(Intf);
599 }
600 }
601}
602
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000603/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000604/// @param VirtReg Currently unassigned virtual register.
605/// @param Order Physregs to try.
606/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000607unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
608 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000609 SmallVectorImpl<LiveInterval*> &NewVRegs,
610 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000611 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
612
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000613 // Keep track of the cheapest interference seen so far.
614 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000615 unsigned BestPhys = 0;
616
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000617 // When we are just looking for a reduced cost per use, don't break any
618 // hints, and only evict smaller spill weights.
619 if (CostPerUseLimit < ~0u) {
620 BestCost.BrokenHints = 0;
621 BestCost.MaxWeight = VirtReg.weight;
622 }
623
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000624 Order.rewind();
625 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000626 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
627 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000628 // The first use of a callee-saved register in a function has cost 1.
629 // Don't start using a CSR when the CostPerUseLimit is low.
630 if (CostPerUseLimit == 1)
631 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
632 if (!MRI->isPhysRegUsed(CSR)) {
633 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
634 << PrintReg(CSR, TRI) << '\n');
635 continue;
636 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000637
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000638 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000639 continue;
640
641 // Best so far.
642 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000643
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000644 // Stop if the hint can be used.
645 if (Order.isHint(PhysReg))
646 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000647 }
648
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000649 if (!BestPhys)
650 return 0;
651
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000652 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000653 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000654}
655
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000656
657//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000658// Region Splitting
659//===----------------------------------------------------------------------===//
660
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000661/// addSplitConstraints - Fill out the SplitConstraints vector based on the
662/// interference pattern in Physreg and its aliases. Add the constraints to
663/// SpillPlacement and return the static cost of this split in Cost, assuming
664/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000665/// Return false if there are no bundles with positive bias.
666bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
667 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000668 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000669
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000670 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000671 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000672 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000673 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
674 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000675 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000676
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000677 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000678 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000679 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
680 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000681 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000682
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000683 if (!Intf.hasInterference())
684 continue;
685
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000686 // Number of spill code instructions to insert.
687 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000688
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000689 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000690 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000691 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000692 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000693 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000694 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000695 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000696 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000697 }
698
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000699 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000700 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000701 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000702 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000703 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000704 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000705 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000706 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000707 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000708
709 // Accumulate the total frequency of inserted spill code.
710 if (Ins)
711 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000712 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000713 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000714
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000715 // Add constraints for use-blocks. Note that these are the only constraints
716 // that may add a positive bias, it is downhill from here.
717 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000718 return SpillPlacer->scanActiveBundles();
719}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000720
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000721
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000722/// addThroughConstraints - Add constraints and links to SpillPlacer from the
723/// live-through blocks in Blocks.
724void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
725 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000726 const unsigned GroupSize = 8;
727 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000728 unsigned TBS[GroupSize];
729 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000730
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000731 for (unsigned i = 0; i != Blocks.size(); ++i) {
732 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000733 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000734
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000735 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000736 assert(T < GroupSize && "Array overflow");
737 TBS[T] = Number;
738 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000739 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000740 T = 0;
741 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000742 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000743 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000744
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000745 assert(B < GroupSize && "Array overflow");
746 BCS[B].Number = Number;
747
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000748 // Interference for the live-in value.
749 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
750 BCS[B].Entry = SpillPlacement::MustSpill;
751 else
752 BCS[B].Entry = SpillPlacement::PrefSpill;
753
754 // Interference for the live-out value.
755 if (Intf.last() >= SA->getLastSplitPoint(Number))
756 BCS[B].Exit = SpillPlacement::MustSpill;
757 else
758 BCS[B].Exit = SpillPlacement::PrefSpill;
759
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000760 if (++B == GroupSize) {
761 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
762 SpillPlacer->addConstraints(Array);
763 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000764 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000765 }
766
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000767 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
768 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000769 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000770}
771
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000772void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000773 // Keep track of through blocks that have not been added to SpillPlacer.
774 BitVector Todo = SA->getThroughBlocks();
775 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
776 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000777#ifndef NDEBUG
778 unsigned Visited = 0;
779#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000780
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000781 for (;;) {
782 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000783 // Find new through blocks in the periphery of PrefRegBundles.
784 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
785 unsigned Bundle = NewBundles[i];
786 // Look at all blocks connected to Bundle in the full graph.
787 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
788 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
789 I != E; ++I) {
790 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000791 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000792 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000793 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000794 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000795 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000796#ifndef NDEBUG
797 ++Visited;
798#endif
799 }
800 }
801 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000802 if (ActiveBlocks.size() == AddedTo)
803 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000804
805 // Compute through constraints from the interference, or assume that all
806 // through blocks prefer spilling when forming compact regions.
807 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
808 if (Cand.PhysReg)
809 addThroughConstraints(Cand.Intf, NewBlocks);
810 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000811 // Provide a strong negative bias on through blocks to prevent unwanted
812 // liveness on loop backedges.
813 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000814 AddedTo = ActiveBlocks.size();
815
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000816 // Perhaps iterating can enable more bundles?
817 SpillPlacer->iterate();
818 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000819 DEBUG(dbgs() << ", v=" << Visited);
820}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000821
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000822/// calcCompactRegion - Compute the set of edge bundles that should be live
823/// when splitting the current live range into compact regions. Compact
824/// regions can be computed without looking at interference. They are the
825/// regions formed by removing all the live-through blocks from the live range.
826///
827/// Returns false if the current live range is already compact, or if the
828/// compact regions would form single block regions anyway.
829bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
830 // Without any through blocks, the live range is already compact.
831 if (!SA->getNumThroughBlocks())
832 return false;
833
834 // Compact regions don't correspond to any physreg.
835 Cand.reset(IntfCache, 0);
836
837 DEBUG(dbgs() << "Compact region bundles");
838
839 // Use the spill placer to determine the live bundles. GrowRegion pretends
840 // that all the through blocks have interference when PhysReg is unset.
841 SpillPlacer->prepare(Cand.LiveBundles);
842
843 // The static split cost will be zero since Cand.Intf reports no interference.
844 float Cost;
845 if (!addSplitConstraints(Cand.Intf, Cost)) {
846 DEBUG(dbgs() << ", none.\n");
847 return false;
848 }
849
850 growRegion(Cand);
851 SpillPlacer->finish();
852
853 if (!Cand.LiveBundles.any()) {
854 DEBUG(dbgs() << ", none.\n");
855 return false;
856 }
857
858 DEBUG({
859 for (int i = Cand.LiveBundles.find_first(); i>=0;
860 i = Cand.LiveBundles.find_next(i))
861 dbgs() << " EB#" << i;
862 dbgs() << ".\n";
863 });
864 return true;
865}
866
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000867/// calcSpillCost - Compute how expensive it would be to split the live range in
868/// SA around all use blocks instead of forming bundle regions.
869float RAGreedy::calcSpillCost() {
870 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000871 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
872 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
873 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
874 unsigned Number = BI.MBB->getNumber();
875 // We normally only need one spill instruction - a load or a store.
876 Cost += SpillPlacer->getBlockFrequency(Number);
877
878 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000879 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
880 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000881 }
882 return Cost;
883}
884
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000885/// calcGlobalSplitCost - Return the global split cost of following the split
886/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000887/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000888///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000889float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000890 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000891 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000892 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
893 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
894 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000895 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000896 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
897 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
898 unsigned Ins = 0;
899
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000900 if (BI.LiveIn)
901 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
902 if (BI.LiveOut)
903 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000904 if (Ins)
905 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000906 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000907
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000908 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
909 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000910 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
911 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000912 if (!RegIn && !RegOut)
913 continue;
914 if (RegIn && RegOut) {
915 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000916 Cand.Intf.moveToBlock(Number);
917 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000918 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
919 continue;
920 }
921 // live-in / stack-out or stack-in live-out.
922 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000923 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000924 return GlobalCost;
925}
926
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000927/// splitAroundRegion - Split the current live range around the regions
928/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000929///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000930/// Before calling this function, GlobalCand and BundleCand must be initialized
931/// so each bundle is assigned to a valid candidate, or NoCand for the
932/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
933/// objects must be initialized for the current live range, and intervals
934/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000935///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000936/// @param LREdit The LiveRangeEdit object handling the current split.
937/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
938/// must appear in this list.
939void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
940 ArrayRef<unsigned> UsedCands) {
941 // These are the intervals created for new global ranges. We may create more
942 // intervals for local ranges.
943 const unsigned NumGlobalIntvs = LREdit.size();
944 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
945 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000946
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000947 // Isolate even single instructions when dealing with a proper sub-class.
948 // That giarantees register class inflation for the stack interval because it
949 // is all copies.
950 unsigned Reg = SA->getParent().reg;
951 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
952
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000953 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000954 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
955 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
956 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000957 unsigned Number = BI.MBB->getNumber();
958 unsigned IntvIn = 0, IntvOut = 0;
959 SlotIndex IntfIn, IntfOut;
960 if (BI.LiveIn) {
961 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
962 if (CandIn != NoCand) {
963 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
964 IntvIn = Cand.IntvIdx;
965 Cand.Intf.moveToBlock(Number);
966 IntfIn = Cand.Intf.first();
967 }
968 }
969 if (BI.LiveOut) {
970 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
971 if (CandOut != NoCand) {
972 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
973 IntvOut = Cand.IntvIdx;
974 Cand.Intf.moveToBlock(Number);
975 IntfOut = Cand.Intf.last();
976 }
977 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000978
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000979 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000980 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000981 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000982 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000983 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000984 continue;
985 }
986
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000987 if (IntvIn && IntvOut)
988 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
989 else if (IntvIn)
990 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000991 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000992 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000993 }
994
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000995 // Handle live-through blocks. The relevant live-through blocks are stored in
996 // the ActiveBlocks list with each candidate. We need to filter out
997 // duplicates.
998 BitVector Todo = SA->getThroughBlocks();
999 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1000 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1001 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1002 unsigned Number = Blocks[i];
1003 if (!Todo.test(Number))
1004 continue;
1005 Todo.reset(Number);
1006
1007 unsigned IntvIn = 0, IntvOut = 0;
1008 SlotIndex IntfIn, IntfOut;
1009
1010 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1011 if (CandIn != NoCand) {
1012 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1013 IntvIn = Cand.IntvIdx;
1014 Cand.Intf.moveToBlock(Number);
1015 IntfIn = Cand.Intf.first();
1016 }
1017
1018 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1019 if (CandOut != NoCand) {
1020 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1021 IntvOut = Cand.IntvIdx;
1022 Cand.Intf.moveToBlock(Number);
1023 IntfOut = Cand.Intf.last();
1024 }
1025 if (!IntvIn && !IntvOut)
1026 continue;
1027 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1028 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001029 }
1030
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001031 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001032
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001033 SmallVector<unsigned, 8> IntvMap;
1034 SE->finish(&IntvMap);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001035 DebugVars->splitRegister(SA->getParent().reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001036
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001037 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001038 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001039
1040 // Sort out the new intervals created by splitting. We get four kinds:
1041 // - Remainder intervals should not be split again.
1042 // - Candidate intervals can be assigned to Cand.PhysReg.
1043 // - Block-local splits are candidates for local splitting.
1044 // - DCE leftovers should go back on the queue.
1045 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001046 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001047
1048 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001049 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001050 continue;
1051
1052 // Remainder interval. Don't try splitting again, spill if it doesn't
1053 // allocate.
1054 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001055 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001056 continue;
1057 }
1058
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001059 // Global intervals. Allow repeated splitting as long as the number of live
1060 // blocks is strictly decreasing.
1061 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001062 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001063 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1064 << " blocks as original.\n");
1065 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001066 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001067 }
1068 continue;
1069 }
1070
1071 // Other intervals are treated as new. This includes local intervals created
1072 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001073 }
1074
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001075 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001076 MF->verify(this, "After splitting live range around region");
1077}
1078
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001079unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1080 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001081 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001082 unsigned BestCand = NoCand;
1083 float BestCost;
1084 SmallVector<unsigned, 8> UsedCands;
1085
1086 // Check if we can split this live range around a compact region.
1087 bool HasCompact = CompactRegions && calcCompactRegion(GlobalCand.front());
1088 if (HasCompact) {
1089 // Yes, keep GlobalCand[0] as the compact region candidate.
1090 NumCands = 1;
1091 BestCost = HUGE_VALF;
1092 } else {
1093 // No benefit from the compact region, our fallback will be per-block
1094 // splitting. Make sure we find a solution that is cheaper than spilling.
1095 BestCost = Hysteresis * calcSpillCost();
1096 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1097 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001098
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001099 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001100 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001101 // Discard bad candidates before we run out of interference cache cursors.
1102 // This will only affect register classes with a lot of registers (>32).
1103 if (NumCands == IntfCache.getMaxCursors()) {
1104 unsigned WorstCount = ~0u;
1105 unsigned Worst = 0;
1106 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001107 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001108 continue;
1109 unsigned Count = GlobalCand[i].LiveBundles.count();
1110 if (Count < WorstCount)
1111 Worst = i, WorstCount = Count;
1112 }
1113 --NumCands;
1114 GlobalCand[Worst] = GlobalCand[NumCands];
1115 }
1116
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001117 if (GlobalCand.size() <= NumCands)
1118 GlobalCand.resize(NumCands+1);
1119 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1120 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001121
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001122 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001123 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001124 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001125 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001126 continue;
1127 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001128 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001129 if (Cost >= BestCost) {
1130 DEBUG({
1131 if (BestCand == NoCand)
1132 dbgs() << " worse than no bundles\n";
1133 else
1134 dbgs() << " worse than "
1135 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1136 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001137 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001138 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001139 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001140
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001141 SpillPlacer->finish();
1142
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001143 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001144 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001145 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001146 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001147 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001148
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001149 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001150 DEBUG({
1151 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001152 for (int i = Cand.LiveBundles.find_first(); i>=0;
1153 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001154 dbgs() << " EB#" << i;
1155 dbgs() << ".\n";
1156 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001157 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001158 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001159 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001160 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001161 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001162 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001163
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001164 // No solutions found, fall back to single block splitting.
1165 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001166 return 0;
1167
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001168 // Prepare split editor.
1169 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1170 SE->reset(LREdit);
1171
1172 // Assign all edge bundles to the preferred candidate, or NoCand.
1173 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1174
1175 // Assign bundles for the best candidate region.
1176 if (BestCand != NoCand) {
1177 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1178 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1179 UsedCands.push_back(BestCand);
1180 Cand.IntvIdx = SE->openIntv();
1181 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1182 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001183 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001184 }
1185 }
1186
1187 // Assign bundles for the compact region.
1188 if (HasCompact) {
1189 GlobalSplitCandidate &Cand = GlobalCand.front();
1190 assert(!Cand.PhysReg && "Compact region has no physreg");
1191 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1192 UsedCands.push_back(0);
1193 Cand.IntvIdx = SE->openIntv();
1194 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1195 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001196 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001197 }
1198 }
1199
1200 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001201 return 0;
1202}
1203
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001204
1205//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001206// Per-Block Splitting
1207//===----------------------------------------------------------------------===//
1208
1209/// tryBlockSplit - Split a global live range around every block with uses. This
1210/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1211/// they don't allocate.
1212unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1213 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1214 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1215 unsigned Reg = VirtReg.reg;
1216 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1217 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1218 SE->reset(LREdit);
1219 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1220 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1221 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1222 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1223 SE->splitSingleBlock(BI);
1224 }
1225 // No blocks were split.
1226 if (LREdit.empty())
1227 return 0;
1228
1229 // We did split for some blocks.
1230 SE->finish();
1231 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
1232 if (VerifyEnabled)
1233 MF->verify(this, "After splitting live range around basic blocks");
1234 return 0;
1235}
1236
1237//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001238// Local Splitting
1239//===----------------------------------------------------------------------===//
1240
1241
1242/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1243/// in order to use PhysReg between two entries in SA->UseSlots.
1244///
1245/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1246///
1247void RAGreedy::calcGapWeights(unsigned PhysReg,
1248 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001249 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1250 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001251 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1252 const unsigned NumGaps = Uses.size()-1;
1253
1254 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001255 SlotIndex StartIdx =
1256 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1257 SlotIndex StopIdx =
1258 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001259
1260 GapWeight.assign(NumGaps, 0.0f);
1261
1262 // Add interference from each overlapping register.
1263 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1264 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1265 .checkInterference())
1266 continue;
1267
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001268 // We know that VirtReg is a continuous interval from FirstInstr to
1269 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001270 //
1271 // Interference that overlaps an instruction is counted in both gaps
1272 // surrounding the instruction. The exception is interference before
1273 // StartIdx and after StopIdx.
1274 //
1275 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1276 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1277 // Skip the gaps before IntI.
1278 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1279 if (++Gap == NumGaps)
1280 break;
1281 if (Gap == NumGaps)
1282 break;
1283
1284 // Update the gaps covered by IntI.
1285 const float weight = IntI.value()->weight;
1286 for (; Gap != NumGaps; ++Gap) {
1287 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1288 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1289 break;
1290 }
1291 if (Gap == NumGaps)
1292 break;
1293 }
1294 }
1295}
1296
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001297/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1298/// basic block.
1299///
1300unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1301 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001302 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1303 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001304
1305 // Note that it is possible to have an interval that is live-in or live-out
1306 // while only covering a single block - A phi-def can use undef values from
1307 // predecessors, and the block could be a single-block loop.
1308 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001309 // that the interval is continuous from FirstInstr to LastInstr. We should
1310 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001311
1312 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1313 if (Uses.size() <= 2)
1314 return 0;
1315 const unsigned NumGaps = Uses.size()-1;
1316
1317 DEBUG({
1318 dbgs() << "tryLocalSplit: ";
1319 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1320 dbgs() << ' ' << SA->UseSlots[i];
1321 dbgs() << '\n';
1322 });
1323
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001324 // Since we allow local split results to be split again, there is a risk of
1325 // creating infinite loops. It is tempting to require that the new live
1326 // ranges have less instructions than the original. That would guarantee
1327 // convergence, but it is too strict. A live range with 3 instructions can be
1328 // split 2+3 (including the COPY), and we want to allow that.
1329 //
1330 // Instead we use these rules:
1331 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001332 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001333 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001334 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001335 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001336 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001337 // smaller ranges are marked RS_New.
1338 //
1339 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1340 // excessive splitting and infinite loops.
1341 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001342 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001343
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001344 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001345 unsigned BestBefore = NumGaps;
1346 unsigned BestAfter = 0;
1347 float BestDiff = 0;
1348
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001349 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001350 SmallVector<float, 8> GapWeight;
1351
1352 Order.rewind();
1353 while (unsigned PhysReg = Order.next()) {
1354 // Keep track of the largest spill weight that would need to be evicted in
1355 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1356 calcGapWeights(PhysReg, GapWeight);
1357
1358 // Try to find the best sequence of gaps to close.
1359 // The new spill weight must be larger than any gap interference.
1360
1361 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001362 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001363
1364 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1365 // It is the spill weight that needs to be evicted.
1366 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001367
1368 for (;;) {
1369 // Live before/after split?
1370 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1371 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1372
1373 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1374 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1375 << " i=" << MaxGap);
1376
1377 // Stop before the interval gets so big we wouldn't be making progress.
1378 if (!LiveBefore && !LiveAfter) {
1379 DEBUG(dbgs() << " all\n");
1380 break;
1381 }
1382 // Should the interval be extended or shrunk?
1383 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001384
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001385 // How many gaps would the new range have?
1386 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1387
1388 // Legally, without causing looping?
1389 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1390
1391 if (Legal && MaxGap < HUGE_VALF) {
1392 // Estimate the new spill weight. Each instruction reads or writes the
1393 // register. Conservatively assume there are no read-modify-write
1394 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001395 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001396 // Try to guess the size of the new interval.
1397 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1398 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1399 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001400 // Would this split be possible to allocate?
1401 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001402 DEBUG(dbgs() << " w=" << EstWeight);
1403 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001404 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001405 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001406 if (Diff > BestDiff) {
1407 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001408 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001409 BestBefore = SplitBefore;
1410 BestAfter = SplitAfter;
1411 }
1412 }
1413 }
1414
1415 // Try to shrink.
1416 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001417 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001418 DEBUG(dbgs() << " shrink\n");
1419 // Recompute the max when necessary.
1420 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1421 MaxGap = GapWeight[SplitBefore];
1422 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1423 MaxGap = std::max(MaxGap, GapWeight[i]);
1424 }
1425 continue;
1426 }
1427 MaxGap = 0;
1428 }
1429
1430 // Try to extend the interval.
1431 if (SplitAfter >= NumGaps) {
1432 DEBUG(dbgs() << " end\n");
1433 break;
1434 }
1435
1436 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001437 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001438 }
1439 }
1440
1441 // Didn't find any candidates?
1442 if (BestBefore == NumGaps)
1443 return 0;
1444
1445 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1446 << '-' << Uses[BestAfter] << ", " << BestDiff
1447 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1448
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001449 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001450 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001451
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001452 SE->openIntv();
1453 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1454 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1455 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001456 SmallVector<unsigned, 8> IntvMap;
1457 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001458 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001459
1460 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001461 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001462 // leave the new intervals as RS_New so they can compete.
1463 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1464 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1465 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1466 if (NewGaps >= NumGaps) {
1467 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1468 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001469 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1470 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001471 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001472 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1473 }
1474 DEBUG(dbgs() << '\n');
1475 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001476 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001477
1478 return 0;
1479}
1480
1481//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001482// Live Range Splitting
1483//===----------------------------------------------------------------------===//
1484
1485/// trySplit - Try to split VirtReg or one of its interferences, making it
1486/// assignable.
1487/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1488unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1489 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001490 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001491 if (LIS->intervalIsInOneMBB(VirtReg)) {
1492 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001493 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001494 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001495 }
1496
1497 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001498
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001499 // Ranges must be Split2 or less.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001500 if (getStage(VirtReg) >= RS_Spill)
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001501 return 0;
1502
1503 SA->analyze(&VirtReg);
1504
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001505 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1506 // coalescer. That may cause the range to become allocatable which means that
1507 // tryRegionSplit won't be making progress. This check should be replaced with
1508 // an assertion when the coalescer is fixed.
1509 if (SA->didRepairRange()) {
1510 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001511 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001512 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1513 return PhysReg;
1514 }
1515
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001516 // First try to split around a region spanning multiple blocks. RS_Split2
1517 // ranges already made dubious progress with region splitting, so they go
1518 // straight to single block splitting.
1519 if (getStage(VirtReg) < RS_Split2) {
1520 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1521 if (PhysReg || !NewVRegs.empty())
1522 return PhysReg;
1523 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001524
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001525 // Then isolate blocks.
1526 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001527}
1528
1529
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001530//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001531// Main Entry Point
1532//===----------------------------------------------------------------------===//
1533
1534unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001535 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001536 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001537 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001538 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1539 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001540
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001541 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001542 DEBUG(dbgs() << StageName[Stage]
1543 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001544
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001545 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001546 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001547 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001548 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001549 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1550 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001551
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001552 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1553
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001554 // The first time we see a live range, don't try to split or spill.
1555 // Wait until the second time, when all smaller ranges have been allocated.
1556 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001557 if (Stage < RS_Split) {
1558 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001559 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001560 NewVRegs.push_back(&VirtReg);
1561 return 0;
1562 }
1563
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001564 // If we couldn't allocate a register from spilling, there is probably some
1565 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001566 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001567 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001568
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001569 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001570 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1571 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001572 return PhysReg;
1573
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001574 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001575 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001576 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1577 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001578 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001579
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001580 if (VerifyEnabled)
1581 MF->verify(this, "After spilling");
1582
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001583 // The live virtual register requesting allocation was spilled, so tell
1584 // the caller not to allocate anything during this round.
1585 return 0;
1586}
1587
1588bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1589 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1590 << "********** Function: "
1591 << ((Value*)mf.getFunction())->getName() << '\n');
1592
1593 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001594 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001595 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001596
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001597 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001598 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001599 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001600 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001601 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001602 Bundles = &getAnalysis<EdgeBundles>();
1603 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001604 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001605
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001606 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001607 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001608 ExtraRegInfo.clear();
1609 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1610 NextCascade = 1;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001611 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001612 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001613
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001614 allocatePhysRegs();
1615 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001616 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001617
1618 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001619 {
1620 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001621 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001622 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001623
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001624 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenc4769022011-07-31 03:53:42 +00001625 {
1626 NamedRegionTimer T("Emit Debug Info", TimerGroupName, TimePassesIsEnabled);
1627 DebugVars->emitDebugValues(VRM);
1628 }
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001629
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001630 // The pass output is in VirtRegMap. Release all the transient data.
1631 releaseMemory();
1632
1633 return true;
1634}