blob: 563c9bb0960c13a34f44f7f31c4694dc0a4e78a2 [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 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 {
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +000093 RS_New, ///< Never seen before.
94 RS_First, ///< First time in the queue.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000095 RS_Second, ///< Second time in the queue.
96 RS_Region, ///< Produced by region splitting.
97 RS_Block, ///< Produced by per-block splitting.
98 RS_Local, ///< Produced by local splitting.
99 RS_Spill ///< Produced by spilling.
100 };
101
102 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
103
104 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
105 return LiveRangeStage(LRStage[VirtReg.reg]);
106 }
107
108 template<typename Iterator>
109 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
110 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000111 for (;Begin != End; ++Begin) {
112 unsigned Reg = (*Begin)->reg;
113 if (LRStage[Reg] == RS_New)
114 LRStage[Reg] = NewStage;
115 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000116 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000117
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000118 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000119 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000120 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000121
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000122 /// Cached per-block interference maps
123 InterferenceCache IntfCache;
124
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000125 /// All basic blocks where the current register is live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000126 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000127
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000128 /// Global live range splitting candidate info.
129 struct GlobalSplitCandidate {
130 unsigned PhysReg;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000131 BitVector LiveBundles;
132 };
133
134 /// Candidate info for for each PhysReg in AllocationOrder.
135 /// This vector never shrinks, but grows to the size of the largest register
136 /// class.
137 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
138
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000139 /// For every instruction in SA->UseSlots, store the previous non-copy
140 /// instruction.
141 SmallVector<SlotIndex, 8> PrevSlot;
142
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000143public:
144 RAGreedy();
145
146 /// Return the pass name.
147 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000148 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000149 }
150
151 /// RAGreedy analysis usage.
152 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000153 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000154 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000155 virtual void enqueue(LiveInterval *LI);
156 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000157 virtual unsigned selectOrSplit(LiveInterval&,
158 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000159
160 /// Perform register allocation.
161 virtual bool runOnMachineFunction(MachineFunction &mf);
162
163 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000164
165private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000166 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000167 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000168 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000169 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000170
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000171 float calcSplitConstraints(unsigned);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000172 float calcGlobalSplitCost(const BitVector&);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000173 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
174 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000175 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
176 SlotIndex getPrevMappedIndex(const MachineInstr*);
177 void calcPrevSlots();
178 unsigned nextSplitPoint(unsigned);
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000179 bool canEvictInterference(LiveInterval&, unsigned, float&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000180
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000181 unsigned tryEvict(LiveInterval&, AllocationOrder&,
182 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000183 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
184 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000185 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
186 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000187 unsigned trySplit(LiveInterval&, AllocationOrder&,
188 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000189};
190} // end anonymous namespace
191
192char RAGreedy::ID = 0;
193
194FunctionPass* llvm::createGreedyRegisterAllocator() {
195 return new RAGreedy();
196}
197
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000198RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_New) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000199 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000200 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
201 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
202 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
203 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
204 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
205 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
206 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
207 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000208 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000209 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000210 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
211 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000212}
213
214void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
215 AU.setPreservesCFG();
216 AU.addRequired<AliasAnalysis>();
217 AU.addPreserved<AliasAnalysis>();
218 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000219 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000220 AU.addPreserved<SlotIndexes>();
221 if (StrongPHIElim)
222 AU.addRequiredID(StrongPHIEliminationID);
223 AU.addRequiredTransitive<RegisterCoalescer>();
224 AU.addRequired<CalculateSpillWeights>();
225 AU.addRequired<LiveStacks>();
226 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000227 AU.addRequired<MachineDominatorTree>();
228 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000229 AU.addRequired<MachineLoopInfo>();
230 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000231 AU.addRequired<MachineLoopRanges>();
232 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000233 AU.addRequired<VirtRegMap>();
234 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000235 AU.addRequired<EdgeBundles>();
236 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000237 MachineFunctionPass::getAnalysisUsage(AU);
238}
239
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000240
241//===----------------------------------------------------------------------===//
242// LiveRangeEdit delegate methods
243//===----------------------------------------------------------------------===//
244
245void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
246 // LRE itself will remove from SlotIndexes and parent basic block.
247 VRM->RemoveMachineInstrFromMaps(MI);
248}
249
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000250bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
251 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
252 unassign(LIS->getInterval(VirtReg), PhysReg);
253 return true;
254 }
255 // Unassigned virtreg is probably in the priority queue.
256 // RegAllocBase will erase it after dequeueing.
257 return false;
258}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000259
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000260void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
261 unsigned PhysReg = VRM->getPhys(VirtReg);
262 if (!PhysReg)
263 return;
264
265 // Register is assigned, put it back on the queue for reassignment.
266 LiveInterval &LI = LIS->getInterval(VirtReg);
267 unassign(LI, PhysReg);
268 enqueue(&LI);
269}
270
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000271void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
272 // LRE may clone a virtual register because dead code elimination causes it to
273 // be split into connected components. Ensure that the new register gets the
274 // same stage as the parent.
275 LRStage.grow(New);
276 LRStage[New] = LRStage[Old];
277}
278
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000279void RAGreedy::releaseMemory() {
280 SpillerInstance.reset(0);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000281 LRStage.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000282 RegAllocBase::releaseMemory();
283}
284
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000285void RAGreedy::enqueue(LiveInterval *LI) {
286 // Prioritize live ranges by size, assigning larger ranges first.
287 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000288 const unsigned Size = LI->getSize();
289 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000290 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
291 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000292 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000293
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000294 LRStage.grow(Reg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000295 if (LRStage[Reg] == RS_New)
296 LRStage[Reg] = RS_First;
297
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000298 if (LRStage[Reg] == RS_Second)
299 // Unsplit ranges that couldn't be allocated immediately are deferred until
300 // everything else has been allocated. Long ranges are allocated last so
301 // they are split against realistic interference.
302 Prio = (1u << 31) - Size;
303 else {
304 // Everything else is allocated in long->short order. Long ranges that don't
305 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000306 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000307
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000308 // Boost ranges that have a physical register hint.
309 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
310 Prio |= (1u << 30);
311 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000312
313 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000314}
315
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000316LiveInterval *RAGreedy::dequeue() {
317 if (Queue.empty())
318 return 0;
319 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
320 Queue.pop();
321 return LI;
322}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000323
324//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000325// Interference eviction
326//===----------------------------------------------------------------------===//
327
328/// canEvict - Return true if all interferences between VirtReg and PhysReg can
329/// be evicted. Set maxWeight to the maximal spill weight of an interference.
330bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000331 float &MaxWeight) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000332 float Weight = 0;
333 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
334 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
335 // If there is 10 or more interferences, chances are one is smaller.
336 if (Q.collectInterferingVRegs(10) >= 10)
337 return false;
338
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000339 // Check if any interfering live range is heavier than VirtReg.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000340 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
341 LiveInterval *Intf = Q.interferingVRegs()[i];
342 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
343 return false;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000344 if (Intf->weight >= VirtReg.weight)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000345 return false;
346 Weight = std::max(Weight, Intf->weight);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000347 }
348 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000349 MaxWeight = Weight;
350 return true;
351}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000352
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000353/// tryEvict - Try to evict all interferences for a physreg.
354/// @param VirtReg Currently unassigned virtual register.
355/// @param Order Physregs to try.
356/// @return Physreg to assign VirtReg, or 0.
357unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
358 AllocationOrder &Order,
359 SmallVectorImpl<LiveInterval*> &NewVRegs){
360 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
361
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000362 // Keep track of the lightest single interference seen so far.
363 float BestWeight = 0;
364 unsigned BestPhys = 0;
365
366 Order.rewind();
367 while (unsigned PhysReg = Order.next()) {
368 float Weight = 0;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000369 if (!canEvictInterference(VirtReg, PhysReg, Weight))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000370 continue;
371
372 // This is an eviction candidate.
373 DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
374 << Weight << '\n');
375 if (BestPhys && Weight >= BestWeight)
376 continue;
377
378 // Best so far.
379 BestPhys = PhysReg;
380 BestWeight = Weight;
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000381 // Stop if the hint can be used.
382 if (Order.isHint(PhysReg))
383 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000384 }
385
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000386 if (!BestPhys)
387 return 0;
388
389 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
390 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
391 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
392 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
393 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
394 LiveInterval *Intf = Q.interferingVRegs()[i];
395 unassign(*Intf, VRM->getPhys(Intf->reg));
396 ++NumEvicted;
397 NewVRegs.push_back(Intf);
398 }
399 }
400 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000401}
402
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000403
404//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000405// Region Splitting
406//===----------------------------------------------------------------------===//
407
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000408/// calcSplitConstraints - Fill out the SplitConstraints vector based on the
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000409/// interference pattern in Physreg and its aliases. Return the static cost of
410/// this split, assuming that all preferences in SplitConstraints are met.
411float RAGreedy::calcSplitConstraints(unsigned PhysReg) {
412 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
413
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000414 // Reset interference dependent info.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000415 SplitConstraints.resize(SA->LiveBlocks.size());
416 float StaticCost = 0;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000417 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
418 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000419 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000420
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000421 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000422 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000423 BC.Entry = (BI.Uses && BI.LiveIn) ?
424 SpillPlacement::PrefReg : SpillPlacement::DontCare;
425 BC.Exit = (BI.Uses && BI.LiveOut) ?
426 SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000427
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000428 if (!Intf.hasInterference())
429 continue;
430
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000431 // Number of spill code instructions to insert.
432 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000433
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000434 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000435 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000436 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000437 BC.Entry = SpillPlacement::MustSpill, Ins += BI.Uses;
438 else if (!BI.Uses)
439 BC.Entry = SpillPlacement::PrefSpill;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000440 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000441 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000442 else if (Intf.first() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000443 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000444 }
445
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000446 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000447 if (BI.LiveOut) {
448 if (Intf.last() >= BI.LastSplitPoint)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000449 BC.Exit = SpillPlacement::MustSpill, Ins += BI.Uses;
450 else if (!BI.Uses)
451 BC.Exit = SpillPlacement::PrefSpill;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000452 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000453 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000454 else if (Intf.last() > (BI.LiveThrough ? BI.FirstUse : BI.Def))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000455 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000456 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000457
458 // Accumulate the total frequency of inserted spill code.
459 if (Ins)
460 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000461 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000462 return StaticCost;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000463}
464
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000465
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000466/// calcGlobalSplitCost - Return the global split cost of following the split
467/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000468/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000469///
470float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
471 float GlobalCost = 0;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000472 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
473 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000474 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000475 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
476 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
477 unsigned Ins = 0;
478
479 if (!BI.Uses)
480 Ins += RegIn != RegOut;
481 else {
482 if (BI.LiveIn)
483 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
484 if (BI.LiveOut)
485 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
486 }
487 if (Ins)
488 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000489 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000490 return GlobalCost;
491}
492
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000493/// splitAroundRegion - Split VirtReg around the region determined by
494/// LiveBundles. Make an effort to avoid interference from PhysReg.
495///
496/// The 'register' interval is going to contain as many uses as possible while
497/// avoiding interference. The 'stack' interval is the complement constructed by
498/// SplitEditor. It will contain the rest.
499///
500void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
501 const BitVector &LiveBundles,
502 SmallVectorImpl<LiveInterval*> &NewVRegs) {
503 DEBUG({
504 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
505 << " with bundles";
506 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
507 dbgs() << " EB#" << i;
508 dbgs() << ".\n";
509 });
510
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000511 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000512 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000513 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000514
515 // Create the main cross-block interval.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000516 SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000517
518 // First add all defs that are live out of a block.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000519 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
520 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000521 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
522 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
523
524 // Should the register be live out?
525 if (!BI.LiveOut || !RegOut)
526 continue;
527
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000528 SlotIndex Start, Stop;
529 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000530 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000531 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000532 << Bundles->getBundle(BI.MBB->getNumber(), 1)
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000533 << " [" << Start << ';' << BI.LastSplitPoint << '-'
534 << Stop << ") intf [" << Intf.first() << ';' << Intf.last()
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000535 << ')');
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000536
537 // The interference interval should either be invalid or overlap MBB.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000538 assert((!Intf.hasInterference() || Intf.first() < Stop)
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000539 && "Bad interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000540 assert((!Intf.hasInterference() || Intf.last() > Start)
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000541 && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000542
543 // Check interference leaving the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000544 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000545 // Block is interference-free.
546 DEBUG(dbgs() << ", no interference");
547 if (!BI.Uses) {
548 assert(BI.LiveThrough && "No uses, but not live through block?");
549 // Block is live-through without interference.
550 DEBUG(dbgs() << ", no uses"
551 << (RegIn ? ", live-through.\n" : ", stack in.\n"));
552 if (!RegIn)
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000553 SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000554 continue;
555 }
556 if (!BI.LiveThrough) {
557 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000558 SE->useIntv(SE->enterIntvBefore(BI.Def), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000559 continue;
560 }
561 if (!RegIn) {
562 // Block is live-through, but entry bundle is on the stack.
563 // Reload just before the first use.
564 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000565 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000566 continue;
567 }
568 DEBUG(dbgs() << ", live-through.\n");
569 continue;
570 }
571
572 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000573 DEBUG(dbgs() << ", interference to " << Intf.last());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000574
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000575 if (!BI.LiveThrough && Intf.last() <= BI.Def) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000576 // The interference doesn't reach the outgoing segment.
577 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000578 SE->useIntv(BI.Def, Stop);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000579 continue;
580 }
581
582
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000583 if (!BI.Uses) {
584 // No uses in block, avoid interference by reloading as late as possible.
585 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000586 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000587 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000588 continue;
589 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000590
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000591 if (Intf.last().getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000592 // There are interference-free uses at the end of the block.
593 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000594 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000595 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000596 Intf.last().getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000597 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
598 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000599 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000600 // Only attempt a split befroe the last split point.
601 if (Use.getBaseIndex() <= BI.LastSplitPoint) {
602 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000603 SlotIndex SegStart = SE->enterIntvBefore(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000604 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000605 assert(SegStart < BI.LastSplitPoint && "Impossible split point");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000606 SE->useIntv(SegStart, Stop);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000607 continue;
608 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000609 }
610
611 // Interference is after the last use.
612 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000613 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000614 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000615 }
616
617 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000618 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
619 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000620 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
621 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
622
623 // Is the register live-in?
624 if (!BI.LiveIn || !RegIn)
625 continue;
626
627 // We have an incoming register. Check for interference.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000628 SlotIndex Start, Stop;
629 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000630 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000631 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000632 << " -> BB#" << BI.MBB->getNumber() << " [" << Start << ';'
633 << BI.LastSplitPoint << '-' << Stop << ')');
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000634
635 // Check interference entering the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000636 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000637 // Block is interference-free.
638 DEBUG(dbgs() << ", no interference");
639 if (!BI.Uses) {
640 assert(BI.LiveThrough && "No uses, but not live through block?");
641 // Block is live-through without interference.
642 if (RegOut) {
643 DEBUG(dbgs() << ", no uses, live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000644 SE->useIntv(Start, Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000645 } else {
646 DEBUG(dbgs() << ", no uses, stack-out.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000647 SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000648 }
649 continue;
650 }
651 if (!BI.LiveThrough) {
652 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000653 SE->useIntv(Start, SE->leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000654 continue;
655 }
656 if (!RegOut) {
657 // Block is live-through, but exit bundle is on the stack.
658 // Spill immediately after the last use.
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000659 if (BI.LastUse < BI.LastSplitPoint) {
660 DEBUG(dbgs() << ", uses, stack-out.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000661 SE->useIntv(Start, SE->leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000662 continue;
663 }
664 // The last use is after the last split point, it is probably an
665 // indirect jump.
666 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
667 << BI.LastSplitPoint << ", stack-out.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000668 SlotIndex SegEnd = SE->leaveIntvBefore(BI.LastSplitPoint);
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000669 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000670 // Run a double interval from the split to the last use.
671 // This makes it possible to spill the complement without affecting the
672 // indirect branch.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000673 SE->overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000674 continue;
675 }
676 // Register is live-through.
677 DEBUG(dbgs() << ", uses, live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000678 SE->useIntv(Start, Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000679 continue;
680 }
681
682 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000683 DEBUG(dbgs() << ", interference from " << Intf.first());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000684
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000685 if (!BI.LiveThrough && Intf.first() >= BI.Kill) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000686 // The interference doesn't reach the outgoing segment.
687 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000688 SE->useIntv(Start, BI.Kill);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000689 continue;
690 }
691
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000692 if (!BI.Uses) {
693 // No uses in block, avoid interference by spilling as soon as possible.
694 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000695 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000696 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000697 continue;
698 }
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000699 if (Intf.first().getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000700 // There are interference-free uses at the beginning of the block.
701 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000702 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000703 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000704 Intf.first().getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000705 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
706 SlotIndex Use = (--UI)->getBoundaryIndex();
707 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000708 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000709 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000710 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000711 continue;
712 }
713
714 // Interference is before the first use.
715 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000716 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000717 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000718 }
719
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000720 SE->closeIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000721
722 // FIXME: Should we be more aggressive about splitting the stack region into
723 // per-block segments? The current approach allows the stack region to
724 // separate into connected components. Some components may be allocatable.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000725 SE->finish();
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000726 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000727
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000728 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000729 MF->verify(this, "After splitting live range around region");
730}
731
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000732unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
733 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000734 BitVector LiveBundles, BestBundles;
735 float BestCost = 0;
736 unsigned BestReg = 0;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000737
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000738 Order.rewind();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000739 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
740 if (GlobalCand.size() <= Cand)
741 GlobalCand.resize(Cand+1);
742 GlobalCand[Cand].PhysReg = PhysReg;
743
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000744 float Cost = calcSplitConstraints(PhysReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000745 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
746 if (BestReg && Cost >= BestCost) {
747 DEBUG(dbgs() << " higher.\n");
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000748 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000749 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000750
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000751 SpillPlacer->placeSpills(SplitConstraints, LiveBundles);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000752 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000753 if (!LiveBundles.any()) {
754 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000755 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000756 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000757
758 Cost += calcGlobalSplitCost(LiveBundles);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000759 DEBUG({
760 dbgs() << ", total = " << Cost << " with bundles";
761 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
762 dbgs() << " EB#" << i;
763 dbgs() << ".\n";
764 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000765 if (!BestReg || Cost < BestCost) {
766 BestReg = PhysReg;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000767 BestCost = 0.98f * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000768 BestBundles.swap(LiveBundles);
769 }
770 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000771
772 if (!BestReg)
773 return 0;
774
775 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000776 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000777 return 0;
778}
779
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000780
781//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000782// Local Splitting
783//===----------------------------------------------------------------------===//
784
785
786/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
787/// in order to use PhysReg between two entries in SA->UseSlots.
788///
789/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
790///
791void RAGreedy::calcGapWeights(unsigned PhysReg,
792 SmallVectorImpl<float> &GapWeight) {
793 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
794 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
795 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
796 const unsigned NumGaps = Uses.size()-1;
797
798 // Start and end points for the interference check.
799 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
800 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
801
802 GapWeight.assign(NumGaps, 0.0f);
803
804 // Add interference from each overlapping register.
805 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
806 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
807 .checkInterference())
808 continue;
809
810 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
811 // so we don't need InterferenceQuery.
812 //
813 // Interference that overlaps an instruction is counted in both gaps
814 // surrounding the instruction. The exception is interference before
815 // StartIdx and after StopIdx.
816 //
817 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
818 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
819 // Skip the gaps before IntI.
820 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
821 if (++Gap == NumGaps)
822 break;
823 if (Gap == NumGaps)
824 break;
825
826 // Update the gaps covered by IntI.
827 const float weight = IntI.value()->weight;
828 for (; Gap != NumGaps; ++Gap) {
829 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
830 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
831 break;
832 }
833 if (Gap == NumGaps)
834 break;
835 }
836 }
837}
838
839/// getPrevMappedIndex - Return the slot index of the last non-copy instruction
840/// before MI that has a slot index. If MI is the first mapped instruction in
841/// its block, return the block start index instead.
842///
843SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
844 assert(MI && "Missing MachineInstr");
845 const MachineBasicBlock *MBB = MI->getParent();
846 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
847 while (I != B)
848 if (!(--I)->isDebugValue() && !I->isCopy())
849 return Indexes->getInstructionIndex(I);
850 return Indexes->getMBBStartIdx(MBB);
851}
852
853/// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
854/// real non-copy instruction for each instruction in SA->UseSlots.
855///
856void RAGreedy::calcPrevSlots() {
857 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
858 PrevSlot.clear();
859 PrevSlot.reserve(Uses.size());
860 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
861 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
862 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
863 }
864}
865
866/// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
867/// be beneficial to split before UseSlots[i].
868///
869/// 0 is always a valid split point
870unsigned RAGreedy::nextSplitPoint(unsigned i) {
871 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
872 const unsigned Size = Uses.size();
873 assert(i != Size && "No split points after the end");
874 // Allow split before i when Uses[i] is not adjacent to the previous use.
875 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
876 ;
877 return i;
878}
879
880/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
881/// basic block.
882///
883unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
884 SmallVectorImpl<LiveInterval*> &NewVRegs) {
885 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
886 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
887
888 // Note that it is possible to have an interval that is live-in or live-out
889 // while only covering a single block - A phi-def can use undef values from
890 // predecessors, and the block could be a single-block loop.
891 // We don't bother doing anything clever about such a case, we simply assume
892 // that the interval is continuous from FirstUse to LastUse. We should make
893 // sure that we don't do anything illegal to such an interval, though.
894
895 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
896 if (Uses.size() <= 2)
897 return 0;
898 const unsigned NumGaps = Uses.size()-1;
899
900 DEBUG({
901 dbgs() << "tryLocalSplit: ";
902 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
903 dbgs() << ' ' << SA->UseSlots[i];
904 dbgs() << '\n';
905 });
906
907 // For every use, find the previous mapped non-copy instruction.
908 // We use this to detect valid split points, and to estimate new interval
909 // sizes.
910 calcPrevSlots();
911
912 unsigned BestBefore = NumGaps;
913 unsigned BestAfter = 0;
914 float BestDiff = 0;
915
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +0000916 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000917 SmallVector<float, 8> GapWeight;
918
919 Order.rewind();
920 while (unsigned PhysReg = Order.next()) {
921 // Keep track of the largest spill weight that would need to be evicted in
922 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
923 calcGapWeights(PhysReg, GapWeight);
924
925 // Try to find the best sequence of gaps to close.
926 // The new spill weight must be larger than any gap interference.
927
928 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
929 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
930
931 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
932 // It is the spill weight that needs to be evicted.
933 float MaxGap = GapWeight[0];
934 for (unsigned i = 1; i != SplitAfter; ++i)
935 MaxGap = std::max(MaxGap, GapWeight[i]);
936
937 for (;;) {
938 // Live before/after split?
939 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
940 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
941
942 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
943 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
944 << " i=" << MaxGap);
945
946 // Stop before the interval gets so big we wouldn't be making progress.
947 if (!LiveBefore && !LiveAfter) {
948 DEBUG(dbgs() << " all\n");
949 break;
950 }
951 // Should the interval be extended or shrunk?
952 bool Shrink = true;
953 if (MaxGap < HUGE_VALF) {
954 // Estimate the new spill weight.
955 //
956 // Each instruction reads and writes the register, except the first
957 // instr doesn't read when !FirstLive, and the last instr doesn't write
958 // when !LastLive.
959 //
960 // We will be inserting copies before and after, so the total number of
961 // reads and writes is 2 * EstUses.
962 //
963 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
964 2*(LiveBefore + LiveAfter);
965
966 // Try to guess the size of the new interval. This should be trivial,
967 // but the slot index of an inserted copy can be a lot smaller than the
968 // instruction it is inserted before if there are many dead indexes
969 // between them.
970 //
971 // We measure the distance from the instruction before SplitBefore to
972 // get a conservative estimate.
973 //
974 // The final distance can still be different if inserting copies
975 // triggers a slot index renumbering.
976 //
977 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
978 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
979 // Would this split be possible to allocate?
980 // Never allocate all gaps, we wouldn't be making progress.
981 float Diff = EstWeight - MaxGap;
982 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
983 if (Diff > 0) {
984 Shrink = false;
985 if (Diff > BestDiff) {
986 DEBUG(dbgs() << " (best)");
987 BestDiff = Diff;
988 BestBefore = SplitBefore;
989 BestAfter = SplitAfter;
990 }
991 }
992 }
993
994 // Try to shrink.
995 if (Shrink) {
996 SplitBefore = nextSplitPoint(SplitBefore);
997 if (SplitBefore < SplitAfter) {
998 DEBUG(dbgs() << " shrink\n");
999 // Recompute the max when necessary.
1000 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1001 MaxGap = GapWeight[SplitBefore];
1002 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1003 MaxGap = std::max(MaxGap, GapWeight[i]);
1004 }
1005 continue;
1006 }
1007 MaxGap = 0;
1008 }
1009
1010 // Try to extend the interval.
1011 if (SplitAfter >= NumGaps) {
1012 DEBUG(dbgs() << " end\n");
1013 break;
1014 }
1015
1016 DEBUG(dbgs() << " extend\n");
1017 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1018 SplitAfter != e; ++SplitAfter)
1019 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1020 continue;
1021 }
1022 }
1023
1024 // Didn't find any candidates?
1025 if (BestBefore == NumGaps)
1026 return 0;
1027
1028 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1029 << '-' << Uses[BestAfter] << ", " << BestDiff
1030 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1031
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001032 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001033 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001034
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001035 SE->openIntv();
1036 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1037 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1038 SE->useIntv(SegStart, SegStop);
1039 SE->closeIntv();
1040 SE->finish();
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001041 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001042 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001043
1044 return 0;
1045}
1046
1047//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001048// Live Range Splitting
1049//===----------------------------------------------------------------------===//
1050
1051/// trySplit - Try to split VirtReg or one of its interferences, making it
1052/// assignable.
1053/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1054unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1055 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001056 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001057 if (LIS->intervalIsInOneMBB(VirtReg)) {
1058 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001059 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001060 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001061 }
1062
1063 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001064
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001065 // Don't iterate global splitting.
1066 // Move straight to spilling if this range was produced by a global split.
1067 LiveRangeStage Stage = getStage(VirtReg);
1068 if (Stage >= RS_Block)
1069 return 0;
1070
1071 SA->analyze(&VirtReg);
1072
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001073 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001074 if (Stage < RS_Region) {
1075 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1076 if (PhysReg || !NewVRegs.empty())
1077 return PhysReg;
1078 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001079
1080 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001081 if (Stage < RS_Block) {
1082 SplitAnalysis::BlockPtrSet Blocks;
1083 if (SA->getMultiUseBlocks(Blocks)) {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001084 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001085 SE->reset(LREdit);
1086 SE->splitSingleBlocks(Blocks);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001087 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1088 if (VerifyEnabled)
1089 MF->verify(this, "After splitting live range around basic blocks");
1090 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001091 }
1092
1093 // Don't assign any physregs.
1094 return 0;
1095}
1096
1097
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001098//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001099// Main Entry Point
1100//===----------------------------------------------------------------------===//
1101
1102unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001103 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001104 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001105 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1106 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001107 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001108 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001109 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00001110
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +00001111 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001112 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001113
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001114 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1115
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001116 // The first time we see a live range, don't try to split or spill.
1117 // Wait until the second time, when all smaller ranges have been allocated.
1118 // This gives a better picture of the interference to split around.
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001119 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +00001120 if (Stage == RS_First) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001121 LRStage[VirtReg.reg] = RS_Second;
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001122 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001123 NewVRegs.push_back(&VirtReg);
1124 return 0;
1125 }
1126
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001127 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1128
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001129 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001130 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1131 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001132 return PhysReg;
1133
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001134 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001135 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001136 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1137 spiller().spill(LRE);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001138 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001139
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001140 if (VerifyEnabled)
1141 MF->verify(this, "After spilling");
1142
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001143 // The live virtual register requesting allocation was spilled, so tell
1144 // the caller not to allocate anything during this round.
1145 return 0;
1146}
1147
1148bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1149 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1150 << "********** Function: "
1151 << ((Value*)mf.getFunction())->getName() << '\n');
1152
1153 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001154 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001155 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001156
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001157 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001158 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001159 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001160 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001161 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001162 Loops = &getAnalysis<MachineLoopInfo>();
1163 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001164 Bundles = &getAnalysis<EdgeBundles>();
1165 SpillPlacer = &getAnalysis<SpillPlacement>();
1166
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001167 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001168 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001169 LRStage.clear();
1170 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001171 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001172
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001173 allocatePhysRegs();
1174 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001175 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001176
1177 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001178 {
1179 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001180 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001181 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001182
1183 // The pass output is in VirtRegMap. Release all the transient data.
1184 releaseMemory();
1185
1186 return true;
1187}