blob: d0e6a649a01353ac54222d9470b35708d0cbb14e [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"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000037#include "llvm/CodeGen/MachineLoopRanges.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000038#include "llvm/CodeGen/MachineRegisterInfo.h"
39#include "llvm/CodeGen/Passes.h"
40#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Target/TargetOptions.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 Olesencba2e062010-12-08 03:26:16 +000055static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
56 createGreedyRegisterAllocator);
57
58namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000059class RAGreedy : public MachineFunctionPass,
60 public RegAllocBase,
61 private LiveRangeEdit::Delegate {
62
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000063 // context
64 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000065
66 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000067 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000068 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000069 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000070 MachineLoopInfo *Loops;
71 MachineLoopRanges *LoopRanges;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000072 EdgeBundles *Bundles;
73 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000074 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000075
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000076 // state
77 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000078 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000079
80 // Live ranges pass through a number of stages as we try to allocate them.
81 // Some of the stages may also create new live ranges:
82 //
83 // - Region splitting.
84 // - Per-block splitting.
85 // - Local splitting.
86 // - Spilling.
87 //
88 // Ranges produced by one of the stages skip the previous stages when they are
89 // dequeued. This improves performance because we can skip interference checks
90 // that are unlikely to give any results. It also guarantees that the live
91 // range splitting algorithm terminates, something that is otherwise hard to
92 // ensure.
93 enum LiveRangeStage {
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +000094 RS_New, ///< Never seen before.
95 RS_First, ///< First time in the queue.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +000096 RS_Second, ///< Second time in the queue.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +000097 RS_Global, ///< Produced by global splitting.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000098 RS_Local, ///< Produced by local splitting.
99 RS_Spill ///< Produced by spilling.
100 };
101
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000102 static const char *const StageName[];
103
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000104 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
105
106 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
107 return LiveRangeStage(LRStage[VirtReg.reg]);
108 }
109
110 template<typename Iterator>
111 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
112 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000113 for (;Begin != End; ++Begin) {
114 unsigned Reg = (*Begin)->reg;
115 if (LRStage[Reg] == RS_New)
116 LRStage[Reg] = NewStage;
117 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000118 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000119
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000120 // Eviction. Sometimes an assigned live range can be evicted without
121 // conditions, but other times it must be split after being evicted to avoid
122 // infinite loops.
123 enum CanEvict {
124 CE_Never, ///< Can never evict.
125 CE_Always, ///< Can always evict.
126 CE_WithSplit ///< Can evict only if range is also split or spilled.
127 };
128
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000129 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000130 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000131 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000132
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000133 /// Cached per-block interference maps
134 InterferenceCache IntfCache;
135
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000136 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000137 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000138
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000139 /// Global live range splitting candidate info.
140 struct GlobalSplitCandidate {
141 unsigned PhysReg;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000142 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000143 SmallVector<unsigned, 8> ActiveBlocks;
144
145 void reset(unsigned Reg) {
146 PhysReg = Reg;
147 LiveBundles.clear();
148 ActiveBlocks.clear();
149 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000150 };
151
152 /// Candidate info for for each PhysReg in AllocationOrder.
153 /// This vector never shrinks, but grows to the size of the largest register
154 /// class.
155 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
156
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000157public:
158 RAGreedy();
159
160 /// Return the pass name.
161 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000162 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000163 }
164
165 /// RAGreedy analysis usage.
166 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000167 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000168 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000169 virtual void enqueue(LiveInterval *LI);
170 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000171 virtual unsigned selectOrSplit(LiveInterval&,
172 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000173
174 /// Perform register allocation.
175 virtual bool runOnMachineFunction(MachineFunction &mf);
176
177 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000178
179private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000180 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000181 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000182 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000183 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000184
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000185 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000186 bool addSplitConstraints(InterferenceCache::Cursor, float&);
187 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000188 void growRegion(GlobalSplitCandidate &Cand, InterferenceCache::Cursor);
189 float calcGlobalSplitCost(GlobalSplitCandidate&, InterferenceCache::Cursor);
190 void splitAroundRegion(LiveInterval&, GlobalSplitCandidate&,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000191 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000192 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000193 CanEvict canEvict(LiveInterval &A, LiveInterval &B);
194 bool canEvictInterference(LiveInterval&, unsigned, float&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000195
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000196 unsigned tryAssign(LiveInterval&, AllocationOrder&,
197 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000198 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000199 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000200 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
201 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000202 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
203 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000204 unsigned trySplit(LiveInterval&, AllocationOrder&,
205 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000206};
207} // end anonymous namespace
208
209char RAGreedy::ID = 0;
210
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000211#ifndef NDEBUG
212const char *const RAGreedy::StageName[] = {
213 "RS_New",
214 "RS_First",
215 "RS_Second",
216 "RS_Global",
217 "RS_Local",
218 "RS_Spill"
219};
220#endif
221
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000222// Hysteresis to use when comparing floats.
223// This helps stabilize decisions based on float comparisons.
224const float Hysteresis = 0.98f;
225
226
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000227FunctionPass* llvm::createGreedyRegisterAllocator() {
228 return new RAGreedy();
229}
230
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000231RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_New) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000232 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000233 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000234 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
235 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
236 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000237 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000238 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
239 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
240 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
241 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000242 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000243 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000244 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
245 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000246}
247
248void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
249 AU.setPreservesCFG();
250 AU.addRequired<AliasAnalysis>();
251 AU.addPreserved<AliasAnalysis>();
252 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000253 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000254 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000255 AU.addRequired<LiveDebugVariables>();
256 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000257 if (StrongPHIElim)
258 AU.addRequiredID(StrongPHIEliminationID);
259 AU.addRequiredTransitive<RegisterCoalescer>();
260 AU.addRequired<CalculateSpillWeights>();
261 AU.addRequired<LiveStacks>();
262 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000263 AU.addRequired<MachineDominatorTree>();
264 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000265 AU.addRequired<MachineLoopInfo>();
266 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000267 AU.addRequired<MachineLoopRanges>();
268 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000269 AU.addRequired<VirtRegMap>();
270 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000271 AU.addRequired<EdgeBundles>();
272 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000273 MachineFunctionPass::getAnalysisUsage(AU);
274}
275
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000276
277//===----------------------------------------------------------------------===//
278// LiveRangeEdit delegate methods
279//===----------------------------------------------------------------------===//
280
281void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
282 // LRE itself will remove from SlotIndexes and parent basic block.
283 VRM->RemoveMachineInstrFromMaps(MI);
284}
285
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000286bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
287 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
288 unassign(LIS->getInterval(VirtReg), PhysReg);
289 return true;
290 }
291 // Unassigned virtreg is probably in the priority queue.
292 // RegAllocBase will erase it after dequeueing.
293 return false;
294}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000295
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000296void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
297 unsigned PhysReg = VRM->getPhys(VirtReg);
298 if (!PhysReg)
299 return;
300
301 // Register is assigned, put it back on the queue for reassignment.
302 LiveInterval &LI = LIS->getInterval(VirtReg);
303 unassign(LI, PhysReg);
304 enqueue(&LI);
305}
306
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000307void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
308 // LRE may clone a virtual register because dead code elimination causes it to
309 // be split into connected components. Ensure that the new register gets the
310 // same stage as the parent.
311 LRStage.grow(New);
312 LRStage[New] = LRStage[Old];
313}
314
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000315void RAGreedy::releaseMemory() {
316 SpillerInstance.reset(0);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000317 LRStage.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000318 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000319 RegAllocBase::releaseMemory();
320}
321
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000322void RAGreedy::enqueue(LiveInterval *LI) {
323 // Prioritize live ranges by size, assigning larger ranges first.
324 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000325 const unsigned Size = LI->getSize();
326 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000327 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
328 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000329 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000330
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000331 LRStage.grow(Reg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000332 if (LRStage[Reg] == RS_New)
333 LRStage[Reg] = RS_First;
334
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000335 if (LRStage[Reg] == RS_Second)
336 // Unsplit ranges that couldn't be allocated immediately are deferred until
337 // everything else has been allocated. Long ranges are allocated last so
338 // they are split against realistic interference.
339 Prio = (1u << 31) - Size;
340 else {
341 // Everything else is allocated in long->short order. Long ranges that don't
342 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000343 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000344
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000345 // Boost ranges that have a physical register hint.
346 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
347 Prio |= (1u << 30);
348 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000349
350 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000351}
352
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000353LiveInterval *RAGreedy::dequeue() {
354 if (Queue.empty())
355 return 0;
356 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
357 Queue.pop();
358 return LI;
359}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000360
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000361
362//===----------------------------------------------------------------------===//
363// Direct Assignment
364//===----------------------------------------------------------------------===//
365
366/// tryAssign - Try to assign VirtReg to an available register.
367unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
368 AllocationOrder &Order,
369 SmallVectorImpl<LiveInterval*> &NewVRegs) {
370 Order.rewind();
371 unsigned PhysReg;
372 while ((PhysReg = Order.next()))
373 if (!checkPhysRegInterference(VirtReg, PhysReg))
374 break;
375 if (!PhysReg || Order.isHint(PhysReg))
376 return PhysReg;
377
378 // PhysReg is available. Try to evict interference from a cheaper alternative.
379 unsigned Cost = TRI->getCostPerUse(PhysReg);
380
381 // Most registers have 0 additional cost.
382 if (!Cost)
383 return PhysReg;
384
385 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
386 << '\n');
387 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
388 return CheapReg ? CheapReg : PhysReg;
389}
390
391
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000392//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000393// Interference eviction
394//===----------------------------------------------------------------------===//
395
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000396/// canEvict - determine if A can evict the assigned live range B. The eviction
397/// policy defined by this function together with the allocation order defined
398/// by enqueue() decides which registers ultimately end up being split and
399/// spilled.
400///
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000401/// This function must define a non-circular relation when it returns CE_Always,
402/// otherwise infinite eviction loops are possible. When evicting a <= RS_Second
403/// range, it is possible to return CE_WithSplit which forces the evicted
404/// register to be split or spilled before it can evict anything again. That
405/// guarantees progress.
406RAGreedy::CanEvict RAGreedy::canEvict(LiveInterval &A, LiveInterval &B) {
407 return A.weight > B.weight ? CE_Always : CE_Never;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000408}
409
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000410/// canEvict - Return true if all interferences between VirtReg and PhysReg can
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000411/// be evicted.
412/// Return false if any interference is heavier than MaxWeight.
413/// On return, set MaxWeight to the maximal spill weight of an interference.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000414bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000415 float &MaxWeight) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000416 float Weight = 0;
417 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
418 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000419 // If there is 10 or more interferences, chances are one is heavier.
420 if (Q.collectInterferingVRegs(10, MaxWeight) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000421 return false;
422
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000423 // Check if any interfering live range is heavier than MaxWeight.
424 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
425 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000426 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
427 return false;
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000428 if (Intf->weight >= MaxWeight)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000429 return false;
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000430 switch (canEvict(VirtReg, *Intf)) {
431 case CE_Always:
432 break;
433 case CE_Never:
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000434 return false;
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000435 case CE_WithSplit:
436 if (getStage(*Intf) > RS_Second)
437 return false;
438 break;
439 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000440 Weight = std::max(Weight, Intf->weight);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000441 }
442 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000443 MaxWeight = Weight;
444 return true;
445}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000446
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000447/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000448/// @param VirtReg Currently unassigned virtual register.
449/// @param Order Physregs to try.
450/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000451unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
452 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000453 SmallVectorImpl<LiveInterval*> &NewVRegs,
454 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000455 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
456
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000457 // Keep track of the lightest single interference seen so far.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000458 float BestWeight = HUGE_VALF;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000459 unsigned BestPhys = 0;
460
461 Order.rewind();
462 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000463 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
464 continue;
465 // The first use of a register in a function has cost 1.
466 if (CostPerUseLimit == 1 && !MRI->isPhysRegUsed(PhysReg))
467 continue;
468
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000469 float Weight = BestWeight;
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000470 if (!canEvictInterference(VirtReg, PhysReg, Weight))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000471 continue;
472
473 // This is an eviction candidate.
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000474 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " interference = "
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000475 << Weight << '\n');
476 if (BestPhys && Weight >= BestWeight)
477 continue;
478
479 // Best so far.
480 BestPhys = PhysReg;
481 BestWeight = Weight;
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000482 // Stop if the hint can be used.
483 if (Order.isHint(PhysReg))
484 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000485 }
486
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000487 if (!BestPhys)
488 return 0;
489
490 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
491 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
492 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
493 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
494 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
495 LiveInterval *Intf = Q.interferingVRegs()[i];
496 unassign(*Intf, VRM->getPhys(Intf->reg));
497 ++NumEvicted;
498 NewVRegs.push_back(Intf);
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000499 // Prevent looping by forcing the evicted ranges to be split before they
500 // can evict anything else.
501 if (getStage(*Intf) < RS_Second &&
502 canEvict(VirtReg, *Intf) == CE_WithSplit)
503 LRStage[Intf->reg] = RS_Second;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000504 }
505 }
506 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000507}
508
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000509
510//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000511// Region Splitting
512//===----------------------------------------------------------------------===//
513
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000514/// addSplitConstraints - Fill out the SplitConstraints vector based on the
515/// interference pattern in Physreg and its aliases. Add the constraints to
516/// SpillPlacement and return the static cost of this split in Cost, assuming
517/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000518/// Return false if there are no bundles with positive bias.
519bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
520 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000521 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000522
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000523 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000524 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000525 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000526 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
527 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000528 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000529
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000530 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000531 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000532 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
533 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000534
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000535 if (!Intf.hasInterference())
536 continue;
537
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000538 // Number of spill code instructions to insert.
539 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000540
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000541 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000542 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000543 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000544 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000545 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000546 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000547 else if (Intf.first() < BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000548 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000549 }
550
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000551 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000552 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000553 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000554 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000555 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000556 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000557 else if (Intf.last() > BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000558 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000559 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000560
561 // Accumulate the total frequency of inserted spill code.
562 if (Ins)
563 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000564 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000565 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000566
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000567 // Add constraints for use-blocks. Note that these are the only constraints
568 // that may add a positive bias, it is downhill from here.
569 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000570 return SpillPlacer->scanActiveBundles();
571}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000572
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000573
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000574/// addThroughConstraints - Add constraints and links to SpillPlacer from the
575/// live-through blocks in Blocks.
576void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
577 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000578 const unsigned GroupSize = 8;
579 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000580 unsigned TBS[GroupSize];
581 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000582
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000583 for (unsigned i = 0; i != Blocks.size(); ++i) {
584 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000585 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000586
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000587 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000588 assert(T < GroupSize && "Array overflow");
589 TBS[T] = Number;
590 if (++T == GroupSize) {
591 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
592 T = 0;
593 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000594 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000595 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000596
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000597 assert(B < GroupSize && "Array overflow");
598 BCS[B].Number = Number;
599
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000600 // Interference for the live-in value.
601 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
602 BCS[B].Entry = SpillPlacement::MustSpill;
603 else
604 BCS[B].Entry = SpillPlacement::PrefSpill;
605
606 // Interference for the live-out value.
607 if (Intf.last() >= SA->getLastSplitPoint(Number))
608 BCS[B].Exit = SpillPlacement::MustSpill;
609 else
610 BCS[B].Exit = SpillPlacement::PrefSpill;
611
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000612 if (++B == GroupSize) {
613 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
614 SpillPlacer->addConstraints(Array);
615 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000616 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000617 }
618
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000619 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
620 SpillPlacer->addConstraints(Array);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000621 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000622}
623
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000624void RAGreedy::growRegion(GlobalSplitCandidate &Cand,
625 InterferenceCache::Cursor Intf) {
626 // Keep track of through blocks that have not been added to SpillPlacer.
627 BitVector Todo = SA->getThroughBlocks();
628 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
629 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000630#ifndef NDEBUG
631 unsigned Visited = 0;
632#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000633
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000634 for (;;) {
635 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
636 if (NewBundles.empty())
637 break;
638 // Find new through blocks in the periphery of PrefRegBundles.
639 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
640 unsigned Bundle = NewBundles[i];
641 // Look at all blocks connected to Bundle in the full graph.
642 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
643 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
644 I != E; ++I) {
645 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000646 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000647 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000648 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000649 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000650 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000651#ifndef NDEBUG
652 ++Visited;
653#endif
654 }
655 }
656 // Any new blocks to add?
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000657 if (ActiveBlocks.size() > AddedTo) {
658 ArrayRef<unsigned> Add(&ActiveBlocks[AddedTo],
659 ActiveBlocks.size() - AddedTo);
660 addThroughConstraints(Intf, Add);
661 AddedTo = ActiveBlocks.size();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000662 }
663 // Perhaps iterating can enable more bundles?
664 SpillPlacer->iterate();
665 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000666 DEBUG(dbgs() << ", v=" << Visited);
667}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000668
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000669/// calcSpillCost - Compute how expensive it would be to split the live range in
670/// SA around all use blocks instead of forming bundle regions.
671float RAGreedy::calcSpillCost() {
672 float Cost = 0;
673 const LiveInterval &LI = SA->getParent();
674 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
675 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
676 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
677 unsigned Number = BI.MBB->getNumber();
678 // We normally only need one spill instruction - a load or a store.
679 Cost += SpillPlacer->getBlockFrequency(Number);
680
681 // Unless the value is redefined in the block.
682 if (BI.LiveIn && BI.LiveOut) {
683 SlotIndex Start, Stop;
684 tie(Start, Stop) = Indexes->getMBBRange(Number);
685 LiveInterval::const_iterator I = LI.find(Start);
686 assert(I != LI.end() && "Expected live-in value");
687 // Is there a different live-out value? If so, we need an extra spill
688 // instruction.
689 if (I->end < Stop)
690 Cost += SpillPlacer->getBlockFrequency(Number);
691 }
692 }
693 return Cost;
694}
695
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000696/// calcGlobalSplitCost - Return the global split cost of following the split
697/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000698/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000699///
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000700float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
701 InterferenceCache::Cursor Intf) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000702 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000703 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000704 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
705 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
706 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000707 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000708 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
709 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
710 unsigned Ins = 0;
711
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000712 if (BI.LiveIn)
713 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
714 if (BI.LiveOut)
715 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000716 if (Ins)
717 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000718 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000719
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000720 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
721 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000722 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
723 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000724 if (!RegIn && !RegOut)
725 continue;
726 if (RegIn && RegOut) {
727 // We need double spill code if this block has interference.
728 Intf.moveToBlock(Number);
729 if (Intf.hasInterference())
730 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
731 continue;
732 }
733 // live-in / stack-out or stack-in live-out.
734 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000735 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000736 return GlobalCost;
737}
738
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000739/// splitAroundRegion - Split VirtReg around the region determined by
740/// LiveBundles. Make an effort to avoid interference from PhysReg.
741///
742/// The 'register' interval is going to contain as many uses as possible while
743/// avoiding interference. The 'stack' interval is the complement constructed by
744/// SplitEditor. It will contain the rest.
745///
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000746void RAGreedy::splitAroundRegion(LiveInterval &VirtReg,
747 GlobalSplitCandidate &Cand,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000748 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000749 const BitVector &LiveBundles = Cand.LiveBundles;
750
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000751 DEBUG({
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000752 dbgs() << "Splitting around region for " << PrintReg(Cand.PhysReg, TRI)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000753 << " with bundles";
754 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
755 dbgs() << " EB#" << i;
756 dbgs() << ".\n";
757 });
758
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000759 InterferenceCache::Cursor Intf(IntfCache, Cand.PhysReg);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000760 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000761 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000762
763 // Create the main cross-block interval.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000764 const unsigned MainIntv = SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000765
766 // First add all defs that are live out of a block.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000767 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
768 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
769 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000770 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
771 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
772
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000773 // Create separate intervals for isolated blocks with multiple uses.
774 if (!RegIn && !RegOut && BI.FirstUse != BI.LastUse) {
775 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
776 SE->splitSingleBlock(BI);
777 SE->selectIntv(MainIntv);
778 continue;
779 }
780
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000781 // Should the register be live out?
782 if (!BI.LiveOut || !RegOut)
783 continue;
784
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000785 SlotIndex Start, Stop;
786 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000787 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000788 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000789 << Bundles->getBundle(BI.MBB->getNumber(), 1)
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000790 << " [" << Start << ';'
791 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
792 << ") intf [" << Intf.first() << ';' << Intf.last() << ')');
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000793
794 // The interference interval should either be invalid or overlap MBB.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000795 assert((!Intf.hasInterference() || Intf.first() < Stop)
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000796 && "Bad interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000797 assert((!Intf.hasInterference() || Intf.last() > Start)
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000798 && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000799
800 // Check interference leaving the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000801 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000802 // Block is interference-free.
803 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000804 if (!BI.LiveThrough) {
805 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000806 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000807 continue;
808 }
809 if (!RegIn) {
810 // Block is live-through, but entry bundle is on the stack.
811 // Reload just before the first use.
812 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000813 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000814 continue;
815 }
816 DEBUG(dbgs() << ", live-through.\n");
817 continue;
818 }
819
820 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000821 DEBUG(dbgs() << ", interference to " << Intf.last());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000822
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000823 if (!BI.LiveThrough && Intf.last() <= BI.FirstUse) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000824 // The interference doesn't reach the outgoing segment.
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000825 DEBUG(dbgs() << " doesn't affect def from " << BI.FirstUse << '\n');
826 SE->useIntv(BI.FirstUse, Stop);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000827 continue;
828 }
829
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000830 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000831 if (Intf.last().getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000832 // There are interference-free uses at the end of the block.
833 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000834 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000835 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000836 Intf.last().getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000837 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
838 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000839 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000840 // Only attempt a split befroe the last split point.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000841 if (Use.getBaseIndex() <= LastSplitPoint) {
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000842 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000843 SlotIndex SegStart = SE->enterIntvBefore(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000844 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000845 assert(SegStart < LastSplitPoint && "Impossible split point");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000846 SE->useIntv(SegStart, Stop);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000847 continue;
848 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000849 }
850
851 // Interference is after the last use.
852 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000853 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000854 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000855 }
856
857 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000858 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
859 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000860 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
861 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
862
863 // Is the register live-in?
864 if (!BI.LiveIn || !RegIn)
865 continue;
866
867 // We have an incoming register. Check for interference.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000868 SlotIndex Start, Stop;
869 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000870 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000871 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000872 << " -> BB#" << BI.MBB->getNumber() << " [" << Start << ';'
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000873 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
874 << ')');
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000875
876 // Check interference entering the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000877 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000878 // Block is interference-free.
879 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000880 if (!BI.LiveThrough) {
881 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000882 SE->useIntv(Start, SE->leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000883 continue;
884 }
885 if (!RegOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000886 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000887 // Block is live-through, but exit bundle is on the stack.
888 // Spill immediately after the last use.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000889 if (BI.LastUse < LastSplitPoint) {
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000890 DEBUG(dbgs() << ", uses, stack-out.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000891 SE->useIntv(Start, SE->leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000892 continue;
893 }
894 // The last use is after the last split point, it is probably an
895 // indirect jump.
896 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000897 << LastSplitPoint << ", stack-out.\n");
898 SlotIndex SegEnd = SE->leaveIntvBefore(LastSplitPoint);
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000899 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000900 // Run a double interval from the split to the last use.
901 // This makes it possible to spill the complement without affecting the
902 // indirect branch.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000903 SE->overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000904 continue;
905 }
906 // Register is live-through.
907 DEBUG(dbgs() << ", uses, live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000908 SE->useIntv(Start, Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000909 continue;
910 }
911
912 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000913 DEBUG(dbgs() << ", interference from " << Intf.first());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000914
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000915 if (!BI.LiveThrough && Intf.first() >= BI.LastUse) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000916 // The interference doesn't reach the outgoing segment.
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000917 DEBUG(dbgs() << " doesn't affect kill at " << BI.LastUse << '\n');
918 SE->useIntv(Start, BI.LastUse);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000919 continue;
920 }
921
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000922 if (Intf.first().getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000923 // There are interference-free uses at the beginning of the block.
924 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000925 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000926 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000927 Intf.first().getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000928 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
929 SlotIndex Use = (--UI)->getBoundaryIndex();
930 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000931 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000932 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000933 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000934 continue;
935 }
936
937 // Interference is before the first use.
938 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000939 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000940 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000941 }
942
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000943 // Handle live-through blocks.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000944 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
945 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000946 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
947 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
948 DEBUG(dbgs() << "Live through BB#" << Number << '\n');
949 if (RegIn && RegOut) {
950 Intf.moveToBlock(Number);
951 if (!Intf.hasInterference()) {
952 SE->useIntv(Indexes->getMBBStartIdx(Number),
953 Indexes->getMBBEndIdx(Number));
954 continue;
955 }
956 }
957 MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
958 if (RegIn)
959 SE->leaveIntvAtTop(*MBB);
960 if (RegOut)
961 SE->enterIntvAtEnd(*MBB);
962 }
963
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000964 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000965
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000966 SmallVector<unsigned, 8> IntvMap;
967 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000968 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
969
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000970 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +0000971 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000972
973 // Sort out the new intervals created by splitting. We get four kinds:
974 // - Remainder intervals should not be split again.
975 // - Candidate intervals can be assigned to Cand.PhysReg.
976 // - Block-local splits are candidates for local splitting.
977 // - DCE leftovers should go back on the queue.
978 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
979 unsigned Reg = LREdit.get(i)->reg;
980
981 // Ignore old intervals from DCE.
982 if (LRStage[Reg] != RS_New)
983 continue;
984
985 // Remainder interval. Don't try splitting again, spill if it doesn't
986 // allocate.
987 if (IntvMap[i] == 0) {
988 LRStage[Reg] = RS_Global;
989 continue;
990 }
991
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000992 // Main interval. Allow repeated splitting as long as the number of live
993 // blocks is strictly decreasing.
994 if (IntvMap[i] == MainIntv) {
995 if (SA->countLiveBlocks(LREdit.get(i)) >= OrigBlocks) {
996 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
997 << " blocks as original.\n");
998 // Don't allow repeated splitting as a safe guard against looping.
999 LRStage[Reg] = RS_Global;
1000 }
1001 continue;
1002 }
1003
1004 // Other intervals are treated as new. This includes local intervals created
1005 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001006 }
1007
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001008 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001009 MF->verify(this, "After splitting live range around region");
1010}
1011
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001012unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1013 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001014 float BestCost = Hysteresis * calcSpillCost();
1015 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001016 const unsigned NoCand = ~0u;
1017 unsigned BestCand = NoCand;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001018
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001019 Order.rewind();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001020 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
1021 if (GlobalCand.size() <= Cand)
1022 GlobalCand.resize(Cand+1);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001023 GlobalCand[Cand].reset(PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001024
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001025 SpillPlacer->prepare(GlobalCand[Cand].LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001026 float Cost;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001027 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
1028 if (!addSplitConstraints(Intf, Cost)) {
1029 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001030 continue;
1031 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001032 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001033 if (Cost >= BestCost) {
1034 DEBUG({
1035 if (BestCand == NoCand)
1036 dbgs() << " worse than no bundles\n";
1037 else
1038 dbgs() << " worse than "
1039 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1040 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001041 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001042 }
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001043 growRegion(GlobalCand[Cand], Intf);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001044
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001045 SpillPlacer->finish();
1046
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001047 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001048 if (!GlobalCand[Cand].LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001049 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001050 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001051 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001052
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001053 Cost += calcGlobalSplitCost(GlobalCand[Cand], Intf);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001054 DEBUG({
1055 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001056 for (int i = GlobalCand[Cand].LiveBundles.find_first(); i>=0;
1057 i = GlobalCand[Cand].LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001058 dbgs() << " EB#" << i;
1059 dbgs() << ".\n";
1060 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001061 if (Cost < BestCost) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001062 BestCand = Cand;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001063 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001064 }
1065 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001066
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001067 if (BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001068 return 0;
1069
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001070 splitAroundRegion(VirtReg, GlobalCand[BestCand], NewVRegs);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001071 return 0;
1072}
1073
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001074
1075//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001076// Local Splitting
1077//===----------------------------------------------------------------------===//
1078
1079
1080/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1081/// in order to use PhysReg between two entries in SA->UseSlots.
1082///
1083/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1084///
1085void RAGreedy::calcGapWeights(unsigned PhysReg,
1086 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001087 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1088 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001089 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1090 const unsigned NumGaps = Uses.size()-1;
1091
1092 // Start and end points for the interference check.
1093 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
1094 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
1095
1096 GapWeight.assign(NumGaps, 0.0f);
1097
1098 // Add interference from each overlapping register.
1099 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1100 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1101 .checkInterference())
1102 continue;
1103
1104 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
1105 // so we don't need InterferenceQuery.
1106 //
1107 // Interference that overlaps an instruction is counted in both gaps
1108 // surrounding the instruction. The exception is interference before
1109 // StartIdx and after StopIdx.
1110 //
1111 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1112 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1113 // Skip the gaps before IntI.
1114 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1115 if (++Gap == NumGaps)
1116 break;
1117 if (Gap == NumGaps)
1118 break;
1119
1120 // Update the gaps covered by IntI.
1121 const float weight = IntI.value()->weight;
1122 for (; Gap != NumGaps; ++Gap) {
1123 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1124 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1125 break;
1126 }
1127 if (Gap == NumGaps)
1128 break;
1129 }
1130 }
1131}
1132
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001133/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1134/// basic block.
1135///
1136unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1137 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001138 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1139 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001140
1141 // Note that it is possible to have an interval that is live-in or live-out
1142 // while only covering a single block - A phi-def can use undef values from
1143 // predecessors, and the block could be a single-block loop.
1144 // We don't bother doing anything clever about such a case, we simply assume
1145 // that the interval is continuous from FirstUse to LastUse. We should make
1146 // sure that we don't do anything illegal to such an interval, though.
1147
1148 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1149 if (Uses.size() <= 2)
1150 return 0;
1151 const unsigned NumGaps = Uses.size()-1;
1152
1153 DEBUG({
1154 dbgs() << "tryLocalSplit: ";
1155 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1156 dbgs() << ' ' << SA->UseSlots[i];
1157 dbgs() << '\n';
1158 });
1159
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001160 // Since we allow local split results to be split again, there is a risk of
1161 // creating infinite loops. It is tempting to require that the new live
1162 // ranges have less instructions than the original. That would guarantee
1163 // convergence, but it is too strict. A live range with 3 instructions can be
1164 // split 2+3 (including the COPY), and we want to allow that.
1165 //
1166 // Instead we use these rules:
1167 //
1168 // 1. Allow any split for ranges with getStage() < RS_Local. (Except for the
1169 // noop split, of course).
1170 // 2. Require progress be made for ranges with getStage() >= RS_Local. All
1171 // the new ranges must have fewer instructions than before the split.
1172 // 3. New ranges with the same number of instructions are marked RS_Local,
1173 // smaller ranges are marked RS_New.
1174 //
1175 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1176 // excessive splitting and infinite loops.
1177 //
1178 bool ProgressRequired = getStage(VirtReg) >= RS_Local;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001179
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001180 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001181 unsigned BestBefore = NumGaps;
1182 unsigned BestAfter = 0;
1183 float BestDiff = 0;
1184
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001185 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001186 SmallVector<float, 8> GapWeight;
1187
1188 Order.rewind();
1189 while (unsigned PhysReg = Order.next()) {
1190 // Keep track of the largest spill weight that would need to be evicted in
1191 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1192 calcGapWeights(PhysReg, GapWeight);
1193
1194 // Try to find the best sequence of gaps to close.
1195 // The new spill weight must be larger than any gap interference.
1196
1197 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001198 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001199
1200 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1201 // It is the spill weight that needs to be evicted.
1202 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001203
1204 for (;;) {
1205 // Live before/after split?
1206 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1207 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1208
1209 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1210 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1211 << " i=" << MaxGap);
1212
1213 // Stop before the interval gets so big we wouldn't be making progress.
1214 if (!LiveBefore && !LiveAfter) {
1215 DEBUG(dbgs() << " all\n");
1216 break;
1217 }
1218 // Should the interval be extended or shrunk?
1219 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001220
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001221 // How many gaps would the new range have?
1222 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1223
1224 // Legally, without causing looping?
1225 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1226
1227 if (Legal && MaxGap < HUGE_VALF) {
1228 // Estimate the new spill weight. Each instruction reads or writes the
1229 // register. Conservatively assume there are no read-modify-write
1230 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001231 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001232 // Try to guess the size of the new interval.
1233 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1234 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1235 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001236 // Would this split be possible to allocate?
1237 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001238 DEBUG(dbgs() << " w=" << EstWeight);
1239 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001240 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001241 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001242 if (Diff > BestDiff) {
1243 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001244 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001245 BestBefore = SplitBefore;
1246 BestAfter = SplitAfter;
1247 }
1248 }
1249 }
1250
1251 // Try to shrink.
1252 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001253 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001254 DEBUG(dbgs() << " shrink\n");
1255 // Recompute the max when necessary.
1256 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1257 MaxGap = GapWeight[SplitBefore];
1258 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1259 MaxGap = std::max(MaxGap, GapWeight[i]);
1260 }
1261 continue;
1262 }
1263 MaxGap = 0;
1264 }
1265
1266 // Try to extend the interval.
1267 if (SplitAfter >= NumGaps) {
1268 DEBUG(dbgs() << " end\n");
1269 break;
1270 }
1271
1272 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001273 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001274 }
1275 }
1276
1277 // Didn't find any candidates?
1278 if (BestBefore == NumGaps)
1279 return 0;
1280
1281 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1282 << '-' << Uses[BestAfter] << ", " << BestDiff
1283 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1284
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001285 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001286 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001287
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001288 SE->openIntv();
1289 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1290 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1291 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001292 SmallVector<unsigned, 8> IntvMap;
1293 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001294 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001295
1296 // If the new range has the same number of instructions as before, mark it as
1297 // RS_Local so the next split will be forced to make progress. Otherwise,
1298 // leave the new intervals as RS_New so they can compete.
1299 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1300 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1301 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1302 if (NewGaps >= NumGaps) {
1303 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1304 assert(!ProgressRequired && "Didn't make progress when it was required.");
1305 LRStage.resize(MRI->getNumVirtRegs());
1306 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1307 if (IntvMap[i] == 1) {
1308 LRStage[LREdit.get(i)->reg] = RS_Local;
1309 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1310 }
1311 DEBUG(dbgs() << '\n');
1312 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001313 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001314
1315 return 0;
1316}
1317
1318//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001319// Live Range Splitting
1320//===----------------------------------------------------------------------===//
1321
1322/// trySplit - Try to split VirtReg or one of its interferences, making it
1323/// assignable.
1324/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1325unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1326 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001327 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001328 if (LIS->intervalIsInOneMBB(VirtReg)) {
1329 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001330 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001331 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001332 }
1333
1334 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001335
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001336 // Don't iterate global splitting.
1337 // Move straight to spilling if this range was produced by a global split.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001338 if (getStage(VirtReg) >= RS_Global)
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001339 return 0;
1340
1341 SA->analyze(&VirtReg);
1342
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001343 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1344 // coalescer. That may cause the range to become allocatable which means that
1345 // tryRegionSplit won't be making progress. This check should be replaced with
1346 // an assertion when the coalescer is fixed.
1347 if (SA->didRepairRange()) {
1348 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001349 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001350 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1351 return PhysReg;
1352 }
1353
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001354 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001355 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1356 if (PhysReg || !NewVRegs.empty())
1357 return PhysReg;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001358
1359 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001360 SplitAnalysis::BlockPtrSet Blocks;
1361 if (SA->getMultiUseBlocks(Blocks)) {
1362 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1363 SE->reset(LREdit);
1364 SE->splitSingleBlocks(Blocks);
1365 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Global);
1366 if (VerifyEnabled)
1367 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001368 }
1369
1370 // Don't assign any physregs.
1371 return 0;
1372}
1373
1374
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001375//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001376// Main Entry Point
1377//===----------------------------------------------------------------------===//
1378
1379unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001380 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001381 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001382 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001383 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1384 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001385
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001386 LiveRangeStage Stage = getStage(VirtReg);
1387 DEBUG(dbgs() << StageName[Stage] << '\n');
1388
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001389 // Try to evict a less worthy live range, but only for ranges from the primary
1390 // queue. The RS_Second ranges already failed to do this, and they should not
1391 // get a second chance until they have been split.
1392 if (Stage != RS_Second)
1393 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1394 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001395
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001396 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1397
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001398 // The first time we see a live range, don't try to split or spill.
1399 // Wait until the second time, when all smaller ranges have been allocated.
1400 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +00001401 if (Stage == RS_First) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001402 LRStage[VirtReg.reg] = RS_Second;
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001403 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001404 NewVRegs.push_back(&VirtReg);
1405 return 0;
1406 }
1407
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001408 // If we couldn't allocate a register from spilling, there is probably some
1409 // invalid inline assembly. The base class wil report it.
1410 if (Stage >= RS_Spill)
1411 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001412
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001413 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001414 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1415 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001416 return PhysReg;
1417
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001418 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001419 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001420 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1421 spiller().spill(LRE);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001422 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001423
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001424 if (VerifyEnabled)
1425 MF->verify(this, "After spilling");
1426
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001427 // The live virtual register requesting allocation was spilled, so tell
1428 // the caller not to allocate anything during this round.
1429 return 0;
1430}
1431
1432bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1433 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1434 << "********** Function: "
1435 << ((Value*)mf.getFunction())->getName() << '\n');
1436
1437 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001438 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001439 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001440
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001441 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001442 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001443 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001444 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001445 Loops = &getAnalysis<MachineLoopInfo>();
1446 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001447 Bundles = &getAnalysis<EdgeBundles>();
1448 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001449 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001450
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001451 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001452 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001453 LRStage.clear();
1454 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001455 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001456
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001457 allocatePhysRegs();
1458 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001459 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001460
1461 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001462 {
1463 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001464 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001465 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001466
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001467 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001468 DebugVars->emitDebugValues(VRM);
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001469
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001470 // The pass output is in VirtRegMap. Release all the transient data.
1471 releaseMemory();
1472
1473 return true;
1474}