blob: 87e08ba199fdf9b9c3799157f5028b996b8762fd [file] [log] [blame]
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001//===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the RAGreedy function pass for register allocation in
11// optimized builds.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000016#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000017#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000018#include "LiveDebugVariables.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000019#include "LiveRangeEdit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000020#include "RegAllocBase.h"
21#include "Spiller.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000022#include "SpillPlacement.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000024#include "VirtRegMap.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000025#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000026#include "llvm/Analysis/AliasAnalysis.h"
27#include "llvm/Function.h"
28#include "llvm/PassAnalysisSupport.h"
29#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000030#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveIntervalAnalysis.h"
32#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000033#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000036#include "llvm/CodeGen/MachineLoopRanges.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000037#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/CodeGen/Passes.h"
39#include "llvm/CodeGen/RegAllocRegistry.h"
40#include "llvm/CodeGen/RegisterCoalescer.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 BitVector ReservedRegs;
66
67 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000068 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000069 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000070 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000071 MachineLoopInfo *Loops;
72 MachineLoopRanges *LoopRanges;
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 Olesen22a1df62011-03-01 21:10:07 +000080
81 // Live ranges pass through a number of stages as we try to allocate them.
82 // Some of the stages may also create new live ranges:
83 //
84 // - Region splitting.
85 // - Per-block splitting.
86 // - Local splitting.
87 // - Spilling.
88 //
89 // Ranges produced by one of the stages skip the previous stages when they are
90 // dequeued. This improves performance because we can skip interference checks
91 // that are unlikely to give any results. It also guarantees that the live
92 // range splitting algorithm terminates, something that is otherwise hard to
93 // ensure.
94 enum LiveRangeStage {
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +000095 RS_New, ///< Never seen before.
96 RS_First, ///< First time in the queue.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000097 RS_Second, ///< Second time in the queue.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +000098 RS_Global, ///< Produced by global splitting.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000099 RS_Local, ///< Produced by local splitting.
100 RS_Spill ///< Produced by spilling.
101 };
102
103 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
104
105 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
106 return LiveRangeStage(LRStage[VirtReg.reg]);
107 }
108
109 template<typename Iterator>
110 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
111 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000112 for (;Begin != End; ++Begin) {
113 unsigned Reg = (*Begin)->reg;
114 if (LRStage[Reg] == RS_New)
115 LRStage[Reg] = NewStage;
116 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000117 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000118
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000119 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000120 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000121 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000122
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000123 /// Cached per-block interference maps
124 InterferenceCache IntfCache;
125
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000126 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000127 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000128
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000129 /// Global live range splitting candidate info.
130 struct GlobalSplitCandidate {
131 unsigned PhysReg;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000132 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000133 SmallVector<unsigned, 8> ActiveBlocks;
134
135 void reset(unsigned Reg) {
136 PhysReg = Reg;
137 LiveBundles.clear();
138 ActiveBlocks.clear();
139 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000140 };
141
142 /// Candidate info for for each PhysReg in AllocationOrder.
143 /// This vector never shrinks, but grows to the size of the largest register
144 /// class.
145 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
146
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000147 /// For every instruction in SA->UseSlots, store the previous non-copy
148 /// instruction.
149 SmallVector<SlotIndex, 8> PrevSlot;
150
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000151public:
152 RAGreedy();
153
154 /// Return the pass name.
155 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000156 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000157 }
158
159 /// RAGreedy analysis usage.
160 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000161 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000162 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000163 virtual void enqueue(LiveInterval *LI);
164 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000165 virtual unsigned selectOrSplit(LiveInterval&,
166 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000167
168 /// Perform register allocation.
169 virtual bool runOnMachineFunction(MachineFunction &mf);
170
171 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000172
173private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000174 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000175 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000176 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000177 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000178
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000179 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000180 bool addSplitConstraints(InterferenceCache::Cursor, float&);
181 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000182 void growRegion(GlobalSplitCandidate &Cand, InterferenceCache::Cursor);
183 float calcGlobalSplitCost(GlobalSplitCandidate&, InterferenceCache::Cursor);
184 void splitAroundRegion(LiveInterval&, GlobalSplitCandidate&,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000185 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000186 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
187 SlotIndex getPrevMappedIndex(const MachineInstr*);
188 void calcPrevSlots();
189 unsigned nextSplitPoint(unsigned);
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000190 bool canEvictInterference(LiveInterval&, unsigned, float&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000191
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000192 unsigned tryAssign(LiveInterval&, AllocationOrder&,
193 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000194 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000195 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000196 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
197 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000198 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
199 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000200 unsigned trySplit(LiveInterval&, AllocationOrder&,
201 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000202};
203} // end anonymous namespace
204
205char RAGreedy::ID = 0;
206
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000207// Hysteresis to use when comparing floats.
208// This helps stabilize decisions based on float comparisons.
209const float Hysteresis = 0.98f;
210
211
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000212FunctionPass* llvm::createGreedyRegisterAllocator() {
213 return new RAGreedy();
214}
215
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000216RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_New) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000217 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000218 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000219 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
220 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
221 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
222 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
223 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
224 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
225 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
226 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000227 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000228 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000229 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
230 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000231}
232
233void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
234 AU.setPreservesCFG();
235 AU.addRequired<AliasAnalysis>();
236 AU.addPreserved<AliasAnalysis>();
237 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000238 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000239 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000240 AU.addRequired<LiveDebugVariables>();
241 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000242 if (StrongPHIElim)
243 AU.addRequiredID(StrongPHIEliminationID);
244 AU.addRequiredTransitive<RegisterCoalescer>();
245 AU.addRequired<CalculateSpillWeights>();
246 AU.addRequired<LiveStacks>();
247 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000248 AU.addRequired<MachineDominatorTree>();
249 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000250 AU.addRequired<MachineLoopInfo>();
251 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000252 AU.addRequired<MachineLoopRanges>();
253 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000254 AU.addRequired<VirtRegMap>();
255 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000256 AU.addRequired<EdgeBundles>();
257 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000258 MachineFunctionPass::getAnalysisUsage(AU);
259}
260
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000261
262//===----------------------------------------------------------------------===//
263// LiveRangeEdit delegate methods
264//===----------------------------------------------------------------------===//
265
266void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
267 // LRE itself will remove from SlotIndexes and parent basic block.
268 VRM->RemoveMachineInstrFromMaps(MI);
269}
270
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000271bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
272 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
273 unassign(LIS->getInterval(VirtReg), PhysReg);
274 return true;
275 }
276 // Unassigned virtreg is probably in the priority queue.
277 // RegAllocBase will erase it after dequeueing.
278 return false;
279}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000280
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000281void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
282 unsigned PhysReg = VRM->getPhys(VirtReg);
283 if (!PhysReg)
284 return;
285
286 // Register is assigned, put it back on the queue for reassignment.
287 LiveInterval &LI = LIS->getInterval(VirtReg);
288 unassign(LI, PhysReg);
289 enqueue(&LI);
290}
291
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000292void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
293 // LRE may clone a virtual register because dead code elimination causes it to
294 // be split into connected components. Ensure that the new register gets the
295 // same stage as the parent.
296 LRStage.grow(New);
297 LRStage[New] = LRStage[Old];
298}
299
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000300void RAGreedy::releaseMemory() {
301 SpillerInstance.reset(0);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000302 LRStage.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000303 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000304 RegAllocBase::releaseMemory();
305}
306
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000307void RAGreedy::enqueue(LiveInterval *LI) {
308 // Prioritize live ranges by size, assigning larger ranges first.
309 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000310 const unsigned Size = LI->getSize();
311 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000312 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
313 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000314 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000315
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000316 LRStage.grow(Reg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000317 if (LRStage[Reg] == RS_New)
318 LRStage[Reg] = RS_First;
319
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000320 if (LRStage[Reg] == RS_Second)
321 // Unsplit ranges that couldn't be allocated immediately are deferred until
322 // everything else has been allocated. Long ranges are allocated last so
323 // they are split against realistic interference.
324 Prio = (1u << 31) - Size;
325 else {
326 // Everything else is allocated in long->short order. Long ranges that don't
327 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000328 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000329
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000330 // Boost ranges that have a physical register hint.
331 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
332 Prio |= (1u << 30);
333 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000334
335 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000336}
337
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000338LiveInterval *RAGreedy::dequeue() {
339 if (Queue.empty())
340 return 0;
341 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
342 Queue.pop();
343 return LI;
344}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000345
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000346
347//===----------------------------------------------------------------------===//
348// Direct Assignment
349//===----------------------------------------------------------------------===//
350
351/// tryAssign - Try to assign VirtReg to an available register.
352unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
353 AllocationOrder &Order,
354 SmallVectorImpl<LiveInterval*> &NewVRegs) {
355 Order.rewind();
356 unsigned PhysReg;
357 while ((PhysReg = Order.next()))
358 if (!checkPhysRegInterference(VirtReg, PhysReg))
359 break;
360 if (!PhysReg || Order.isHint(PhysReg))
361 return PhysReg;
362
363 // PhysReg is available. Try to evict interference from a cheaper alternative.
364 unsigned Cost = TRI->getCostPerUse(PhysReg);
365
366 // Most registers have 0 additional cost.
367 if (!Cost)
368 return PhysReg;
369
370 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
371 << '\n');
372 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
373 return CheapReg ? CheapReg : PhysReg;
374}
375
376
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000377//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000378// Interference eviction
379//===----------------------------------------------------------------------===//
380
381/// canEvict - Return true if all interferences between VirtReg and PhysReg can
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000382/// be evicted.
383/// Return false if any interference is heavier than MaxWeight.
384/// On return, set MaxWeight to the maximal spill weight of an interference.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000385bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000386 float &MaxWeight) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000387 float Weight = 0;
388 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
389 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000390 // If there is 10 or more interferences, chances are one is heavier.
391 if (Q.collectInterferingVRegs(10, MaxWeight) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000392 return false;
393
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000394 // Check if any interfering live range is heavier than MaxWeight.
395 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
396 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000397 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
398 return false;
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000399 if (Intf->weight >= MaxWeight)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000400 return false;
401 Weight = std::max(Weight, Intf->weight);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000402 }
403 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000404 MaxWeight = Weight;
405 return true;
406}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000407
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000408/// tryEvict - Try to evict all interferences for a physreg.
409/// @param VirtReg Currently unassigned virtual register.
410/// @param Order Physregs to try.
411/// @return Physreg to assign VirtReg, or 0.
412unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
413 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000414 SmallVectorImpl<LiveInterval*> &NewVRegs,
415 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000416 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
417
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000418 // Keep track of the lightest single interference seen so far.
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000419 float BestWeight = VirtReg.weight;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000420 unsigned BestPhys = 0;
421
422 Order.rewind();
423 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000424 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
425 continue;
426 // The first use of a register in a function has cost 1.
427 if (CostPerUseLimit == 1 && !MRI->isPhysRegUsed(PhysReg))
428 continue;
429
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000430 float Weight = BestWeight;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000431 if (!canEvictInterference(VirtReg, PhysReg, Weight))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000432 continue;
433
434 // This is an eviction candidate.
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000435 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " interference = "
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000436 << Weight << '\n');
437 if (BestPhys && Weight >= BestWeight)
438 continue;
439
440 // Best so far.
441 BestPhys = PhysReg;
442 BestWeight = Weight;
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000443 // Stop if the hint can be used.
444 if (Order.isHint(PhysReg))
445 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000446 }
447
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000448 if (!BestPhys)
449 return 0;
450
451 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
452 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
453 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
454 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
455 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
456 LiveInterval *Intf = Q.interferingVRegs()[i];
457 unassign(*Intf, VRM->getPhys(Intf->reg));
458 ++NumEvicted;
459 NewVRegs.push_back(Intf);
460 }
461 }
462 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000463}
464
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000465
466//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000467// Region Splitting
468//===----------------------------------------------------------------------===//
469
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000470/// addSplitConstraints - Fill out the SplitConstraints vector based on the
471/// interference pattern in Physreg and its aliases. Add the constraints to
472/// SpillPlacement and return the static cost of this split in Cost, assuming
473/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000474/// Return false if there are no bundles with positive bias.
475bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
476 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000477 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000478
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000479 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000480 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000481 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000482 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
483 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000484 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000485
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000486 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000487 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000488 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
489 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000490
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000491 if (!Intf.hasInterference())
492 continue;
493
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000494 // Number of spill code instructions to insert.
495 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000496
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000497 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000498 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000499 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000500 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000501 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000502 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000503 else if (Intf.first() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000504 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000505 }
506
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000507 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000508 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000509 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000510 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000511 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000512 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000513 else if (Intf.last() > (BI.LiveThrough ? BI.FirstUse : BI.Def))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000514 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000515 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000516
517 // Accumulate the total frequency of inserted spill code.
518 if (Ins)
519 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000520 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000521 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000522
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000523 // Add constraints for use-blocks. Note that these are the only constraints
524 // that may add a positive bias, it is downhill from here.
525 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000526 return SpillPlacer->scanActiveBundles();
527}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000528
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000529
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000530/// addThroughConstraints - Add constraints and links to SpillPlacer from the
531/// live-through blocks in Blocks.
532void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
533 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000534 const unsigned GroupSize = 8;
535 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000536 unsigned TBS[GroupSize];
537 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000538
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000539 for (unsigned i = 0; i != Blocks.size(); ++i) {
540 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000541 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000542
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000543 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000544 assert(T < GroupSize && "Array overflow");
545 TBS[T] = Number;
546 if (++T == GroupSize) {
547 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
548 T = 0;
549 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000550 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000551 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000552
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000553 assert(B < GroupSize && "Array overflow");
554 BCS[B].Number = Number;
555
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000556 // Interference for the live-in value.
557 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
558 BCS[B].Entry = SpillPlacement::MustSpill;
559 else
560 BCS[B].Entry = SpillPlacement::PrefSpill;
561
562 // Interference for the live-out value.
563 if (Intf.last() >= SA->getLastSplitPoint(Number))
564 BCS[B].Exit = SpillPlacement::MustSpill;
565 else
566 BCS[B].Exit = SpillPlacement::PrefSpill;
567
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000568 if (++B == GroupSize) {
569 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
570 SpillPlacer->addConstraints(Array);
571 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000572 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000573 }
574
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000575 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
576 SpillPlacer->addConstraints(Array);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000577 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000578}
579
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000580void RAGreedy::growRegion(GlobalSplitCandidate &Cand,
581 InterferenceCache::Cursor Intf) {
582 // Keep track of through blocks that have not been added to SpillPlacer.
583 BitVector Todo = SA->getThroughBlocks();
584 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
585 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000586#ifndef NDEBUG
587 unsigned Visited = 0;
588#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000589
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000590 for (;;) {
591 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
592 if (NewBundles.empty())
593 break;
594 // Find new through blocks in the periphery of PrefRegBundles.
595 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
596 unsigned Bundle = NewBundles[i];
597 // Look at all blocks connected to Bundle in the full graph.
598 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
599 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
600 I != E; ++I) {
601 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000602 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000603 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000604 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000605 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000606 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000607#ifndef NDEBUG
608 ++Visited;
609#endif
610 }
611 }
612 // Any new blocks to add?
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000613 if (ActiveBlocks.size() > AddedTo) {
614 ArrayRef<unsigned> Add(&ActiveBlocks[AddedTo],
615 ActiveBlocks.size() - AddedTo);
616 addThroughConstraints(Intf, Add);
617 AddedTo = ActiveBlocks.size();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000618 }
619 // Perhaps iterating can enable more bundles?
620 SpillPlacer->iterate();
621 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000622 DEBUG(dbgs() << ", v=" << Visited);
623}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000624
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000625/// calcSpillCost - Compute how expensive it would be to split the live range in
626/// SA around all use blocks instead of forming bundle regions.
627float RAGreedy::calcSpillCost() {
628 float Cost = 0;
629 const LiveInterval &LI = SA->getParent();
630 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
631 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
632 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
633 unsigned Number = BI.MBB->getNumber();
634 // We normally only need one spill instruction - a load or a store.
635 Cost += SpillPlacer->getBlockFrequency(Number);
636
637 // Unless the value is redefined in the block.
638 if (BI.LiveIn && BI.LiveOut) {
639 SlotIndex Start, Stop;
640 tie(Start, Stop) = Indexes->getMBBRange(Number);
641 LiveInterval::const_iterator I = LI.find(Start);
642 assert(I != LI.end() && "Expected live-in value");
643 // Is there a different live-out value? If so, we need an extra spill
644 // instruction.
645 if (I->end < Stop)
646 Cost += SpillPlacer->getBlockFrequency(Number);
647 }
648 }
649 return Cost;
650}
651
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000652/// calcGlobalSplitCost - Return the global split cost of following the split
653/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000654/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000655///
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000656float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
657 InterferenceCache::Cursor Intf) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000658 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000659 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000660 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
661 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
662 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000663 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000664 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
665 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
666 unsigned Ins = 0;
667
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000668 if (BI.LiveIn)
669 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
670 if (BI.LiveOut)
671 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000672 if (Ins)
673 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000674 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000675
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000676 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
677 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000678 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
679 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000680 if (!RegIn && !RegOut)
681 continue;
682 if (RegIn && RegOut) {
683 // We need double spill code if this block has interference.
684 Intf.moveToBlock(Number);
685 if (Intf.hasInterference())
686 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
687 continue;
688 }
689 // live-in / stack-out or stack-in live-out.
690 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000691 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000692 return GlobalCost;
693}
694
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000695/// splitAroundRegion - Split VirtReg around the region determined by
696/// LiveBundles. Make an effort to avoid interference from PhysReg.
697///
698/// The 'register' interval is going to contain as many uses as possible while
699/// avoiding interference. The 'stack' interval is the complement constructed by
700/// SplitEditor. It will contain the rest.
701///
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000702void RAGreedy::splitAroundRegion(LiveInterval &VirtReg,
703 GlobalSplitCandidate &Cand,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000704 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000705 const BitVector &LiveBundles = Cand.LiveBundles;
706
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000707 DEBUG({
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000708 dbgs() << "Splitting around region for " << PrintReg(Cand.PhysReg, TRI)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000709 << " with bundles";
710 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
711 dbgs() << " EB#" << i;
712 dbgs() << ".\n";
713 });
714
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000715 InterferenceCache::Cursor Intf(IntfCache, Cand.PhysReg);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000716 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000717 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000718
719 // Create the main cross-block interval.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000720 const unsigned MainIntv = SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000721
722 // First add all defs that are live out of a block.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000723 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
724 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
725 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000726 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
727 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
728
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000729 // Create separate intervals for isolated blocks with multiple uses.
730 if (!RegIn && !RegOut && BI.FirstUse != BI.LastUse) {
731 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
732 SE->splitSingleBlock(BI);
733 SE->selectIntv(MainIntv);
734 continue;
735 }
736
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000737 // Should the register be live out?
738 if (!BI.LiveOut || !RegOut)
739 continue;
740
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000741 SlotIndex Start, Stop;
742 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000743 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000744 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000745 << Bundles->getBundle(BI.MBB->getNumber(), 1)
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000746 << " [" << Start << ';'
747 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
748 << ") intf [" << Intf.first() << ';' << Intf.last() << ')');
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000749
750 // The interference interval should either be invalid or overlap MBB.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000751 assert((!Intf.hasInterference() || Intf.first() < Stop)
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000752 && "Bad interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000753 assert((!Intf.hasInterference() || Intf.last() > Start)
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000754 && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000755
756 // Check interference leaving the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000757 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000758 // Block is interference-free.
759 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000760 if (!BI.LiveThrough) {
761 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000762 SE->useIntv(SE->enterIntvBefore(BI.Def), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000763 continue;
764 }
765 if (!RegIn) {
766 // Block is live-through, but entry bundle is on the stack.
767 // Reload just before the first use.
768 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000769 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000770 continue;
771 }
772 DEBUG(dbgs() << ", live-through.\n");
773 continue;
774 }
775
776 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000777 DEBUG(dbgs() << ", interference to " << Intf.last());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000778
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000779 if (!BI.LiveThrough && Intf.last() <= BI.Def) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000780 // The interference doesn't reach the outgoing segment.
781 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000782 SE->useIntv(BI.Def, Stop);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000783 continue;
784 }
785
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000786 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000787 if (Intf.last().getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000788 // There are interference-free uses at the end of the block.
789 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000790 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000791 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000792 Intf.last().getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000793 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
794 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000795 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000796 // Only attempt a split befroe the last split point.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000797 if (Use.getBaseIndex() <= LastSplitPoint) {
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000798 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000799 SlotIndex SegStart = SE->enterIntvBefore(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000800 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000801 assert(SegStart < LastSplitPoint && "Impossible split point");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000802 SE->useIntv(SegStart, Stop);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000803 continue;
804 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000805 }
806
807 // Interference is after the last use.
808 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000809 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000810 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000811 }
812
813 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000814 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
815 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000816 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
817 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
818
819 // Is the register live-in?
820 if (!BI.LiveIn || !RegIn)
821 continue;
822
823 // We have an incoming register. Check for interference.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000824 SlotIndex Start, Stop;
825 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000826 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000827 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000828 << " -> BB#" << BI.MBB->getNumber() << " [" << Start << ';'
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000829 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
830 << ')');
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000831
832 // Check interference entering the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000833 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000834 // Block is interference-free.
835 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000836 if (!BI.LiveThrough) {
837 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000838 SE->useIntv(Start, SE->leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000839 continue;
840 }
841 if (!RegOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000842 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000843 // Block is live-through, but exit bundle is on the stack.
844 // Spill immediately after the last use.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000845 if (BI.LastUse < LastSplitPoint) {
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000846 DEBUG(dbgs() << ", uses, stack-out.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000847 SE->useIntv(Start, SE->leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000848 continue;
849 }
850 // The last use is after the last split point, it is probably an
851 // indirect jump.
852 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000853 << LastSplitPoint << ", stack-out.\n");
854 SlotIndex SegEnd = SE->leaveIntvBefore(LastSplitPoint);
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000855 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000856 // Run a double interval from the split to the last use.
857 // This makes it possible to spill the complement without affecting the
858 // indirect branch.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000859 SE->overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000860 continue;
861 }
862 // Register is live-through.
863 DEBUG(dbgs() << ", uses, live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000864 SE->useIntv(Start, Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000865 continue;
866 }
867
868 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000869 DEBUG(dbgs() << ", interference from " << Intf.first());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000870
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000871 if (!BI.LiveThrough && Intf.first() >= BI.Kill) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000872 // The interference doesn't reach the outgoing segment.
873 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000874 SE->useIntv(Start, BI.Kill);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000875 continue;
876 }
877
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000878 if (Intf.first().getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000879 // There are interference-free uses at the beginning of the block.
880 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000881 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000882 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000883 Intf.first().getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000884 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
885 SlotIndex Use = (--UI)->getBoundaryIndex();
886 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000887 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000888 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000889 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000890 continue;
891 }
892
893 // Interference is before the first use.
894 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000895 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000896 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000897 }
898
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000899 // Handle live-through blocks.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000900 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
901 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000902 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
903 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
904 DEBUG(dbgs() << "Live through BB#" << Number << '\n');
905 if (RegIn && RegOut) {
906 Intf.moveToBlock(Number);
907 if (!Intf.hasInterference()) {
908 SE->useIntv(Indexes->getMBBStartIdx(Number),
909 Indexes->getMBBEndIdx(Number));
910 continue;
911 }
912 }
913 MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
914 if (RegIn)
915 SE->leaveIntvAtTop(*MBB);
916 if (RegOut)
917 SE->enterIntvAtEnd(*MBB);
918 }
919
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000920 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000921
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000922 SmallVector<unsigned, 8> IntvMap;
923 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000924 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
925
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000926 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000927 unsigned OrigBlocks = SA->getNumThroughBlocks() + SA->getUseBlocks().size();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000928
929 // Sort out the new intervals created by splitting. We get four kinds:
930 // - Remainder intervals should not be split again.
931 // - Candidate intervals can be assigned to Cand.PhysReg.
932 // - Block-local splits are candidates for local splitting.
933 // - DCE leftovers should go back on the queue.
934 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
935 unsigned Reg = LREdit.get(i)->reg;
936
937 // Ignore old intervals from DCE.
938 if (LRStage[Reg] != RS_New)
939 continue;
940
941 // Remainder interval. Don't try splitting again, spill if it doesn't
942 // allocate.
943 if (IntvMap[i] == 0) {
944 LRStage[Reg] = RS_Global;
945 continue;
946 }
947
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000948 // Main interval. Allow repeated splitting as long as the number of live
949 // blocks is strictly decreasing.
950 if (IntvMap[i] == MainIntv) {
951 if (SA->countLiveBlocks(LREdit.get(i)) >= OrigBlocks) {
952 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
953 << " blocks as original.\n");
954 // Don't allow repeated splitting as a safe guard against looping.
955 LRStage[Reg] = RS_Global;
956 }
957 continue;
958 }
959
960 // Other intervals are treated as new. This includes local intervals created
961 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000962 }
963
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000964 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000965 MF->verify(this, "After splitting live range around region");
966}
967
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000968unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
969 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000970 float BestCost = Hysteresis * calcSpillCost();
971 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000972 const unsigned NoCand = ~0u;
973 unsigned BestCand = NoCand;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000974
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000975 Order.rewind();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000976 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
977 if (GlobalCand.size() <= Cand)
978 GlobalCand.resize(Cand+1);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000979 GlobalCand[Cand].reset(PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000980
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000981 SpillPlacer->prepare(GlobalCand[Cand].LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000982 float Cost;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000983 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
984 if (!addSplitConstraints(Intf, Cost)) {
985 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000986 continue;
987 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000988 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000989 if (Cost >= BestCost) {
990 DEBUG({
991 if (BestCand == NoCand)
992 dbgs() << " worse than no bundles\n";
993 else
994 dbgs() << " worse than "
995 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
996 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000997 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000998 }
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000999 growRegion(GlobalCand[Cand], Intf);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001000
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001001 SpillPlacer->finish();
1002
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001003 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001004 if (!GlobalCand[Cand].LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001005 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001006 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001007 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001008
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001009 Cost += calcGlobalSplitCost(GlobalCand[Cand], Intf);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001010 DEBUG({
1011 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001012 for (int i = GlobalCand[Cand].LiveBundles.find_first(); i>=0;
1013 i = GlobalCand[Cand].LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001014 dbgs() << " EB#" << i;
1015 dbgs() << ".\n";
1016 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001017 if (Cost < BestCost) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001018 BestCand = Cand;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001019 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001020 }
1021 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001022
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001023 if (BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001024 return 0;
1025
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001026 splitAroundRegion(VirtReg, GlobalCand[BestCand], NewVRegs);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001027 return 0;
1028}
1029
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001030
1031//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001032// Local Splitting
1033//===----------------------------------------------------------------------===//
1034
1035
1036/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1037/// in order to use PhysReg between two entries in SA->UseSlots.
1038///
1039/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1040///
1041void RAGreedy::calcGapWeights(unsigned PhysReg,
1042 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001043 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1044 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001045 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1046 const unsigned NumGaps = Uses.size()-1;
1047
1048 // Start and end points for the interference check.
1049 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
1050 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
1051
1052 GapWeight.assign(NumGaps, 0.0f);
1053
1054 // Add interference from each overlapping register.
1055 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1056 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1057 .checkInterference())
1058 continue;
1059
1060 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
1061 // so we don't need InterferenceQuery.
1062 //
1063 // Interference that overlaps an instruction is counted in both gaps
1064 // surrounding the instruction. The exception is interference before
1065 // StartIdx and after StopIdx.
1066 //
1067 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1068 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1069 // Skip the gaps before IntI.
1070 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1071 if (++Gap == NumGaps)
1072 break;
1073 if (Gap == NumGaps)
1074 break;
1075
1076 // Update the gaps covered by IntI.
1077 const float weight = IntI.value()->weight;
1078 for (; Gap != NumGaps; ++Gap) {
1079 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1080 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1081 break;
1082 }
1083 if (Gap == NumGaps)
1084 break;
1085 }
1086 }
1087}
1088
1089/// getPrevMappedIndex - Return the slot index of the last non-copy instruction
1090/// before MI that has a slot index. If MI is the first mapped instruction in
1091/// its block, return the block start index instead.
1092///
1093SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
1094 assert(MI && "Missing MachineInstr");
1095 const MachineBasicBlock *MBB = MI->getParent();
1096 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
1097 while (I != B)
1098 if (!(--I)->isDebugValue() && !I->isCopy())
1099 return Indexes->getInstructionIndex(I);
1100 return Indexes->getMBBStartIdx(MBB);
1101}
1102
1103/// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
1104/// real non-copy instruction for each instruction in SA->UseSlots.
1105///
1106void RAGreedy::calcPrevSlots() {
1107 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1108 PrevSlot.clear();
1109 PrevSlot.reserve(Uses.size());
1110 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
1111 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
1112 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
1113 }
1114}
1115
1116/// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
1117/// be beneficial to split before UseSlots[i].
1118///
1119/// 0 is always a valid split point
1120unsigned RAGreedy::nextSplitPoint(unsigned i) {
1121 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1122 const unsigned Size = Uses.size();
1123 assert(i != Size && "No split points after the end");
1124 // Allow split before i when Uses[i] is not adjacent to the previous use.
1125 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
1126 ;
1127 return i;
1128}
1129
1130/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1131/// basic block.
1132///
1133unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1134 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001135 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1136 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001137
1138 // Note that it is possible to have an interval that is live-in or live-out
1139 // while only covering a single block - A phi-def can use undef values from
1140 // predecessors, and the block could be a single-block loop.
1141 // We don't bother doing anything clever about such a case, we simply assume
1142 // that the interval is continuous from FirstUse to LastUse. We should make
1143 // sure that we don't do anything illegal to such an interval, though.
1144
1145 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1146 if (Uses.size() <= 2)
1147 return 0;
1148 const unsigned NumGaps = Uses.size()-1;
1149
1150 DEBUG({
1151 dbgs() << "tryLocalSplit: ";
1152 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1153 dbgs() << ' ' << SA->UseSlots[i];
1154 dbgs() << '\n';
1155 });
1156
1157 // For every use, find the previous mapped non-copy instruction.
1158 // We use this to detect valid split points, and to estimate new interval
1159 // sizes.
1160 calcPrevSlots();
1161
1162 unsigned BestBefore = NumGaps;
1163 unsigned BestAfter = 0;
1164 float BestDiff = 0;
1165
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001166 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001167 SmallVector<float, 8> GapWeight;
1168
1169 Order.rewind();
1170 while (unsigned PhysReg = Order.next()) {
1171 // Keep track of the largest spill weight that would need to be evicted in
1172 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1173 calcGapWeights(PhysReg, GapWeight);
1174
1175 // Try to find the best sequence of gaps to close.
1176 // The new spill weight must be larger than any gap interference.
1177
1178 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1179 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
1180
1181 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1182 // It is the spill weight that needs to be evicted.
1183 float MaxGap = GapWeight[0];
1184 for (unsigned i = 1; i != SplitAfter; ++i)
1185 MaxGap = std::max(MaxGap, GapWeight[i]);
1186
1187 for (;;) {
1188 // Live before/after split?
1189 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1190 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1191
1192 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1193 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1194 << " i=" << MaxGap);
1195
1196 // Stop before the interval gets so big we wouldn't be making progress.
1197 if (!LiveBefore && !LiveAfter) {
1198 DEBUG(dbgs() << " all\n");
1199 break;
1200 }
1201 // Should the interval be extended or shrunk?
1202 bool Shrink = true;
1203 if (MaxGap < HUGE_VALF) {
1204 // Estimate the new spill weight.
1205 //
1206 // Each instruction reads and writes the register, except the first
1207 // instr doesn't read when !FirstLive, and the last instr doesn't write
1208 // when !LastLive.
1209 //
1210 // We will be inserting copies before and after, so the total number of
1211 // reads and writes is 2 * EstUses.
1212 //
1213 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1214 2*(LiveBefore + LiveAfter);
1215
1216 // Try to guess the size of the new interval. This should be trivial,
1217 // but the slot index of an inserted copy can be a lot smaller than the
1218 // instruction it is inserted before if there are many dead indexes
1219 // between them.
1220 //
1221 // We measure the distance from the instruction before SplitBefore to
1222 // get a conservative estimate.
1223 //
1224 // The final distance can still be different if inserting copies
1225 // triggers a slot index renumbering.
1226 //
1227 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1228 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1229 // Would this split be possible to allocate?
1230 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001231 DEBUG(dbgs() << " w=" << EstWeight);
1232 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001233 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001234 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001235 if (Diff > BestDiff) {
1236 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001237 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001238 BestBefore = SplitBefore;
1239 BestAfter = SplitAfter;
1240 }
1241 }
1242 }
1243
1244 // Try to shrink.
1245 if (Shrink) {
1246 SplitBefore = nextSplitPoint(SplitBefore);
1247 if (SplitBefore < SplitAfter) {
1248 DEBUG(dbgs() << " shrink\n");
1249 // Recompute the max when necessary.
1250 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1251 MaxGap = GapWeight[SplitBefore];
1252 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1253 MaxGap = std::max(MaxGap, GapWeight[i]);
1254 }
1255 continue;
1256 }
1257 MaxGap = 0;
1258 }
1259
1260 // Try to extend the interval.
1261 if (SplitAfter >= NumGaps) {
1262 DEBUG(dbgs() << " end\n");
1263 break;
1264 }
1265
1266 DEBUG(dbgs() << " extend\n");
1267 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1268 SplitAfter != e; ++SplitAfter)
1269 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1270 continue;
1271 }
1272 }
1273
1274 // Didn't find any candidates?
1275 if (BestBefore == NumGaps)
1276 return 0;
1277
1278 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1279 << '-' << Uses[BestAfter] << ", " << BestDiff
1280 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1281
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001282 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001283 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001284
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001285 SE->openIntv();
1286 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1287 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1288 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001289 SE->finish();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001290 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001291 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001292 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001293
1294 return 0;
1295}
1296
1297//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001298// Live Range Splitting
1299//===----------------------------------------------------------------------===//
1300
1301/// trySplit - Try to split VirtReg or one of its interferences, making it
1302/// assignable.
1303/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1304unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1305 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001306 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001307 if (LIS->intervalIsInOneMBB(VirtReg)) {
1308 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001309 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001310 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001311 }
1312
1313 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001314
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001315 // Don't iterate global splitting.
1316 // Move straight to spilling if this range was produced by a global split.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001317 if (getStage(VirtReg) >= RS_Global)
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001318 return 0;
1319
1320 SA->analyze(&VirtReg);
1321
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001322 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1323 // coalescer. That may cause the range to become allocatable which means that
1324 // tryRegionSplit won't be making progress. This check should be replaced with
1325 // an assertion when the coalescer is fixed.
1326 if (SA->didRepairRange()) {
1327 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001328 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001329 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1330 return PhysReg;
1331 }
1332
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001333 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001334 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1335 if (PhysReg || !NewVRegs.empty())
1336 return PhysReg;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001337
1338 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001339 SplitAnalysis::BlockPtrSet Blocks;
1340 if (SA->getMultiUseBlocks(Blocks)) {
1341 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1342 SE->reset(LREdit);
1343 SE->splitSingleBlocks(Blocks);
1344 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Global);
1345 if (VerifyEnabled)
1346 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001347 }
1348
1349 // Don't assign any physregs.
1350 return 0;
1351}
1352
1353
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001354//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001355// Main Entry Point
1356//===----------------------------------------------------------------------===//
1357
1358unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001359 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001360 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001361 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001362 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1363 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001364
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +00001365 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001366 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001367
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001368 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1369
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001370 // The first time we see a live range, don't try to split or spill.
1371 // Wait until the second time, when all smaller ranges have been allocated.
1372 // This gives a better picture of the interference to split around.
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001373 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +00001374 if (Stage == RS_First) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001375 LRStage[VirtReg.reg] = RS_Second;
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001376 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001377 NewVRegs.push_back(&VirtReg);
1378 return 0;
1379 }
1380
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001381 // If we couldn't allocate a register from spilling, there is probably some
1382 // invalid inline assembly. The base class wil report it.
1383 if (Stage >= RS_Spill)
1384 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001385
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001386 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001387 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1388 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001389 return PhysReg;
1390
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001391 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001392 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001393 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1394 spiller().spill(LRE);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001395 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001396
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001397 if (VerifyEnabled)
1398 MF->verify(this, "After spilling");
1399
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001400 // The live virtual register requesting allocation was spilled, so tell
1401 // the caller not to allocate anything during this round.
1402 return 0;
1403}
1404
1405bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1406 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1407 << "********** Function: "
1408 << ((Value*)mf.getFunction())->getName() << '\n');
1409
1410 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001411 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001412 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001413
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001414 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001415 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001416 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001417 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001418 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001419 Loops = &getAnalysis<MachineLoopInfo>();
1420 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001421 Bundles = &getAnalysis<EdgeBundles>();
1422 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001423 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001424
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001425 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001426 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001427 LRStage.clear();
1428 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001429 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001430
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001431 allocatePhysRegs();
1432 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001433 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001434
1435 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001436 {
1437 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001438 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001439 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001440
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001441 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001442 DebugVars->emitDebugValues(VRM);
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001443
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001444 // The pass output is in VirtRegMap. Release all the transient data.
1445 releaseMemory();
1446
1447 return true;
1448}