blob: 77a172870a3d12dc120b17ca7f213f93eb2eba00 [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 Olesencba2e062010-12-08 03:26:16 +000017#include "LiveIntervalUnion.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000018#include "LiveRangeEdit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000019#include "RegAllocBase.h"
20#include "Spiller.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000022#include "SplitKit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000023#include "VirtRegMap.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000025#include "llvm/Analysis/AliasAnalysis.h"
26#include "llvm/Function.h"
27#include "llvm/PassAnalysisSupport.h"
28#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000029#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000030#include "llvm/CodeGen/LiveIntervalAnalysis.h"
31#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000032#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000035#include "llvm/CodeGen/MachineLoopRanges.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/Passes.h"
38#include "llvm/CodeGen/RegAllocRegistry.h"
39#include "llvm/CodeGen/RegisterCoalescer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000040#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000044#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000045
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000046#include <queue>
47
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000048using namespace llvm;
49
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000050STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000052STATISTIC(NumEvicted, "Number of interferences evicted");
53
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000054static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
55 createGreedyRegisterAllocator);
56
57namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000058class RAGreedy : public MachineFunctionPass,
59 public RegAllocBase,
60 private LiveRangeEdit::Delegate {
61
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000062 // context
63 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000064 BitVector ReservedRegs;
65
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 Olesenf428eb62010-12-17 23:16:32 +000074
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000075 // state
76 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000077 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000078
79 // Live ranges pass through a number of stages as we try to allocate them.
80 // Some of the stages may also create new live ranges:
81 //
82 // - Region splitting.
83 // - Per-block splitting.
84 // - Local splitting.
85 // - Spilling.
86 //
87 // Ranges produced by one of the stages skip the previous stages when they are
88 // dequeued. This improves performance because we can skip interference checks
89 // that are unlikely to give any results. It also guarantees that the live
90 // range splitting algorithm terminates, something that is otherwise hard to
91 // ensure.
92 enum LiveRangeStage {
93 RS_Original, ///< Never seen before, never split.
94 RS_Second, ///< Second time in the queue.
95 RS_Region, ///< Produced by region splitting.
96 RS_Block, ///< Produced by per-block splitting.
97 RS_Local, ///< Produced by local splitting.
98 RS_Spill ///< Produced by spilling.
99 };
100
101 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
102
103 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
104 return LiveRangeStage(LRStage[VirtReg.reg]);
105 }
106
107 template<typename Iterator>
108 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
109 LRStage.resize(MRI->getNumVirtRegs());
110 for (;Begin != End; ++Begin)
111 LRStage[(*Begin)->reg] = NewStage;
112 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000113
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000114 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000115 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000116 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000117
118 /// All basic blocks where the current register is live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000119 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000120
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000121 typedef std::pair<SlotIndex, SlotIndex> IndexPair;
122
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000123 /// Global live range splitting candidate info.
124 struct GlobalSplitCandidate {
125 unsigned PhysReg;
126 SmallVector<IndexPair, 8> Interference;
127 BitVector LiveBundles;
128 };
129
130 /// Candidate info for for each PhysReg in AllocationOrder.
131 /// This vector never shrinks, but grows to the size of the largest register
132 /// class.
133 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
134
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000135 /// For every instruction in SA->UseSlots, store the previous non-copy
136 /// instruction.
137 SmallVector<SlotIndex, 8> PrevSlot;
138
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000139public:
140 RAGreedy();
141
142 /// Return the pass name.
143 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000144 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000145 }
146
147 /// RAGreedy analysis usage.
148 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000149 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000150 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000151 virtual void enqueue(LiveInterval *LI);
152 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000153 virtual unsigned selectOrSplit(LiveInterval&,
154 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000155
156 /// Perform register allocation.
157 virtual bool runOnMachineFunction(MachineFunction &mf);
158
159 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000160
161private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000162 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000163 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000164 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000165
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000166 void mapGlobalInterference(unsigned, SmallVectorImpl<IndexPair>&);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000167 float calcSplitConstraints(const SmallVectorImpl<IndexPair>&);
168
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000169 float calcGlobalSplitCost(const BitVector&);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000170 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
171 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000172 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
173 SlotIndex getPrevMappedIndex(const MachineInstr*);
174 void calcPrevSlots();
175 unsigned nextSplitPoint(unsigned);
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000176 bool canEvictInterference(LiveInterval&, unsigned, float&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000177
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000178 unsigned tryEvict(LiveInterval&, AllocationOrder&,
179 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000180 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
181 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000182 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
183 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000184 unsigned trySplit(LiveInterval&, AllocationOrder&,
185 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000186};
187} // end anonymous namespace
188
189char RAGreedy::ID = 0;
190
191FunctionPass* llvm::createGreedyRegisterAllocator() {
192 return new RAGreedy();
193}
194
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000195RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_Original) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000196 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000197 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
198 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
199 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
200 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
201 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
202 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
203 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
204 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000205 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000206 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000207 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
208 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000209}
210
211void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
212 AU.setPreservesCFG();
213 AU.addRequired<AliasAnalysis>();
214 AU.addPreserved<AliasAnalysis>();
215 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000216 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000217 AU.addPreserved<SlotIndexes>();
218 if (StrongPHIElim)
219 AU.addRequiredID(StrongPHIEliminationID);
220 AU.addRequiredTransitive<RegisterCoalescer>();
221 AU.addRequired<CalculateSpillWeights>();
222 AU.addRequired<LiveStacks>();
223 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000224 AU.addRequired<MachineDominatorTree>();
225 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000226 AU.addRequired<MachineLoopInfo>();
227 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000228 AU.addRequired<MachineLoopRanges>();
229 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000230 AU.addRequired<VirtRegMap>();
231 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000232 AU.addRequired<EdgeBundles>();
233 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000234 MachineFunctionPass::getAnalysisUsage(AU);
235}
236
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000237
238//===----------------------------------------------------------------------===//
239// LiveRangeEdit delegate methods
240//===----------------------------------------------------------------------===//
241
242void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
243 // LRE itself will remove from SlotIndexes and parent basic block.
244 VRM->RemoveMachineInstrFromMaps(MI);
245}
246
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000247bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
248 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
249 unassign(LIS->getInterval(VirtReg), PhysReg);
250 return true;
251 }
252 // Unassigned virtreg is probably in the priority queue.
253 // RegAllocBase will erase it after dequeueing.
254 return false;
255}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000256
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000257void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
258 unsigned PhysReg = VRM->getPhys(VirtReg);
259 if (!PhysReg)
260 return;
261
262 // Register is assigned, put it back on the queue for reassignment.
263 LiveInterval &LI = LIS->getInterval(VirtReg);
264 unassign(LI, PhysReg);
265 enqueue(&LI);
266}
267
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000268void RAGreedy::releaseMemory() {
269 SpillerInstance.reset(0);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000270 LRStage.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000271 RegAllocBase::releaseMemory();
272}
273
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000274void RAGreedy::enqueue(LiveInterval *LI) {
275 // Prioritize live ranges by size, assigning larger ranges first.
276 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000277 const unsigned Size = LI->getSize();
278 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000279 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
280 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000281 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000282
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000283 LRStage.grow(Reg);
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000284 if (LRStage[Reg] == RS_Second)
285 // Unsplit ranges that couldn't be allocated immediately are deferred until
286 // everything else has been allocated. Long ranges are allocated last so
287 // they are split against realistic interference.
288 Prio = (1u << 31) - Size;
289 else {
290 // Everything else is allocated in long->short order. Long ranges that don't
291 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000292 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000293
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000294 // Boost ranges that have a physical register hint.
295 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
296 Prio |= (1u << 30);
297 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000298
299 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000300}
301
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000302LiveInterval *RAGreedy::dequeue() {
303 if (Queue.empty())
304 return 0;
305 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
306 Queue.pop();
307 return LI;
308}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000309
310//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000311// Interference eviction
312//===----------------------------------------------------------------------===//
313
314/// canEvict - Return true if all interferences between VirtReg and PhysReg can
315/// be evicted. Set maxWeight to the maximal spill weight of an interference.
316bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000317 float &MaxWeight) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000318 float Weight = 0;
319 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
320 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
321 // If there is 10 or more interferences, chances are one is smaller.
322 if (Q.collectInterferingVRegs(10) >= 10)
323 return false;
324
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000325 // Check if any interfering live range is heavier than VirtReg.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000326 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
327 LiveInterval *Intf = Q.interferingVRegs()[i];
328 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
329 return false;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000330 if (Intf->weight >= VirtReg.weight)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000331 return false;
332 Weight = std::max(Weight, Intf->weight);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000333 }
334 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000335 MaxWeight = Weight;
336 return true;
337}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000338
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000339/// tryEvict - Try to evict all interferences for a physreg.
340/// @param VirtReg Currently unassigned virtual register.
341/// @param Order Physregs to try.
342/// @return Physreg to assign VirtReg, or 0.
343unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
344 AllocationOrder &Order,
345 SmallVectorImpl<LiveInterval*> &NewVRegs){
346 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
347
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000348 // Keep track of the lightest single interference seen so far.
349 float BestWeight = 0;
350 unsigned BestPhys = 0;
351
352 Order.rewind();
353 while (unsigned PhysReg = Order.next()) {
354 float Weight = 0;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000355 if (!canEvictInterference(VirtReg, PhysReg, Weight))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000356 continue;
357
358 // This is an eviction candidate.
359 DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
360 << Weight << '\n');
361 if (BestPhys && Weight >= BestWeight)
362 continue;
363
364 // Best so far.
365 BestPhys = PhysReg;
366 BestWeight = Weight;
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000367 // Stop if the hint can be used.
368 if (Order.isHint(PhysReg))
369 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000370 }
371
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000372 if (!BestPhys)
373 return 0;
374
375 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
376 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
377 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
378 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
379 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
380 LiveInterval *Intf = Q.interferingVRegs()[i];
381 unassign(*Intf, VRM->getPhys(Intf->reg));
382 ++NumEvicted;
383 NewVRegs.push_back(Intf);
384 }
385 }
386 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000387}
388
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000389
390//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000391// Region Splitting
392//===----------------------------------------------------------------------===//
393
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000394/// mapGlobalInterference - Compute a map of the interference from PhysReg and
395/// its aliases in each block in SA->LiveBlocks.
396/// If LiveBlocks[i] is live-in, Ranges[i].first is the first interference.
397/// If LiveBlocks[i] is live-out, Ranges[i].second is the last interference.
398void RAGreedy::mapGlobalInterference(unsigned PhysReg,
399 SmallVectorImpl<IndexPair> &Ranges) {
400 Ranges.assign(SA->LiveBlocks.size(), IndexPair());
401 LiveInterval &VirtReg = const_cast<LiveInterval&>(SA->getParent());
402 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
403 if (!query(VirtReg, *AI).checkInterference())
404 continue;
405 LiveIntervalUnion::SegmentIter IntI =
406 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
407 if (!IntI.valid())
408 continue;
409 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
410 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
411 IndexPair &IP = Ranges[i];
412
413 // Skip interference-free blocks.
414 if (IntI.start() >= BI.Stop)
415 continue;
416
417 // First interference in block.
418 if (BI.LiveIn) {
419 IntI.advanceTo(BI.Start);
420 if (!IntI.valid())
421 break;
422 if (IntI.start() >= BI.Stop)
423 continue;
424 if (!IP.first.isValid() || IntI.start() < IP.first)
425 IP.first = IntI.start();
426 }
427
428 // Last interference in block.
429 if (BI.LiveOut) {
430 IntI.advanceTo(BI.Stop);
431 if (!IntI.valid() || IntI.start() >= BI.Stop)
432 --IntI;
433 if (IntI.stop() <= BI.Start)
434 continue;
435 if (!IP.second.isValid() || IntI.stop() > IP.second)
436 IP.second = IntI.stop();
437 }
438 }
439 }
440}
441
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000442/// calcSplitConstraints - Fill out the SplitConstraints vector based on the
443/// interference pattern in Intf. Return the static cost of this split,
444/// assuming that all preferences in SplitConstraints are met.
445float RAGreedy::calcSplitConstraints(const SmallVectorImpl<IndexPair> &Intf) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000446 // Reset interference dependent info.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000447 SplitConstraints.resize(SA->LiveBlocks.size());
448 float StaticCost = 0;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000449 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
450 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000451 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
452 IndexPair IP = Intf[i];
453
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000454 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000455 BC.Entry = (BI.Uses && BI.LiveIn) ?
456 SpillPlacement::PrefReg : SpillPlacement::DontCare;
457 BC.Exit = (BI.Uses && BI.LiveOut) ?
458 SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000459
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000460 // Number of spill code instructions to insert.
461 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000462
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000463 // Interference for the live-in value.
464 if (IP.first.isValid()) {
465 if (IP.first <= BI.Start)
466 BC.Entry = SpillPlacement::MustSpill, Ins += BI.Uses;
467 else if (!BI.Uses)
468 BC.Entry = SpillPlacement::PrefSpill;
469 else if (IP.first < BI.FirstUse)
470 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
471 else if (IP.first < (BI.LiveThrough ? BI.LastUse : BI.Kill))
472 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000473 }
474
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000475 // Interference for the live-out value.
476 if (IP.second.isValid()) {
477 if (IP.second >= BI.LastSplitPoint)
478 BC.Exit = SpillPlacement::MustSpill, Ins += BI.Uses;
479 else if (!BI.Uses)
480 BC.Exit = SpillPlacement::PrefSpill;
481 else if (IP.second > BI.LastUse)
482 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
483 else if (IP.second > (BI.LiveThrough ? BI.FirstUse : BI.Def))
484 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000485 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000486
487 // Accumulate the total frequency of inserted spill code.
488 if (Ins)
489 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000490 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000491 return StaticCost;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000492}
493
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000494
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000495/// calcGlobalSplitCost - Return the global split cost of following the split
496/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000497/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000498///
499float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
500 float GlobalCost = 0;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000501 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
502 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000503 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000504 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
505 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
506 unsigned Ins = 0;
507
508 if (!BI.Uses)
509 Ins += RegIn != RegOut;
510 else {
511 if (BI.LiveIn)
512 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
513 if (BI.LiveOut)
514 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
515 }
516 if (Ins)
517 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000518 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000519 return GlobalCost;
520}
521
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000522/// splitAroundRegion - Split VirtReg around the region determined by
523/// LiveBundles. Make an effort to avoid interference from PhysReg.
524///
525/// The 'register' interval is going to contain as many uses as possible while
526/// avoiding interference. The 'stack' interval is the complement constructed by
527/// SplitEditor. It will contain the rest.
528///
529void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
530 const BitVector &LiveBundles,
531 SmallVectorImpl<LiveInterval*> &NewVRegs) {
532 DEBUG({
533 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
534 << " with bundles";
535 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
536 dbgs() << " EB#" << i;
537 dbgs() << ".\n";
538 });
539
540 // First compute interference ranges in the live blocks.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000541 SmallVector<IndexPair, 8> InterferenceRanges;
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000542 mapGlobalInterference(PhysReg, InterferenceRanges);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000543
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000544 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000545 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000546
547 // Create the main cross-block interval.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000548 SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000549
550 // First add all defs that are live out of a block.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000551 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
552 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000553 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
554 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
555
556 // Should the register be live out?
557 if (!BI.LiveOut || !RegOut)
558 continue;
559
560 IndexPair &IP = InterferenceRanges[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000561 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000562 << Bundles->getBundle(BI.MBB->getNumber(), 1)
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000563 << " [" << BI.Start << ';' << BI.LastSplitPoint << '-'
564 << BI.Stop << ") intf [" << IP.first << ';' << IP.second
565 << ')');
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000566
567 // The interference interval should either be invalid or overlap MBB.
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000568 assert((!IP.first.isValid() || IP.first < BI.Stop) && "Bad interference");
569 assert((!IP.second.isValid() || IP.second > BI.Start)
570 && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000571
572 // Check interference leaving the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000573 if (!IP.second.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000574 // Block is interference-free.
575 DEBUG(dbgs() << ", no interference");
576 if (!BI.Uses) {
577 assert(BI.LiveThrough && "No uses, but not live through block?");
578 // Block is live-through without interference.
579 DEBUG(dbgs() << ", no uses"
580 << (RegIn ? ", live-through.\n" : ", stack in.\n"));
581 if (!RegIn)
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000582 SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000583 continue;
584 }
585 if (!BI.LiveThrough) {
586 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000587 SE->useIntv(SE->enterIntvBefore(BI.Def), BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000588 continue;
589 }
590 if (!RegIn) {
591 // Block is live-through, but entry bundle is on the stack.
592 // Reload just before the first use.
593 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000594 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000595 continue;
596 }
597 DEBUG(dbgs() << ", live-through.\n");
598 continue;
599 }
600
601 // Block has interference.
602 DEBUG(dbgs() << ", interference to " << IP.second);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000603
604 if (!BI.LiveThrough && IP.second <= BI.Def) {
605 // The interference doesn't reach the outgoing segment.
606 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000607 SE->useIntv(BI.Def, BI.Stop);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000608 continue;
609 }
610
611
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000612 if (!BI.Uses) {
613 // No uses in block, avoid interference by reloading as late as possible.
614 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000615 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000616 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000617 continue;
618 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000619
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000620 if (IP.second.getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000621 // There are interference-free uses at the end of the block.
622 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000623 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000624 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
625 IP.second.getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000626 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
627 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000628 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000629 // Only attempt a split befroe the last split point.
630 if (Use.getBaseIndex() <= BI.LastSplitPoint) {
631 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000632 SlotIndex SegStart = SE->enterIntvBefore(Use);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000633 assert(SegStart >= IP.second && "Couldn't avoid interference");
634 assert(SegStart < BI.LastSplitPoint && "Impossible split point");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000635 SE->useIntv(SegStart, BI.Stop);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000636 continue;
637 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000638 }
639
640 // Interference is after the last use.
641 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000642 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000643 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000644 }
645
646 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000647 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
648 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000649 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
650 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
651
652 // Is the register live-in?
653 if (!BI.LiveIn || !RegIn)
654 continue;
655
656 // We have an incoming register. Check for interference.
657 IndexPair &IP = InterferenceRanges[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000658
659 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000660 << " -> BB#" << BI.MBB->getNumber() << " [" << BI.Start << ';'
661 << BI.LastSplitPoint << '-' << BI.Stop << ')');
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000662
663 // Check interference entering the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000664 if (!IP.first.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000665 // Block is interference-free.
666 DEBUG(dbgs() << ", no interference");
667 if (!BI.Uses) {
668 assert(BI.LiveThrough && "No uses, but not live through block?");
669 // Block is live-through without interference.
670 if (RegOut) {
671 DEBUG(dbgs() << ", no uses, live-through.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000672 SE->useIntv(BI.Start, BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000673 } else {
674 DEBUG(dbgs() << ", no uses, stack-out.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000675 SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000676 }
677 continue;
678 }
679 if (!BI.LiveThrough) {
680 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000681 SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000682 continue;
683 }
684 if (!RegOut) {
685 // Block is live-through, but exit bundle is on the stack.
686 // Spill immediately after the last use.
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000687 if (BI.LastUse < BI.LastSplitPoint) {
688 DEBUG(dbgs() << ", uses, stack-out.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000689 SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000690 continue;
691 }
692 // The last use is after the last split point, it is probably an
693 // indirect jump.
694 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
695 << BI.LastSplitPoint << ", stack-out.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000696 SlotIndex SegEnd = SE->leaveIntvBefore(BI.LastSplitPoint);
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000697 SE->useIntv(BI.Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000698 // Run a double interval from the split to the last use.
699 // This makes it possible to spill the complement without affecting the
700 // indirect branch.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000701 SE->overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000702 continue;
703 }
704 // Register is live-through.
705 DEBUG(dbgs() << ", uses, live-through.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000706 SE->useIntv(BI.Start, BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000707 continue;
708 }
709
710 // Block has interference.
711 DEBUG(dbgs() << ", interference from " << IP.first);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000712
713 if (!BI.LiveThrough && IP.first >= BI.Kill) {
714 // The interference doesn't reach the outgoing segment.
715 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000716 SE->useIntv(BI.Start, BI.Kill);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000717 continue;
718 }
719
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000720 if (!BI.Uses) {
721 // No uses in block, avoid interference by spilling as soon as possible.
722 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000723 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000724 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000725 continue;
726 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000727 if (IP.first.getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000728 // There are interference-free uses at the beginning of the block.
729 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000730 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000731 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
732 IP.first.getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000733 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
734 SlotIndex Use = (--UI)->getBoundaryIndex();
735 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000736 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000737 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000738 SE->useIntv(BI.Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000739 continue;
740 }
741
742 // Interference is before the first use.
743 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000744 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000745 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000746 }
747
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000748 SE->closeIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000749
750 // FIXME: Should we be more aggressive about splitting the stack region into
751 // per-block segments? The current approach allows the stack region to
752 // separate into connected components. Some components may be allocatable.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000753 SE->finish();
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000754 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000755
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000756 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000757 MF->verify(this, "After splitting live range around region");
758}
759
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000760unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
761 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000762 BitVector LiveBundles, BestBundles;
763 float BestCost = 0;
764 unsigned BestReg = 0;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000765
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000766 Order.rewind();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000767 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
768 if (GlobalCand.size() <= Cand)
769 GlobalCand.resize(Cand+1);
770 GlobalCand[Cand].PhysReg = PhysReg;
771
772 mapGlobalInterference(PhysReg, GlobalCand[Cand].Interference);
773 float Cost = calcSplitConstraints(GlobalCand[Cand].Interference);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000774 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
775 if (BestReg && Cost >= BestCost) {
776 DEBUG(dbgs() << " higher.\n");
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000777 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000778 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000779
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000780 SpillPlacer->placeSpills(SplitConstraints, LiveBundles);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000781 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000782 if (!LiveBundles.any()) {
783 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000784 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000785 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000786
787 Cost += calcGlobalSplitCost(LiveBundles);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000788 DEBUG({
789 dbgs() << ", total = " << Cost << " with bundles";
790 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
791 dbgs() << " EB#" << i;
792 dbgs() << ".\n";
793 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000794 if (!BestReg || Cost < BestCost) {
795 BestReg = PhysReg;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000796 BestCost = 0.98f * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000797 BestBundles.swap(LiveBundles);
798 }
799 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000800
801 if (!BestReg)
802 return 0;
803
804 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000805 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000806 return 0;
807}
808
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000809
810//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000811// Local Splitting
812//===----------------------------------------------------------------------===//
813
814
815/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
816/// in order to use PhysReg between two entries in SA->UseSlots.
817///
818/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
819///
820void RAGreedy::calcGapWeights(unsigned PhysReg,
821 SmallVectorImpl<float> &GapWeight) {
822 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
823 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
824 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
825 const unsigned NumGaps = Uses.size()-1;
826
827 // Start and end points for the interference check.
828 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
829 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
830
831 GapWeight.assign(NumGaps, 0.0f);
832
833 // Add interference from each overlapping register.
834 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
835 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
836 .checkInterference())
837 continue;
838
839 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
840 // so we don't need InterferenceQuery.
841 //
842 // Interference that overlaps an instruction is counted in both gaps
843 // surrounding the instruction. The exception is interference before
844 // StartIdx and after StopIdx.
845 //
846 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
847 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
848 // Skip the gaps before IntI.
849 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
850 if (++Gap == NumGaps)
851 break;
852 if (Gap == NumGaps)
853 break;
854
855 // Update the gaps covered by IntI.
856 const float weight = IntI.value()->weight;
857 for (; Gap != NumGaps; ++Gap) {
858 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
859 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
860 break;
861 }
862 if (Gap == NumGaps)
863 break;
864 }
865 }
866}
867
868/// getPrevMappedIndex - Return the slot index of the last non-copy instruction
869/// before MI that has a slot index. If MI is the first mapped instruction in
870/// its block, return the block start index instead.
871///
872SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
873 assert(MI && "Missing MachineInstr");
874 const MachineBasicBlock *MBB = MI->getParent();
875 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
876 while (I != B)
877 if (!(--I)->isDebugValue() && !I->isCopy())
878 return Indexes->getInstructionIndex(I);
879 return Indexes->getMBBStartIdx(MBB);
880}
881
882/// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
883/// real non-copy instruction for each instruction in SA->UseSlots.
884///
885void RAGreedy::calcPrevSlots() {
886 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
887 PrevSlot.clear();
888 PrevSlot.reserve(Uses.size());
889 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
890 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
891 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
892 }
893}
894
895/// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
896/// be beneficial to split before UseSlots[i].
897///
898/// 0 is always a valid split point
899unsigned RAGreedy::nextSplitPoint(unsigned i) {
900 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
901 const unsigned Size = Uses.size();
902 assert(i != Size && "No split points after the end");
903 // Allow split before i when Uses[i] is not adjacent to the previous use.
904 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
905 ;
906 return i;
907}
908
909/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
910/// basic block.
911///
912unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
913 SmallVectorImpl<LiveInterval*> &NewVRegs) {
914 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
915 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
916
917 // Note that it is possible to have an interval that is live-in or live-out
918 // while only covering a single block - A phi-def can use undef values from
919 // predecessors, and the block could be a single-block loop.
920 // We don't bother doing anything clever about such a case, we simply assume
921 // that the interval is continuous from FirstUse to LastUse. We should make
922 // sure that we don't do anything illegal to such an interval, though.
923
924 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
925 if (Uses.size() <= 2)
926 return 0;
927 const unsigned NumGaps = Uses.size()-1;
928
929 DEBUG({
930 dbgs() << "tryLocalSplit: ";
931 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
932 dbgs() << ' ' << SA->UseSlots[i];
933 dbgs() << '\n';
934 });
935
936 // For every use, find the previous mapped non-copy instruction.
937 // We use this to detect valid split points, and to estimate new interval
938 // sizes.
939 calcPrevSlots();
940
941 unsigned BestBefore = NumGaps;
942 unsigned BestAfter = 0;
943 float BestDiff = 0;
944
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +0000945 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000946 SmallVector<float, 8> GapWeight;
947
948 Order.rewind();
949 while (unsigned PhysReg = Order.next()) {
950 // Keep track of the largest spill weight that would need to be evicted in
951 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
952 calcGapWeights(PhysReg, GapWeight);
953
954 // Try to find the best sequence of gaps to close.
955 // The new spill weight must be larger than any gap interference.
956
957 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
958 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
959
960 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
961 // It is the spill weight that needs to be evicted.
962 float MaxGap = GapWeight[0];
963 for (unsigned i = 1; i != SplitAfter; ++i)
964 MaxGap = std::max(MaxGap, GapWeight[i]);
965
966 for (;;) {
967 // Live before/after split?
968 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
969 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
970
971 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
972 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
973 << " i=" << MaxGap);
974
975 // Stop before the interval gets so big we wouldn't be making progress.
976 if (!LiveBefore && !LiveAfter) {
977 DEBUG(dbgs() << " all\n");
978 break;
979 }
980 // Should the interval be extended or shrunk?
981 bool Shrink = true;
982 if (MaxGap < HUGE_VALF) {
983 // Estimate the new spill weight.
984 //
985 // Each instruction reads and writes the register, except the first
986 // instr doesn't read when !FirstLive, and the last instr doesn't write
987 // when !LastLive.
988 //
989 // We will be inserting copies before and after, so the total number of
990 // reads and writes is 2 * EstUses.
991 //
992 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
993 2*(LiveBefore + LiveAfter);
994
995 // Try to guess the size of the new interval. This should be trivial,
996 // but the slot index of an inserted copy can be a lot smaller than the
997 // instruction it is inserted before if there are many dead indexes
998 // between them.
999 //
1000 // We measure the distance from the instruction before SplitBefore to
1001 // get a conservative estimate.
1002 //
1003 // The final distance can still be different if inserting copies
1004 // triggers a slot index renumbering.
1005 //
1006 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1007 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1008 // Would this split be possible to allocate?
1009 // Never allocate all gaps, we wouldn't be making progress.
1010 float Diff = EstWeight - MaxGap;
1011 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1012 if (Diff > 0) {
1013 Shrink = false;
1014 if (Diff > BestDiff) {
1015 DEBUG(dbgs() << " (best)");
1016 BestDiff = Diff;
1017 BestBefore = SplitBefore;
1018 BestAfter = SplitAfter;
1019 }
1020 }
1021 }
1022
1023 // Try to shrink.
1024 if (Shrink) {
1025 SplitBefore = nextSplitPoint(SplitBefore);
1026 if (SplitBefore < SplitAfter) {
1027 DEBUG(dbgs() << " shrink\n");
1028 // Recompute the max when necessary.
1029 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1030 MaxGap = GapWeight[SplitBefore];
1031 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1032 MaxGap = std::max(MaxGap, GapWeight[i]);
1033 }
1034 continue;
1035 }
1036 MaxGap = 0;
1037 }
1038
1039 // Try to extend the interval.
1040 if (SplitAfter >= NumGaps) {
1041 DEBUG(dbgs() << " end\n");
1042 break;
1043 }
1044
1045 DEBUG(dbgs() << " extend\n");
1046 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1047 SplitAfter != e; ++SplitAfter)
1048 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1049 continue;
1050 }
1051 }
1052
1053 // Didn't find any candidates?
1054 if (BestBefore == NumGaps)
1055 return 0;
1056
1057 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1058 << '-' << Uses[BestAfter] << ", " << BestDiff
1059 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1060
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001061 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001062 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001063
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001064 SE->openIntv();
1065 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1066 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1067 SE->useIntv(SegStart, SegStop);
1068 SE->closeIntv();
1069 SE->finish();
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001070 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001071 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001072
1073 return 0;
1074}
1075
1076//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001077// Live Range Splitting
1078//===----------------------------------------------------------------------===//
1079
1080/// trySplit - Try to split VirtReg or one of its interferences, making it
1081/// assignable.
1082/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1083unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1084 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001085 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001086 if (LIS->intervalIsInOneMBB(VirtReg)) {
1087 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001088 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001089 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001090 }
1091
1092 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001093
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001094 // Don't iterate global splitting.
1095 // Move straight to spilling if this range was produced by a global split.
1096 LiveRangeStage Stage = getStage(VirtReg);
1097 if (Stage >= RS_Block)
1098 return 0;
1099
1100 SA->analyze(&VirtReg);
1101
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001102 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001103 if (Stage < RS_Region) {
1104 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1105 if (PhysReg || !NewVRegs.empty())
1106 return PhysReg;
1107 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001108
1109 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001110 if (Stage < RS_Block) {
1111 SplitAnalysis::BlockPtrSet Blocks;
1112 if (SA->getMultiUseBlocks(Blocks)) {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001113 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001114 SE->reset(LREdit);
1115 SE->splitSingleBlocks(Blocks);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001116 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1117 if (VerifyEnabled)
1118 MF->verify(this, "After splitting live range around basic blocks");
1119 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001120 }
1121
1122 // Don't assign any physregs.
1123 return 0;
1124}
1125
1126
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001127//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001128// Main Entry Point
1129//===----------------------------------------------------------------------===//
1130
1131unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001132 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001133 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001134 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1135 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001136 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001137 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001138 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00001139
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +00001140 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001141 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001142
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001143 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1144
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001145 // The first time we see a live range, don't try to split or spill.
1146 // Wait until the second time, when all smaller ranges have been allocated.
1147 // This gives a better picture of the interference to split around.
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001148 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001149 if (Stage == RS_Original) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001150 LRStage[VirtReg.reg] = RS_Second;
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001151 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001152 NewVRegs.push_back(&VirtReg);
1153 return 0;
1154 }
1155
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001156 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1157
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001158 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001159 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1160 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001161 return PhysReg;
1162
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001163 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001164 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001165 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1166 spiller().spill(LRE);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001167
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001168 if (VerifyEnabled)
1169 MF->verify(this, "After spilling");
1170
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001171 // The live virtual register requesting allocation was spilled, so tell
1172 // the caller not to allocate anything during this round.
1173 return 0;
1174}
1175
1176bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1177 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1178 << "********** Function: "
1179 << ((Value*)mf.getFunction())->getName() << '\n');
1180
1181 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001182 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001183 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001184
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001185 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001186 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001187 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001188 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001189 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001190 Loops = &getAnalysis<MachineLoopInfo>();
1191 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001192 Bundles = &getAnalysis<EdgeBundles>();
1193 SpillPlacer = &getAnalysis<SpillPlacement>();
1194
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001195 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001196 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001197 LRStage.clear();
1198 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001199
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001200 allocatePhysRegs();
1201 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001202 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001203
1204 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001205 {
1206 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001207 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001208 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001209
1210 // The pass output is in VirtRegMap. Release all the transient data.
1211 releaseMemory();
1212
1213 return true;
1214}