blob: 889bca3011d929543e2cb2dae6c8b525c9304600 [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 Olesen7b41fbe2011-04-07 17:27:46 +0000126 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000127 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000128
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000129 /// All basic blocks where the current register is live-through and
130 /// interference free.
131 SmallVector<unsigned, 8> TransparentBlocks;
132
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000133 /// Global live range splitting candidate info.
134 struct GlobalSplitCandidate {
135 unsigned PhysReg;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000136 BitVector LiveBundles;
137 };
138
139 /// Candidate info for for each PhysReg in AllocationOrder.
140 /// This vector never shrinks, but grows to the size of the largest register
141 /// class.
142 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
143
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000144 /// For every instruction in SA->UseSlots, store the previous non-copy
145 /// instruction.
146 SmallVector<SlotIndex, 8> PrevSlot;
147
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000148public:
149 RAGreedy();
150
151 /// Return the pass name.
152 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000153 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000154 }
155
156 /// RAGreedy analysis usage.
157 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000158 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000159 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000160 virtual void enqueue(LiveInterval *LI);
161 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000162 virtual unsigned selectOrSplit(LiveInterval&,
163 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000164
165 /// Perform register allocation.
166 virtual bool runOnMachineFunction(MachineFunction &mf);
167
168 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000169
170private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000171 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000172 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000173 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000174 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000175
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000176 bool addSplitConstraints(unsigned, float&);
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000177 float calcGlobalSplitCost(unsigned, const BitVector&);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000178 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
179 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000180 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
181 SlotIndex getPrevMappedIndex(const MachineInstr*);
182 void calcPrevSlots();
183 unsigned nextSplitPoint(unsigned);
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000184 bool canEvictInterference(LiveInterval&, unsigned, float&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000185
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000186 unsigned tryEvict(LiveInterval&, AllocationOrder&,
187 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000188 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
189 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000190 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
191 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000192 unsigned trySplit(LiveInterval&, AllocationOrder&,
193 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000194};
195} // end anonymous namespace
196
197char RAGreedy::ID = 0;
198
199FunctionPass* llvm::createGreedyRegisterAllocator() {
200 return new RAGreedy();
201}
202
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000203RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_New) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000204 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000205 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000206 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
207 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
208 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
209 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
210 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
211 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
212 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
213 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000214 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000215 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000216 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
217 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000218}
219
220void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
221 AU.setPreservesCFG();
222 AU.addRequired<AliasAnalysis>();
223 AU.addPreserved<AliasAnalysis>();
224 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000225 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000226 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000227 AU.addRequired<LiveDebugVariables>();
228 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000229 if (StrongPHIElim)
230 AU.addRequiredID(StrongPHIEliminationID);
231 AU.addRequiredTransitive<RegisterCoalescer>();
232 AU.addRequired<CalculateSpillWeights>();
233 AU.addRequired<LiveStacks>();
234 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000235 AU.addRequired<MachineDominatorTree>();
236 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000237 AU.addRequired<MachineLoopInfo>();
238 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000239 AU.addRequired<MachineLoopRanges>();
240 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000241 AU.addRequired<VirtRegMap>();
242 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000243 AU.addRequired<EdgeBundles>();
244 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000245 MachineFunctionPass::getAnalysisUsage(AU);
246}
247
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000248
249//===----------------------------------------------------------------------===//
250// LiveRangeEdit delegate methods
251//===----------------------------------------------------------------------===//
252
253void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
254 // LRE itself will remove from SlotIndexes and parent basic block.
255 VRM->RemoveMachineInstrFromMaps(MI);
256}
257
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000258bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
259 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
260 unassign(LIS->getInterval(VirtReg), PhysReg);
261 return true;
262 }
263 // Unassigned virtreg is probably in the priority queue.
264 // RegAllocBase will erase it after dequeueing.
265 return false;
266}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000267
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000268void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
269 unsigned PhysReg = VRM->getPhys(VirtReg);
270 if (!PhysReg)
271 return;
272
273 // Register is assigned, put it back on the queue for reassignment.
274 LiveInterval &LI = LIS->getInterval(VirtReg);
275 unassign(LI, PhysReg);
276 enqueue(&LI);
277}
278
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000279void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
280 // LRE may clone a virtual register because dead code elimination causes it to
281 // be split into connected components. Ensure that the new register gets the
282 // same stage as the parent.
283 LRStage.grow(New);
284 LRStage[New] = LRStage[Old];
285}
286
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000287void RAGreedy::releaseMemory() {
288 SpillerInstance.reset(0);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000289 LRStage.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000290 RegAllocBase::releaseMemory();
291}
292
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000293void RAGreedy::enqueue(LiveInterval *LI) {
294 // Prioritize live ranges by size, assigning larger ranges first.
295 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000296 const unsigned Size = LI->getSize();
297 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000298 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
299 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000300 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000301
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000302 LRStage.grow(Reg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000303 if (LRStage[Reg] == RS_New)
304 LRStage[Reg] = RS_First;
305
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000306 if (LRStage[Reg] == RS_Second)
307 // Unsplit ranges that couldn't be allocated immediately are deferred until
308 // everything else has been allocated. Long ranges are allocated last so
309 // they are split against realistic interference.
310 Prio = (1u << 31) - Size;
311 else {
312 // Everything else is allocated in long->short order. Long ranges that don't
313 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000314 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000315
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000316 // Boost ranges that have a physical register hint.
317 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
318 Prio |= (1u << 30);
319 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000320
321 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000322}
323
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000324LiveInterval *RAGreedy::dequeue() {
325 if (Queue.empty())
326 return 0;
327 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
328 Queue.pop();
329 return LI;
330}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000331
332//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000333// Interference eviction
334//===----------------------------------------------------------------------===//
335
336/// canEvict - Return true if all interferences between VirtReg and PhysReg can
337/// be evicted. Set maxWeight to the maximal spill weight of an interference.
338bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000339 float &MaxWeight) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000340 float Weight = 0;
341 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
342 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
343 // If there is 10 or more interferences, chances are one is smaller.
344 if (Q.collectInterferingVRegs(10) >= 10)
345 return false;
346
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000347 // Check if any interfering live range is heavier than VirtReg.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000348 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
349 LiveInterval *Intf = Q.interferingVRegs()[i];
350 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
351 return false;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000352 if (Intf->weight >= VirtReg.weight)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000353 return false;
354 Weight = std::max(Weight, Intf->weight);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000355 }
356 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000357 MaxWeight = Weight;
358 return true;
359}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000360
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000361/// tryEvict - Try to evict all interferences for a physreg.
362/// @param VirtReg Currently unassigned virtual register.
363/// @param Order Physregs to try.
364/// @return Physreg to assign VirtReg, or 0.
365unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
366 AllocationOrder &Order,
367 SmallVectorImpl<LiveInterval*> &NewVRegs){
368 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
369
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000370 // Keep track of the lightest single interference seen so far.
371 float BestWeight = 0;
372 unsigned BestPhys = 0;
373
374 Order.rewind();
375 while (unsigned PhysReg = Order.next()) {
376 float Weight = 0;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000377 if (!canEvictInterference(VirtReg, PhysReg, Weight))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000378 continue;
379
380 // This is an eviction candidate.
381 DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
382 << Weight << '\n');
383 if (BestPhys && Weight >= BestWeight)
384 continue;
385
386 // Best so far.
387 BestPhys = PhysReg;
388 BestWeight = Weight;
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000389 // Stop if the hint can be used.
390 if (Order.isHint(PhysReg))
391 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000392 }
393
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000394 if (!BestPhys)
395 return 0;
396
397 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
398 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
399 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
400 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
401 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
402 LiveInterval *Intf = Q.interferingVRegs()[i];
403 unassign(*Intf, VRM->getPhys(Intf->reg));
404 ++NumEvicted;
405 NewVRegs.push_back(Intf);
406 }
407 }
408 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000409}
410
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000411
412//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000413// Region Splitting
414//===----------------------------------------------------------------------===//
415
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000416/// addSplitConstraints - Fill out the SplitConstraints vector based on the
417/// interference pattern in Physreg and its aliases. Add the constraints to
418/// SpillPlacement and return the static cost of this split in Cost, assuming
419/// that all preferences in SplitConstraints are met.
420/// If it is evident that no bundles will be live, abort early and return false.
421bool RAGreedy::addSplitConstraints(unsigned PhysReg, float &Cost) {
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000422 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000423 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000424
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000425 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000426 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000427 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000428 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
429 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000430 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000431
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000432 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000433 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000434 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
435 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000436
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000437 if (!Intf.hasInterference())
438 continue;
439
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000440 // Number of spill code instructions to insert.
441 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000442
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000443 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000444 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000445 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000446 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000447 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000448 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000449 else if (Intf.first() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000450 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000451 }
452
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000453 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000454 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000455 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000456 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000457 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000458 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000459 else if (Intf.last() > (BI.LiveThrough ? BI.FirstUse : BI.Def))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000460 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000461 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000462
463 // Accumulate the total frequency of inserted spill code.
464 if (Ins)
465 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000466 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000467
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000468 // Add constraints for use-blocks. Note that these are the only constraints
469 // that may add a positive bias, it is downhill from here.
470 SpillPlacer->addConstraints(SplitConstraints);
471 if (SpillPlacer->getPositiveNodes() == 0)
472 return false;
473
474 Cost = StaticCost;
475
476 // Now handle the live-through blocks without uses. These can only add
477 // negative bias, so we can abort whenever there are no more positive nodes.
478 // Compute constraints for a group of 8 blocks at a time.
479 const unsigned GroupSize = 8;
480 SpillPlacement::BlockConstraint BCS[GroupSize];
481 unsigned B = 0;
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000482 TransparentBlocks.clear();
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000483
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000484 ArrayRef<unsigned> ThroughBlocks = SA->getThroughBlocks();
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000485 for (unsigned i = 0; i != ThroughBlocks.size(); ++i) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000486 unsigned Number = ThroughBlocks[i];
487 assert(B < GroupSize && "Array overflow");
488 BCS[B].Number = Number;
489 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000490
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000491 if (!Intf.hasInterference()) {
492 TransparentBlocks.push_back(Number);
493 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000494 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000495
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000496 // Interference for the live-in value.
497 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
498 BCS[B].Entry = SpillPlacement::MustSpill;
499 else
500 BCS[B].Entry = SpillPlacement::PrefSpill;
501
502 // Interference for the live-out value.
503 if (Intf.last() >= SA->getLastSplitPoint(Number))
504 BCS[B].Exit = SpillPlacement::MustSpill;
505 else
506 BCS[B].Exit = SpillPlacement::PrefSpill;
507
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000508 if (++B == GroupSize) {
509 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
510 SpillPlacer->addConstraints(Array);
511 B = 0;
512 // Abort early when all hope is lost.
513 if (SpillPlacer->getPositiveNodes() == 0)
514 return false;
515 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000516 }
517
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000518 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
519 SpillPlacer->addConstraints(Array);
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000520 if (SpillPlacer->getPositiveNodes() == 0)
521 return false;
522
523 // There is still some positive bias. Add all the links.
524 SpillPlacer->addLinks(TransparentBlocks);
525 return true;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000526}
527
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000528
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000529/// calcGlobalSplitCost - Return the global split cost of following the split
530/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000531/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000532///
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000533float RAGreedy::calcGlobalSplitCost(unsigned PhysReg,
534 const BitVector &LiveBundles) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000535 float GlobalCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000536 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
537 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
538 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000539 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000540 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
541 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
542 unsigned Ins = 0;
543
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000544 if (BI.LiveIn)
545 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
546 if (BI.LiveOut)
547 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000548 if (Ins)
549 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000550 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000551
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000552 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000553 ArrayRef<unsigned> ThroughBlocks = SA->getThroughBlocks();
554 SplitConstraints.resize(UseBlocks.size() + ThroughBlocks.size());
555 for (unsigned i = 0; i != ThroughBlocks.size(); ++i) {
556 unsigned Number = ThroughBlocks[i];
557 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
558 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000559 if (!RegIn && !RegOut)
560 continue;
561 if (RegIn && RegOut) {
562 // We need double spill code if this block has interference.
563 Intf.moveToBlock(Number);
564 if (Intf.hasInterference())
565 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
566 continue;
567 }
568 // live-in / stack-out or stack-in live-out.
569 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000570 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000571 return GlobalCost;
572}
573
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000574/// splitAroundRegion - Split VirtReg around the region determined by
575/// LiveBundles. Make an effort to avoid interference from PhysReg.
576///
577/// The 'register' interval is going to contain as many uses as possible while
578/// avoiding interference. The 'stack' interval is the complement constructed by
579/// SplitEditor. It will contain the rest.
580///
581void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
582 const BitVector &LiveBundles,
583 SmallVectorImpl<LiveInterval*> &NewVRegs) {
584 DEBUG({
585 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
586 << " with bundles";
587 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
588 dbgs() << " EB#" << i;
589 dbgs() << ".\n";
590 });
591
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000592 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000593 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000594 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000595
596 // Create the main cross-block interval.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000597 SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000598
599 // First add all defs that are live out of a block.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000600 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
601 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
602 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000603 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
604 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
605
606 // Should the register be live out?
607 if (!BI.LiveOut || !RegOut)
608 continue;
609
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000610 SlotIndex Start, Stop;
611 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000612 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000613 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000614 << Bundles->getBundle(BI.MBB->getNumber(), 1)
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000615 << " [" << Start << ';'
616 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
617 << ") intf [" << Intf.first() << ';' << Intf.last() << ')');
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000618
619 // The interference interval should either be invalid or overlap MBB.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000620 assert((!Intf.hasInterference() || Intf.first() < Stop)
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000621 && "Bad interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000622 assert((!Intf.hasInterference() || Intf.last() > Start)
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000623 && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000624
625 // Check interference leaving the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000626 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000627 // Block is interference-free.
628 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000629 if (!BI.LiveThrough) {
630 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000631 SE->useIntv(SE->enterIntvBefore(BI.Def), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000632 continue;
633 }
634 if (!RegIn) {
635 // Block is live-through, but entry bundle is on the stack.
636 // Reload just before the first use.
637 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000638 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000639 continue;
640 }
641 DEBUG(dbgs() << ", live-through.\n");
642 continue;
643 }
644
645 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000646 DEBUG(dbgs() << ", interference to " << Intf.last());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000647
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000648 if (!BI.LiveThrough && Intf.last() <= BI.Def) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000649 // The interference doesn't reach the outgoing segment.
650 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000651 SE->useIntv(BI.Def, Stop);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000652 continue;
653 }
654
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000655 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000656 if (Intf.last().getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000657 // There are interference-free uses at the end of the block.
658 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000659 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000660 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000661 Intf.last().getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000662 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
663 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000664 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000665 // Only attempt a split befroe the last split point.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000666 if (Use.getBaseIndex() <= LastSplitPoint) {
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000667 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000668 SlotIndex SegStart = SE->enterIntvBefore(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000669 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000670 assert(SegStart < LastSplitPoint && "Impossible split point");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000671 SE->useIntv(SegStart, Stop);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000672 continue;
673 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000674 }
675
676 // Interference is after the last use.
677 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000678 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000679 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000680 }
681
682 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000683 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
684 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000685 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
686 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
687
688 // Is the register live-in?
689 if (!BI.LiveIn || !RegIn)
690 continue;
691
692 // We have an incoming register. Check for interference.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000693 SlotIndex Start, Stop;
694 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000695 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000696 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000697 << " -> BB#" << BI.MBB->getNumber() << " [" << Start << ';'
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000698 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
699 << ')');
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000700
701 // Check interference entering the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000702 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000703 // Block is interference-free.
704 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000705 if (!BI.LiveThrough) {
706 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000707 SE->useIntv(Start, SE->leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000708 continue;
709 }
710 if (!RegOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000711 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000712 // Block is live-through, but exit bundle is on the stack.
713 // Spill immediately after the last use.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000714 if (BI.LastUse < LastSplitPoint) {
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000715 DEBUG(dbgs() << ", uses, stack-out.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000716 SE->useIntv(Start, SE->leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000717 continue;
718 }
719 // The last use is after the last split point, it is probably an
720 // indirect jump.
721 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000722 << LastSplitPoint << ", stack-out.\n");
723 SlotIndex SegEnd = SE->leaveIntvBefore(LastSplitPoint);
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000724 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000725 // Run a double interval from the split to the last use.
726 // This makes it possible to spill the complement without affecting the
727 // indirect branch.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000728 SE->overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000729 continue;
730 }
731 // Register is live-through.
732 DEBUG(dbgs() << ", uses, live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000733 SE->useIntv(Start, Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000734 continue;
735 }
736
737 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000738 DEBUG(dbgs() << ", interference from " << Intf.first());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000739
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000740 if (!BI.LiveThrough && Intf.first() >= BI.Kill) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000741 // The interference doesn't reach the outgoing segment.
742 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000743 SE->useIntv(Start, BI.Kill);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000744 continue;
745 }
746
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000747 if (Intf.first().getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000748 // There are interference-free uses at the beginning of the block.
749 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000750 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000751 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000752 Intf.first().getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000753 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
754 SlotIndex Use = (--UI)->getBoundaryIndex();
755 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000756 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000757 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000758 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000759 continue;
760 }
761
762 // Interference is before the first use.
763 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000764 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000765 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000766 }
767
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000768 // Handle live-through blocks.
769 ArrayRef<unsigned> ThroughBlocks = SA->getThroughBlocks();
770 for (unsigned i = 0; i != ThroughBlocks.size(); ++i) {
771 unsigned Number = ThroughBlocks[i];
772 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
773 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
774 DEBUG(dbgs() << "Live through BB#" << Number << '\n');
775 if (RegIn && RegOut) {
776 Intf.moveToBlock(Number);
777 if (!Intf.hasInterference()) {
778 SE->useIntv(Indexes->getMBBStartIdx(Number),
779 Indexes->getMBBEndIdx(Number));
780 continue;
781 }
782 }
783 MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
784 if (RegIn)
785 SE->leaveIntvAtTop(*MBB);
786 if (RegOut)
787 SE->enterIntvAtEnd(*MBB);
788 }
789
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000790 SE->closeIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000791
792 // FIXME: Should we be more aggressive about splitting the stack region into
793 // per-block segments? The current approach allows the stack region to
794 // separate into connected components. Some components may be allocatable.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000795 SE->finish();
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000796 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000797
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000798 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000799 MF->verify(this, "After splitting live range around region");
800}
801
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000802unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
803 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000804 BitVector LiveBundles, BestBundles;
805 float BestCost = 0;
806 unsigned BestReg = 0;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000807
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000808 Order.rewind();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000809 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
810 if (GlobalCand.size() <= Cand)
811 GlobalCand.resize(Cand+1);
812 GlobalCand[Cand].PhysReg = PhysReg;
813
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000814 SpillPlacer->prepare(LiveBundles);
815 float Cost;
816 if (!addSplitConstraints(PhysReg, Cost)) {
817 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bias\n");
818 continue;
819 }
820 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tbiased = "
821 << SpillPlacer->getPositiveNodes() << ", static = " << Cost);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000822 if (BestReg && Cost >= BestCost) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000823 DEBUG(dbgs() << " worse than " << PrintReg(BestReg, TRI) << '\n');
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000824 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000825 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000826
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000827 SpillPlacer->finish();
828
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000829 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000830 if (!LiveBundles.any()) {
831 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000832 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000833 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000834
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000835 Cost += calcGlobalSplitCost(PhysReg, LiveBundles);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000836 DEBUG({
837 dbgs() << ", total = " << Cost << " with bundles";
838 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
839 dbgs() << " EB#" << i;
840 dbgs() << ".\n";
841 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000842 if (!BestReg || Cost < BestCost) {
843 BestReg = PhysReg;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000844 BestCost = 0.98f * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000845 BestBundles.swap(LiveBundles);
846 }
847 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000848
849 if (!BestReg)
850 return 0;
851
852 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000853 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000854 return 0;
855}
856
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000857
858//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000859// Local Splitting
860//===----------------------------------------------------------------------===//
861
862
863/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
864/// in order to use PhysReg between two entries in SA->UseSlots.
865///
866/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
867///
868void RAGreedy::calcGapWeights(unsigned PhysReg,
869 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000870 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
871 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000872 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
873 const unsigned NumGaps = Uses.size()-1;
874
875 // Start and end points for the interference check.
876 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
877 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
878
879 GapWeight.assign(NumGaps, 0.0f);
880
881 // Add interference from each overlapping register.
882 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
883 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
884 .checkInterference())
885 continue;
886
887 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
888 // so we don't need InterferenceQuery.
889 //
890 // Interference that overlaps an instruction is counted in both gaps
891 // surrounding the instruction. The exception is interference before
892 // StartIdx and after StopIdx.
893 //
894 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
895 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
896 // Skip the gaps before IntI.
897 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
898 if (++Gap == NumGaps)
899 break;
900 if (Gap == NumGaps)
901 break;
902
903 // Update the gaps covered by IntI.
904 const float weight = IntI.value()->weight;
905 for (; Gap != NumGaps; ++Gap) {
906 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
907 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
908 break;
909 }
910 if (Gap == NumGaps)
911 break;
912 }
913 }
914}
915
916/// getPrevMappedIndex - Return the slot index of the last non-copy instruction
917/// before MI that has a slot index. If MI is the first mapped instruction in
918/// its block, return the block start index instead.
919///
920SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
921 assert(MI && "Missing MachineInstr");
922 const MachineBasicBlock *MBB = MI->getParent();
923 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
924 while (I != B)
925 if (!(--I)->isDebugValue() && !I->isCopy())
926 return Indexes->getInstructionIndex(I);
927 return Indexes->getMBBStartIdx(MBB);
928}
929
930/// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
931/// real non-copy instruction for each instruction in SA->UseSlots.
932///
933void RAGreedy::calcPrevSlots() {
934 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
935 PrevSlot.clear();
936 PrevSlot.reserve(Uses.size());
937 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
938 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
939 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
940 }
941}
942
943/// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
944/// be beneficial to split before UseSlots[i].
945///
946/// 0 is always a valid split point
947unsigned RAGreedy::nextSplitPoint(unsigned i) {
948 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
949 const unsigned Size = Uses.size();
950 assert(i != Size && "No split points after the end");
951 // Allow split before i when Uses[i] is not adjacent to the previous use.
952 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
953 ;
954 return i;
955}
956
957/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
958/// basic block.
959///
960unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
961 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000962 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
963 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000964
965 // Note that it is possible to have an interval that is live-in or live-out
966 // while only covering a single block - A phi-def can use undef values from
967 // predecessors, and the block could be a single-block loop.
968 // We don't bother doing anything clever about such a case, we simply assume
969 // that the interval is continuous from FirstUse to LastUse. We should make
970 // sure that we don't do anything illegal to such an interval, though.
971
972 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
973 if (Uses.size() <= 2)
974 return 0;
975 const unsigned NumGaps = Uses.size()-1;
976
977 DEBUG({
978 dbgs() << "tryLocalSplit: ";
979 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
980 dbgs() << ' ' << SA->UseSlots[i];
981 dbgs() << '\n';
982 });
983
984 // For every use, find the previous mapped non-copy instruction.
985 // We use this to detect valid split points, and to estimate new interval
986 // sizes.
987 calcPrevSlots();
988
989 unsigned BestBefore = NumGaps;
990 unsigned BestAfter = 0;
991 float BestDiff = 0;
992
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +0000993 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000994 SmallVector<float, 8> GapWeight;
995
996 Order.rewind();
997 while (unsigned PhysReg = Order.next()) {
998 // Keep track of the largest spill weight that would need to be evicted in
999 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1000 calcGapWeights(PhysReg, GapWeight);
1001
1002 // Try to find the best sequence of gaps to close.
1003 // The new spill weight must be larger than any gap interference.
1004
1005 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1006 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
1007
1008 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1009 // It is the spill weight that needs to be evicted.
1010 float MaxGap = GapWeight[0];
1011 for (unsigned i = 1; i != SplitAfter; ++i)
1012 MaxGap = std::max(MaxGap, GapWeight[i]);
1013
1014 for (;;) {
1015 // Live before/after split?
1016 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1017 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1018
1019 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1020 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1021 << " i=" << MaxGap);
1022
1023 // Stop before the interval gets so big we wouldn't be making progress.
1024 if (!LiveBefore && !LiveAfter) {
1025 DEBUG(dbgs() << " all\n");
1026 break;
1027 }
1028 // Should the interval be extended or shrunk?
1029 bool Shrink = true;
1030 if (MaxGap < HUGE_VALF) {
1031 // Estimate the new spill weight.
1032 //
1033 // Each instruction reads and writes the register, except the first
1034 // instr doesn't read when !FirstLive, and the last instr doesn't write
1035 // when !LastLive.
1036 //
1037 // We will be inserting copies before and after, so the total number of
1038 // reads and writes is 2 * EstUses.
1039 //
1040 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1041 2*(LiveBefore + LiveAfter);
1042
1043 // Try to guess the size of the new interval. This should be trivial,
1044 // but the slot index of an inserted copy can be a lot smaller than the
1045 // instruction it is inserted before if there are many dead indexes
1046 // between them.
1047 //
1048 // We measure the distance from the instruction before SplitBefore to
1049 // get a conservative estimate.
1050 //
1051 // The final distance can still be different if inserting copies
1052 // triggers a slot index renumbering.
1053 //
1054 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1055 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1056 // Would this split be possible to allocate?
1057 // Never allocate all gaps, we wouldn't be making progress.
1058 float Diff = EstWeight - MaxGap;
1059 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1060 if (Diff > 0) {
1061 Shrink = false;
1062 if (Diff > BestDiff) {
1063 DEBUG(dbgs() << " (best)");
1064 BestDiff = Diff;
1065 BestBefore = SplitBefore;
1066 BestAfter = SplitAfter;
1067 }
1068 }
1069 }
1070
1071 // Try to shrink.
1072 if (Shrink) {
1073 SplitBefore = nextSplitPoint(SplitBefore);
1074 if (SplitBefore < SplitAfter) {
1075 DEBUG(dbgs() << " shrink\n");
1076 // Recompute the max when necessary.
1077 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1078 MaxGap = GapWeight[SplitBefore];
1079 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1080 MaxGap = std::max(MaxGap, GapWeight[i]);
1081 }
1082 continue;
1083 }
1084 MaxGap = 0;
1085 }
1086
1087 // Try to extend the interval.
1088 if (SplitAfter >= NumGaps) {
1089 DEBUG(dbgs() << " end\n");
1090 break;
1091 }
1092
1093 DEBUG(dbgs() << " extend\n");
1094 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1095 SplitAfter != e; ++SplitAfter)
1096 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1097 continue;
1098 }
1099 }
1100
1101 // Didn't find any candidates?
1102 if (BestBefore == NumGaps)
1103 return 0;
1104
1105 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1106 << '-' << Uses[BestAfter] << ", " << BestDiff
1107 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1108
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001109 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001110 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001111
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001112 SE->openIntv();
1113 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1114 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1115 SE->useIntv(SegStart, SegStop);
1116 SE->closeIntv();
1117 SE->finish();
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001118 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001119 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001120
1121 return 0;
1122}
1123
1124//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001125// Live Range Splitting
1126//===----------------------------------------------------------------------===//
1127
1128/// trySplit - Try to split VirtReg or one of its interferences, making it
1129/// assignable.
1130/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1131unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1132 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001133 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001134 if (LIS->intervalIsInOneMBB(VirtReg)) {
1135 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001136 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001137 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001138 }
1139
1140 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001141
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001142 // Don't iterate global splitting.
1143 // Move straight to spilling if this range was produced by a global split.
1144 LiveRangeStage Stage = getStage(VirtReg);
1145 if (Stage >= RS_Block)
1146 return 0;
1147
1148 SA->analyze(&VirtReg);
1149
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001150 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001151 if (Stage < RS_Region) {
1152 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1153 if (PhysReg || !NewVRegs.empty())
1154 return PhysReg;
1155 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001156
1157 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001158 if (Stage < RS_Block) {
1159 SplitAnalysis::BlockPtrSet Blocks;
1160 if (SA->getMultiUseBlocks(Blocks)) {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001161 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001162 SE->reset(LREdit);
1163 SE->splitSingleBlocks(Blocks);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001164 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1165 if (VerifyEnabled)
1166 MF->verify(this, "After splitting live range around basic blocks");
1167 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001168 }
1169
1170 // Don't assign any physregs.
1171 return 0;
1172}
1173
1174
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001175//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001176// Main Entry Point
1177//===----------------------------------------------------------------------===//
1178
1179unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001180 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001181 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001182 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1183 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001184 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001185 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001186 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00001187
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +00001188 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001189 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001190
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001191 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1192
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001193 // The first time we see a live range, don't try to split or spill.
1194 // Wait until the second time, when all smaller ranges have been allocated.
1195 // This gives a better picture of the interference to split around.
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001196 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +00001197 if (Stage == RS_First) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001198 LRStage[VirtReg.reg] = RS_Second;
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001199 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001200 NewVRegs.push_back(&VirtReg);
1201 return 0;
1202 }
1203
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001204 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1205
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001206 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001207 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1208 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001209 return PhysReg;
1210
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001211 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001212 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001213 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1214 spiller().spill(LRE);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001215 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001216
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001217 if (VerifyEnabled)
1218 MF->verify(this, "After spilling");
1219
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001220 // The live virtual register requesting allocation was spilled, so tell
1221 // the caller not to allocate anything during this round.
1222 return 0;
1223}
1224
1225bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1226 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1227 << "********** Function: "
1228 << ((Value*)mf.getFunction())->getName() << '\n');
1229
1230 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001231 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001232 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001233
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001234 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001235 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001236 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001237 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001238 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001239 Loops = &getAnalysis<MachineLoopInfo>();
1240 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001241 Bundles = &getAnalysis<EdgeBundles>();
1242 SpillPlacer = &getAnalysis<SpillPlacement>();
1243
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001244 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001245 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001246 LRStage.clear();
1247 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001248 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001249
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001250 allocatePhysRegs();
1251 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001252 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001253
1254 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001255 {
1256 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001257 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001258 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001259
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001260 // Write out new DBG_VALUE instructions.
1261 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
1262
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001263 // The pass output is in VirtRegMap. Release all the transient data.
1264 releaseMemory();
1265
1266 return true;
1267}