blob: 7564c1da89a63b6f910b71c600d28cc4dc1cb554 [file] [log] [blame]
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001//===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the RAGreedy function pass for register allocation in
11// optimized builds.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000016#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000017#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000018#include "LiveDebugVariables.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000019#include "LiveRangeEdit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000020#include "RegAllocBase.h"
21#include "Spiller.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000022#include "SpillPlacement.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000024#include "VirtRegMap.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000025#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000026#include "llvm/Analysis/AliasAnalysis.h"
27#include "llvm/Function.h"
28#include "llvm/PassAnalysisSupport.h"
29#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000030#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveIntervalAnalysis.h"
32#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000033#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000036#include "llvm/CodeGen/MachineLoopRanges.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000037#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/CodeGen/Passes.h"
39#include "llvm/CodeGen/RegAllocRegistry.h"
40#include "llvm/CodeGen/RegisterCoalescer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000042#include "llvm/Support/Debug.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000045#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000046
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000047#include <queue>
48
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000049using namespace llvm;
50
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000051STATISTIC(NumGlobalSplits, "Number of split global live ranges");
52STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000053STATISTIC(NumEvicted, "Number of interferences evicted");
54
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000055static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
56 createGreedyRegisterAllocator);
57
58namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000059class RAGreedy : public MachineFunctionPass,
60 public RegAllocBase,
61 private LiveRangeEdit::Delegate {
62
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000063 // context
64 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000065 BitVector ReservedRegs;
66
67 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000068 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000069 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000070 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000071 MachineLoopInfo *Loops;
72 MachineLoopRanges *LoopRanges;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000073 EdgeBundles *Bundles;
74 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000075
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000076 // state
77 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000078 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000079
80 // Live ranges pass through a number of stages as we try to allocate them.
81 // Some of the stages may also create new live ranges:
82 //
83 // - Region splitting.
84 // - Per-block splitting.
85 // - Local splitting.
86 // - Spilling.
87 //
88 // Ranges produced by one of the stages skip the previous stages when they are
89 // dequeued. This improves performance because we can skip interference checks
90 // that are unlikely to give any results. It also guarantees that the live
91 // range splitting algorithm terminates, something that is otherwise hard to
92 // ensure.
93 enum LiveRangeStage {
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +000094 RS_New, ///< Never seen before.
95 RS_First, ///< First time in the queue.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000096 RS_Second, ///< Second time in the queue.
97 RS_Region, ///< Produced by region splitting.
98 RS_Block, ///< Produced by per-block splitting.
99 RS_Local, ///< Produced by local splitting.
100 RS_Spill ///< Produced by spilling.
101 };
102
103 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
104
105 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
106 return LiveRangeStage(LRStage[VirtReg.reg]);
107 }
108
109 template<typename Iterator>
110 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
111 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000112 for (;Begin != End; ++Begin) {
113 unsigned Reg = (*Begin)->reg;
114 if (LRStage[Reg] == RS_New)
115 LRStage[Reg] = NewStage;
116 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000117 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000118
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000119 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000120 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000121 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000122
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000123 /// Cached per-block interference maps
124 InterferenceCache IntfCache;
125
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000126 /// All basic blocks where the current register is live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000127 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000128
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000129 /// Global live range splitting candidate info.
130 struct GlobalSplitCandidate {
131 unsigned PhysReg;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000132 BitVector LiveBundles;
133 };
134
135 /// Candidate info for for each PhysReg in AllocationOrder.
136 /// This vector never shrinks, but grows to the size of the largest register
137 /// class.
138 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
139
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000140 /// For every instruction in SA->UseSlots, store the previous non-copy
141 /// instruction.
142 SmallVector<SlotIndex, 8> PrevSlot;
143
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000144public:
145 RAGreedy();
146
147 /// Return the pass name.
148 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000149 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000150 }
151
152 /// RAGreedy analysis usage.
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000154 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000155 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000156 virtual void enqueue(LiveInterval *LI);
157 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000158 virtual unsigned selectOrSplit(LiveInterval&,
159 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000160
161 /// Perform register allocation.
162 virtual bool runOnMachineFunction(MachineFunction &mf);
163
164 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000165
166private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000167 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000168 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000169 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000170 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000171
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000172 bool addSplitConstraints(unsigned, float&);
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000173 float calcGlobalSplitCost(unsigned, const BitVector&);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000174 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
175 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000176 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
177 SlotIndex getPrevMappedIndex(const MachineInstr*);
178 void calcPrevSlots();
179 unsigned nextSplitPoint(unsigned);
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000180 bool canEvictInterference(LiveInterval&, unsigned, float&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000181
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000182 unsigned tryEvict(LiveInterval&, AllocationOrder&,
183 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000184 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
185 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000186 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
187 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000188 unsigned trySplit(LiveInterval&, AllocationOrder&,
189 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000190};
191} // end anonymous namespace
192
193char RAGreedy::ID = 0;
194
195FunctionPass* llvm::createGreedyRegisterAllocator() {
196 return new RAGreedy();
197}
198
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000199RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_New) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000200 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000201 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000202 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
203 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
204 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
205 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
206 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
207 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
208 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
209 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000210 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000211 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000212 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
213 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000214}
215
216void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
217 AU.setPreservesCFG();
218 AU.addRequired<AliasAnalysis>();
219 AU.addPreserved<AliasAnalysis>();
220 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000221 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000222 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000223 AU.addRequired<LiveDebugVariables>();
224 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000225 if (StrongPHIElim)
226 AU.addRequiredID(StrongPHIEliminationID);
227 AU.addRequiredTransitive<RegisterCoalescer>();
228 AU.addRequired<CalculateSpillWeights>();
229 AU.addRequired<LiveStacks>();
230 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000231 AU.addRequired<MachineDominatorTree>();
232 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000233 AU.addRequired<MachineLoopInfo>();
234 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000235 AU.addRequired<MachineLoopRanges>();
236 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000237 AU.addRequired<VirtRegMap>();
238 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000239 AU.addRequired<EdgeBundles>();
240 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000241 MachineFunctionPass::getAnalysisUsage(AU);
242}
243
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000244
245//===----------------------------------------------------------------------===//
246// LiveRangeEdit delegate methods
247//===----------------------------------------------------------------------===//
248
249void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
250 // LRE itself will remove from SlotIndexes and parent basic block.
251 VRM->RemoveMachineInstrFromMaps(MI);
252}
253
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000254bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
255 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
256 unassign(LIS->getInterval(VirtReg), PhysReg);
257 return true;
258 }
259 // Unassigned virtreg is probably in the priority queue.
260 // RegAllocBase will erase it after dequeueing.
261 return false;
262}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000263
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000264void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
265 unsigned PhysReg = VRM->getPhys(VirtReg);
266 if (!PhysReg)
267 return;
268
269 // Register is assigned, put it back on the queue for reassignment.
270 LiveInterval &LI = LIS->getInterval(VirtReg);
271 unassign(LI, PhysReg);
272 enqueue(&LI);
273}
274
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000275void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
276 // LRE may clone a virtual register because dead code elimination causes it to
277 // be split into connected components. Ensure that the new register gets the
278 // same stage as the parent.
279 LRStage.grow(New);
280 LRStage[New] = LRStage[Old];
281}
282
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000283void RAGreedy::releaseMemory() {
284 SpillerInstance.reset(0);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000285 LRStage.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000286 RegAllocBase::releaseMemory();
287}
288
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000289void RAGreedy::enqueue(LiveInterval *LI) {
290 // Prioritize live ranges by size, assigning larger ranges first.
291 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000292 const unsigned Size = LI->getSize();
293 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000294 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
295 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000296 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000297
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000298 LRStage.grow(Reg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000299 if (LRStage[Reg] == RS_New)
300 LRStage[Reg] = RS_First;
301
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000302 if (LRStage[Reg] == RS_Second)
303 // Unsplit ranges that couldn't be allocated immediately are deferred until
304 // everything else has been allocated. Long ranges are allocated last so
305 // they are split against realistic interference.
306 Prio = (1u << 31) - Size;
307 else {
308 // Everything else is allocated in long->short order. Long ranges that don't
309 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000310 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000311
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000312 // Boost ranges that have a physical register hint.
313 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
314 Prio |= (1u << 30);
315 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000316
317 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000318}
319
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000320LiveInterval *RAGreedy::dequeue() {
321 if (Queue.empty())
322 return 0;
323 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
324 Queue.pop();
325 return LI;
326}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000327
328//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000329// Interference eviction
330//===----------------------------------------------------------------------===//
331
332/// canEvict - Return true if all interferences between VirtReg and PhysReg can
333/// be evicted. Set maxWeight to the maximal spill weight of an interference.
334bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000335 float &MaxWeight) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000336 float Weight = 0;
337 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
338 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
339 // If there is 10 or more interferences, chances are one is smaller.
340 if (Q.collectInterferingVRegs(10) >= 10)
341 return false;
342
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000343 // Check if any interfering live range is heavier than VirtReg.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000344 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
345 LiveInterval *Intf = Q.interferingVRegs()[i];
346 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
347 return false;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000348 if (Intf->weight >= VirtReg.weight)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000349 return false;
350 Weight = std::max(Weight, Intf->weight);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000351 }
352 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000353 MaxWeight = Weight;
354 return true;
355}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000356
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000357/// tryEvict - Try to evict all interferences for a physreg.
358/// @param VirtReg Currently unassigned virtual register.
359/// @param Order Physregs to try.
360/// @return Physreg to assign VirtReg, or 0.
361unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
362 AllocationOrder &Order,
363 SmallVectorImpl<LiveInterval*> &NewVRegs){
364 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
365
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000366 // Keep track of the lightest single interference seen so far.
367 float BestWeight = 0;
368 unsigned BestPhys = 0;
369
370 Order.rewind();
371 while (unsigned PhysReg = Order.next()) {
372 float Weight = 0;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000373 if (!canEvictInterference(VirtReg, PhysReg, Weight))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000374 continue;
375
376 // This is an eviction candidate.
377 DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
378 << Weight << '\n');
379 if (BestPhys && Weight >= BestWeight)
380 continue;
381
382 // Best so far.
383 BestPhys = PhysReg;
384 BestWeight = Weight;
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000385 // Stop if the hint can be used.
386 if (Order.isHint(PhysReg))
387 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000388 }
389
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000390 if (!BestPhys)
391 return 0;
392
393 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
394 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
395 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
396 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
397 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
398 LiveInterval *Intf = Q.interferingVRegs()[i];
399 unassign(*Intf, VRM->getPhys(Intf->reg));
400 ++NumEvicted;
401 NewVRegs.push_back(Intf);
402 }
403 }
404 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000405}
406
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000407
408//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000409// Region Splitting
410//===----------------------------------------------------------------------===//
411
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000412/// addSplitConstraints - Fill out the SplitConstraints vector based on the
413/// interference pattern in Physreg and its aliases. Add the constraints to
414/// SpillPlacement and return the static cost of this split in Cost, assuming
415/// that all preferences in SplitConstraints are met.
416/// If it is evident that no bundles will be live, abort early and return false.
417bool RAGreedy::addSplitConstraints(unsigned PhysReg, float &Cost) {
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000418 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000419 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000420
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000421 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000422 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000423 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000424 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
425 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000426 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000427
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000428 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000429 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000430 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
431 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000432
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000433 if (!Intf.hasInterference())
434 continue;
435
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000436 // Number of spill code instructions to insert.
437 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000438
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000439 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000440 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000441 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000442 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000443 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000444 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000445 else if (Intf.first() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000446 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000447 }
448
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000449 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000450 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000451 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000452 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000453 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000454 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000455 else if (Intf.last() > (BI.LiveThrough ? BI.FirstUse : BI.Def))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000456 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000457 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000458
459 // Accumulate the total frequency of inserted spill code.
460 if (Ins)
461 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000462 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000463
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000464 // Add constraints for use-blocks. Note that these are the only constraints
465 // that may add a positive bias, it is downhill from here.
466 SpillPlacer->addConstraints(SplitConstraints);
467 if (SpillPlacer->getPositiveNodes() == 0)
468 return false;
469
470 Cost = StaticCost;
471
472 // Now handle the live-through blocks without uses. These can only add
473 // negative bias, so we can abort whenever there are no more positive nodes.
474 // Compute constraints for a group of 8 blocks at a time.
475 const unsigned GroupSize = 8;
476 SpillPlacement::BlockConstraint BCS[GroupSize];
477 unsigned B = 0;
478
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000479 ArrayRef<unsigned> ThroughBlocks = SA->getThroughBlocks();
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000480 for (unsigned i = 0; i != ThroughBlocks.size(); ++i) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000481 unsigned Number = ThroughBlocks[i];
482 assert(B < GroupSize && "Array overflow");
483 BCS[B].Number = Number;
484 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000485
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000486 if (Intf.hasInterference()) {
487 // Interference for the live-in value.
488 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
489 BCS[B].Entry = SpillPlacement::MustSpill;
490 else
491 BCS[B].Entry = SpillPlacement::PrefSpill;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000492
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000493 // Interference for the live-out value.
494 if (Intf.last() >= SA->getLastSplitPoint(Number))
495 BCS[B].Exit = SpillPlacement::MustSpill;
496 else
497 BCS[B].Exit = SpillPlacement::PrefSpill;
498 } else {
499 // No interference, transparent block.
500 BCS[B].Entry = BCS[B].Exit = SpillPlacement::DontCare;
501 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000502
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000503 if (++B == GroupSize) {
504 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
505 SpillPlacer->addConstraints(Array);
506 B = 0;
507 // Abort early when all hope is lost.
508 if (SpillPlacer->getPositiveNodes() == 0)
509 return false;
510 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000511 }
512
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000513 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
514 SpillPlacer->addConstraints(Array);
515 return SpillPlacer->getPositiveNodes() != 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000516}
517
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000518
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000519/// calcGlobalSplitCost - Return the global split cost of following the split
520/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000521/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000522///
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000523float RAGreedy::calcGlobalSplitCost(unsigned PhysReg,
524 const BitVector &LiveBundles) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000525 float GlobalCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000526 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
527 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
528 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000529 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000530 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
531 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
532 unsigned Ins = 0;
533
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000534 if (BI.LiveIn)
535 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
536 if (BI.LiveOut)
537 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000538 if (Ins)
539 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000540 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000541
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000542 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000543 ArrayRef<unsigned> ThroughBlocks = SA->getThroughBlocks();
544 SplitConstraints.resize(UseBlocks.size() + ThroughBlocks.size());
545 for (unsigned i = 0; i != ThroughBlocks.size(); ++i) {
546 unsigned Number = ThroughBlocks[i];
547 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
548 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000549 if (!RegIn && !RegOut)
550 continue;
551 if (RegIn && RegOut) {
552 // We need double spill code if this block has interference.
553 Intf.moveToBlock(Number);
554 if (Intf.hasInterference())
555 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
556 continue;
557 }
558 // live-in / stack-out or stack-in live-out.
559 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000560 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000561 return GlobalCost;
562}
563
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000564/// splitAroundRegion - Split VirtReg around the region determined by
565/// LiveBundles. Make an effort to avoid interference from PhysReg.
566///
567/// The 'register' interval is going to contain as many uses as possible while
568/// avoiding interference. The 'stack' interval is the complement constructed by
569/// SplitEditor. It will contain the rest.
570///
571void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
572 const BitVector &LiveBundles,
573 SmallVectorImpl<LiveInterval*> &NewVRegs) {
574 DEBUG({
575 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
576 << " with bundles";
577 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
578 dbgs() << " EB#" << i;
579 dbgs() << ".\n";
580 });
581
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000582 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000583 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000584 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000585
586 // Create the main cross-block interval.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000587 SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000588
589 // First add all defs that are live out of a block.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000590 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
591 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
592 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000593 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
594 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
595
596 // Should the register be live out?
597 if (!BI.LiveOut || !RegOut)
598 continue;
599
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000600 SlotIndex Start, Stop;
601 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000602 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000603 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000604 << Bundles->getBundle(BI.MBB->getNumber(), 1)
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000605 << " [" << Start << ';'
606 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
607 << ") intf [" << Intf.first() << ';' << Intf.last() << ')');
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000608
609 // The interference interval should either be invalid or overlap MBB.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000610 assert((!Intf.hasInterference() || Intf.first() < Stop)
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000611 && "Bad interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000612 assert((!Intf.hasInterference() || Intf.last() > Start)
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000613 && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000614
615 // Check interference leaving the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000616 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000617 // Block is interference-free.
618 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000619 if (!BI.LiveThrough) {
620 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000621 SE->useIntv(SE->enterIntvBefore(BI.Def), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000622 continue;
623 }
624 if (!RegIn) {
625 // Block is live-through, but entry bundle is on the stack.
626 // Reload just before the first use.
627 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000628 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000629 continue;
630 }
631 DEBUG(dbgs() << ", live-through.\n");
632 continue;
633 }
634
635 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000636 DEBUG(dbgs() << ", interference to " << Intf.last());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000637
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000638 if (!BI.LiveThrough && Intf.last() <= BI.Def) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000639 // The interference doesn't reach the outgoing segment.
640 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000641 SE->useIntv(BI.Def, Stop);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000642 continue;
643 }
644
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000645 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000646 if (Intf.last().getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000647 // There are interference-free uses at the end of the block.
648 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000649 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000650 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000651 Intf.last().getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000652 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
653 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000654 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000655 // Only attempt a split befroe the last split point.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000656 if (Use.getBaseIndex() <= LastSplitPoint) {
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000657 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000658 SlotIndex SegStart = SE->enterIntvBefore(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000659 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000660 assert(SegStart < LastSplitPoint && "Impossible split point");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000661 SE->useIntv(SegStart, Stop);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000662 continue;
663 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000664 }
665
666 // Interference is after the last use.
667 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000668 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000669 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000670 }
671
672 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000673 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
674 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000675 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
676 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
677
678 // Is the register live-in?
679 if (!BI.LiveIn || !RegIn)
680 continue;
681
682 // We have an incoming register. Check for interference.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000683 SlotIndex Start, Stop;
684 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000685 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000686 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000687 << " -> BB#" << BI.MBB->getNumber() << " [" << Start << ';'
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000688 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
689 << ')');
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000690
691 // Check interference entering the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000692 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000693 // Block is interference-free.
694 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000695 if (!BI.LiveThrough) {
696 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000697 SE->useIntv(Start, SE->leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000698 continue;
699 }
700 if (!RegOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000701 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000702 // Block is live-through, but exit bundle is on the stack.
703 // Spill immediately after the last use.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000704 if (BI.LastUse < LastSplitPoint) {
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000705 DEBUG(dbgs() << ", uses, stack-out.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000706 SE->useIntv(Start, SE->leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000707 continue;
708 }
709 // The last use is after the last split point, it is probably an
710 // indirect jump.
711 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000712 << LastSplitPoint << ", stack-out.\n");
713 SlotIndex SegEnd = SE->leaveIntvBefore(LastSplitPoint);
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000714 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000715 // Run a double interval from the split to the last use.
716 // This makes it possible to spill the complement without affecting the
717 // indirect branch.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000718 SE->overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000719 continue;
720 }
721 // Register is live-through.
722 DEBUG(dbgs() << ", uses, live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000723 SE->useIntv(Start, Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000724 continue;
725 }
726
727 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000728 DEBUG(dbgs() << ", interference from " << Intf.first());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000729
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000730 if (!BI.LiveThrough && Intf.first() >= BI.Kill) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000731 // The interference doesn't reach the outgoing segment.
732 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000733 SE->useIntv(Start, BI.Kill);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000734 continue;
735 }
736
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000737 if (Intf.first().getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000738 // There are interference-free uses at the beginning of the block.
739 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000740 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000741 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000742 Intf.first().getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000743 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
744 SlotIndex Use = (--UI)->getBoundaryIndex();
745 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000746 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000747 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000748 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000749 continue;
750 }
751
752 // Interference is before the first use.
753 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000754 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000755 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000756 }
757
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000758 // Handle live-through blocks.
759 ArrayRef<unsigned> ThroughBlocks = SA->getThroughBlocks();
760 for (unsigned i = 0; i != ThroughBlocks.size(); ++i) {
761 unsigned Number = ThroughBlocks[i];
762 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
763 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
764 DEBUG(dbgs() << "Live through BB#" << Number << '\n');
765 if (RegIn && RegOut) {
766 Intf.moveToBlock(Number);
767 if (!Intf.hasInterference()) {
768 SE->useIntv(Indexes->getMBBStartIdx(Number),
769 Indexes->getMBBEndIdx(Number));
770 continue;
771 }
772 }
773 MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
774 if (RegIn)
775 SE->leaveIntvAtTop(*MBB);
776 if (RegOut)
777 SE->enterIntvAtEnd(*MBB);
778 }
779
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000780 SE->closeIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000781
782 // FIXME: Should we be more aggressive about splitting the stack region into
783 // per-block segments? The current approach allows the stack region to
784 // separate into connected components. Some components may be allocatable.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000785 SE->finish();
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000786 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000787
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000788 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000789 MF->verify(this, "After splitting live range around region");
790}
791
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000792unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
793 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000794 BitVector LiveBundles, BestBundles;
795 float BestCost = 0;
796 unsigned BestReg = 0;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000797
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000798 Order.rewind();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000799 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
800 if (GlobalCand.size() <= Cand)
801 GlobalCand.resize(Cand+1);
802 GlobalCand[Cand].PhysReg = PhysReg;
803
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000804 SpillPlacer->prepare(LiveBundles);
805 float Cost;
806 if (!addSplitConstraints(PhysReg, Cost)) {
807 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bias\n");
808 continue;
809 }
810 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tbiased = "
811 << SpillPlacer->getPositiveNodes() << ", static = " << Cost);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000812 if (BestReg && Cost >= BestCost) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000813 DEBUG(dbgs() << " worse than " << PrintReg(BestReg, TRI) << '\n');
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000814 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000815 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000816
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000817 SpillPlacer->finish();
818
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000819 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000820 if (!LiveBundles.any()) {
821 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000822 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000823 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000824
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000825 Cost += calcGlobalSplitCost(PhysReg, LiveBundles);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000826 DEBUG({
827 dbgs() << ", total = " << Cost << " with bundles";
828 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
829 dbgs() << " EB#" << i;
830 dbgs() << ".\n";
831 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000832 if (!BestReg || Cost < BestCost) {
833 BestReg = PhysReg;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000834 BestCost = 0.98f * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000835 BestBundles.swap(LiveBundles);
836 }
837 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000838
839 if (!BestReg)
840 return 0;
841
842 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000843 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000844 return 0;
845}
846
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000847
848//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000849// Local Splitting
850//===----------------------------------------------------------------------===//
851
852
853/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
854/// in order to use PhysReg between two entries in SA->UseSlots.
855///
856/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
857///
858void RAGreedy::calcGapWeights(unsigned PhysReg,
859 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000860 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
861 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000862 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
863 const unsigned NumGaps = Uses.size()-1;
864
865 // Start and end points for the interference check.
866 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
867 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
868
869 GapWeight.assign(NumGaps, 0.0f);
870
871 // Add interference from each overlapping register.
872 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
873 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
874 .checkInterference())
875 continue;
876
877 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
878 // so we don't need InterferenceQuery.
879 //
880 // Interference that overlaps an instruction is counted in both gaps
881 // surrounding the instruction. The exception is interference before
882 // StartIdx and after StopIdx.
883 //
884 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
885 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
886 // Skip the gaps before IntI.
887 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
888 if (++Gap == NumGaps)
889 break;
890 if (Gap == NumGaps)
891 break;
892
893 // Update the gaps covered by IntI.
894 const float weight = IntI.value()->weight;
895 for (; Gap != NumGaps; ++Gap) {
896 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
897 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
898 break;
899 }
900 if (Gap == NumGaps)
901 break;
902 }
903 }
904}
905
906/// getPrevMappedIndex - Return the slot index of the last non-copy instruction
907/// before MI that has a slot index. If MI is the first mapped instruction in
908/// its block, return the block start index instead.
909///
910SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
911 assert(MI && "Missing MachineInstr");
912 const MachineBasicBlock *MBB = MI->getParent();
913 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
914 while (I != B)
915 if (!(--I)->isDebugValue() && !I->isCopy())
916 return Indexes->getInstructionIndex(I);
917 return Indexes->getMBBStartIdx(MBB);
918}
919
920/// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
921/// real non-copy instruction for each instruction in SA->UseSlots.
922///
923void RAGreedy::calcPrevSlots() {
924 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
925 PrevSlot.clear();
926 PrevSlot.reserve(Uses.size());
927 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
928 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
929 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
930 }
931}
932
933/// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
934/// be beneficial to split before UseSlots[i].
935///
936/// 0 is always a valid split point
937unsigned RAGreedy::nextSplitPoint(unsigned i) {
938 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
939 const unsigned Size = Uses.size();
940 assert(i != Size && "No split points after the end");
941 // Allow split before i when Uses[i] is not adjacent to the previous use.
942 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
943 ;
944 return i;
945}
946
947/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
948/// basic block.
949///
950unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
951 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000952 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
953 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000954
955 // Note that it is possible to have an interval that is live-in or live-out
956 // while only covering a single block - A phi-def can use undef values from
957 // predecessors, and the block could be a single-block loop.
958 // We don't bother doing anything clever about such a case, we simply assume
959 // that the interval is continuous from FirstUse to LastUse. We should make
960 // sure that we don't do anything illegal to such an interval, though.
961
962 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
963 if (Uses.size() <= 2)
964 return 0;
965 const unsigned NumGaps = Uses.size()-1;
966
967 DEBUG({
968 dbgs() << "tryLocalSplit: ";
969 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
970 dbgs() << ' ' << SA->UseSlots[i];
971 dbgs() << '\n';
972 });
973
974 // For every use, find the previous mapped non-copy instruction.
975 // We use this to detect valid split points, and to estimate new interval
976 // sizes.
977 calcPrevSlots();
978
979 unsigned BestBefore = NumGaps;
980 unsigned BestAfter = 0;
981 float BestDiff = 0;
982
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +0000983 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000984 SmallVector<float, 8> GapWeight;
985
986 Order.rewind();
987 while (unsigned PhysReg = Order.next()) {
988 // Keep track of the largest spill weight that would need to be evicted in
989 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
990 calcGapWeights(PhysReg, GapWeight);
991
992 // Try to find the best sequence of gaps to close.
993 // The new spill weight must be larger than any gap interference.
994
995 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
996 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
997
998 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
999 // It is the spill weight that needs to be evicted.
1000 float MaxGap = GapWeight[0];
1001 for (unsigned i = 1; i != SplitAfter; ++i)
1002 MaxGap = std::max(MaxGap, GapWeight[i]);
1003
1004 for (;;) {
1005 // Live before/after split?
1006 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1007 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1008
1009 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1010 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1011 << " i=" << MaxGap);
1012
1013 // Stop before the interval gets so big we wouldn't be making progress.
1014 if (!LiveBefore && !LiveAfter) {
1015 DEBUG(dbgs() << " all\n");
1016 break;
1017 }
1018 // Should the interval be extended or shrunk?
1019 bool Shrink = true;
1020 if (MaxGap < HUGE_VALF) {
1021 // Estimate the new spill weight.
1022 //
1023 // Each instruction reads and writes the register, except the first
1024 // instr doesn't read when !FirstLive, and the last instr doesn't write
1025 // when !LastLive.
1026 //
1027 // We will be inserting copies before and after, so the total number of
1028 // reads and writes is 2 * EstUses.
1029 //
1030 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1031 2*(LiveBefore + LiveAfter);
1032
1033 // Try to guess the size of the new interval. This should be trivial,
1034 // but the slot index of an inserted copy can be a lot smaller than the
1035 // instruction it is inserted before if there are many dead indexes
1036 // between them.
1037 //
1038 // We measure the distance from the instruction before SplitBefore to
1039 // get a conservative estimate.
1040 //
1041 // The final distance can still be different if inserting copies
1042 // triggers a slot index renumbering.
1043 //
1044 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1045 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1046 // Would this split be possible to allocate?
1047 // Never allocate all gaps, we wouldn't be making progress.
1048 float Diff = EstWeight - MaxGap;
1049 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1050 if (Diff > 0) {
1051 Shrink = false;
1052 if (Diff > BestDiff) {
1053 DEBUG(dbgs() << " (best)");
1054 BestDiff = Diff;
1055 BestBefore = SplitBefore;
1056 BestAfter = SplitAfter;
1057 }
1058 }
1059 }
1060
1061 // Try to shrink.
1062 if (Shrink) {
1063 SplitBefore = nextSplitPoint(SplitBefore);
1064 if (SplitBefore < SplitAfter) {
1065 DEBUG(dbgs() << " shrink\n");
1066 // Recompute the max when necessary.
1067 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1068 MaxGap = GapWeight[SplitBefore];
1069 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1070 MaxGap = std::max(MaxGap, GapWeight[i]);
1071 }
1072 continue;
1073 }
1074 MaxGap = 0;
1075 }
1076
1077 // Try to extend the interval.
1078 if (SplitAfter >= NumGaps) {
1079 DEBUG(dbgs() << " end\n");
1080 break;
1081 }
1082
1083 DEBUG(dbgs() << " extend\n");
1084 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1085 SplitAfter != e; ++SplitAfter)
1086 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1087 continue;
1088 }
1089 }
1090
1091 // Didn't find any candidates?
1092 if (BestBefore == NumGaps)
1093 return 0;
1094
1095 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1096 << '-' << Uses[BestAfter] << ", " << BestDiff
1097 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1098
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001099 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001100 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001101
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001102 SE->openIntv();
1103 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1104 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1105 SE->useIntv(SegStart, SegStop);
1106 SE->closeIntv();
1107 SE->finish();
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001108 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001109 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001110
1111 return 0;
1112}
1113
1114//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001115// Live Range Splitting
1116//===----------------------------------------------------------------------===//
1117
1118/// trySplit - Try to split VirtReg or one of its interferences, making it
1119/// assignable.
1120/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1121unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1122 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001123 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001124 if (LIS->intervalIsInOneMBB(VirtReg)) {
1125 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001126 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001127 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001128 }
1129
1130 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001131
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001132 // Don't iterate global splitting.
1133 // Move straight to spilling if this range was produced by a global split.
1134 LiveRangeStage Stage = getStage(VirtReg);
1135 if (Stage >= RS_Block)
1136 return 0;
1137
1138 SA->analyze(&VirtReg);
1139
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001140 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001141 if (Stage < RS_Region) {
1142 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1143 if (PhysReg || !NewVRegs.empty())
1144 return PhysReg;
1145 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001146
1147 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001148 if (Stage < RS_Block) {
1149 SplitAnalysis::BlockPtrSet Blocks;
1150 if (SA->getMultiUseBlocks(Blocks)) {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001151 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001152 SE->reset(LREdit);
1153 SE->splitSingleBlocks(Blocks);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001154 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1155 if (VerifyEnabled)
1156 MF->verify(this, "After splitting live range around basic blocks");
1157 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001158 }
1159
1160 // Don't assign any physregs.
1161 return 0;
1162}
1163
1164
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001165//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001166// Main Entry Point
1167//===----------------------------------------------------------------------===//
1168
1169unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001170 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001171 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001172 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1173 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001174 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001175 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001176 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00001177
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +00001178 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001179 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001180
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001181 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1182
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001183 // The first time we see a live range, don't try to split or spill.
1184 // Wait until the second time, when all smaller ranges have been allocated.
1185 // This gives a better picture of the interference to split around.
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001186 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +00001187 if (Stage == RS_First) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001188 LRStage[VirtReg.reg] = RS_Second;
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001189 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001190 NewVRegs.push_back(&VirtReg);
1191 return 0;
1192 }
1193
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001194 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1195
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001196 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001197 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1198 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001199 return PhysReg;
1200
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001201 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001202 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001203 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1204 spiller().spill(LRE);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001205 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001206
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001207 if (VerifyEnabled)
1208 MF->verify(this, "After spilling");
1209
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001210 // The live virtual register requesting allocation was spilled, so tell
1211 // the caller not to allocate anything during this round.
1212 return 0;
1213}
1214
1215bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1216 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1217 << "********** Function: "
1218 << ((Value*)mf.getFunction())->getName() << '\n');
1219
1220 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001221 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001222 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001223
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001224 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001225 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001226 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001227 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001228 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001229 Loops = &getAnalysis<MachineLoopInfo>();
1230 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001231 Bundles = &getAnalysis<EdgeBundles>();
1232 SpillPlacer = &getAnalysis<SpillPlacement>();
1233
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001234 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001235 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001236 LRStage.clear();
1237 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001238 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001239
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001240 allocatePhysRegs();
1241 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001242 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001243
1244 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001245 {
1246 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001247 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001248 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001249
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001250 // Write out new DBG_VALUE instructions.
1251 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
1252
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001253 // The pass output is in VirtRegMap. Release all the transient data.
1254 releaseMemory();
1255
1256 return true;
1257}