blob: 57119aacd2be1c8a49304c363b95c31dcc22f841 [file] [log] [blame]
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001//===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the RAGreedy function pass for register allocation in
11// optimized builds.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000016#include "AllocationOrder.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000017#include "LiveIntervalUnion.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000018#include "LiveRangeEdit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000019#include "RegAllocBase.h"
20#include "Spiller.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000022#include "SplitKit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000023#include "VirtRegMap.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000025#include "llvm/Analysis/AliasAnalysis.h"
26#include "llvm/Function.h"
27#include "llvm/PassAnalysisSupport.h"
28#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000029#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000030#include "llvm/CodeGen/LiveIntervalAnalysis.h"
31#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000032#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000035#include "llvm/CodeGen/MachineLoopRanges.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/Passes.h"
38#include "llvm/CodeGen/RegAllocRegistry.h"
39#include "llvm/CodeGen/RegisterCoalescer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000040#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000044#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000045
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000046#include <queue>
47
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000048using namespace llvm;
49
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000050STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51STATISTIC(NumLocalSplits, "Number of split local live ranges");
52STATISTIC(NumReassigned, "Number of interferences reassigned");
53STATISTIC(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 {
94 RS_Original, ///< Never seen before, never split.
95 RS_Second, ///< Second time in the queue.
96 RS_Region, ///< Produced by region splitting.
97 RS_Block, ///< Produced by per-block splitting.
98 RS_Local, ///< Produced by local splitting.
99 RS_Spill ///< Produced by spilling.
100 };
101
102 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
103
104 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
105 return LiveRangeStage(LRStage[VirtReg.reg]);
106 }
107
108 template<typename Iterator>
109 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
110 LRStage.resize(MRI->getNumVirtRegs());
111 for (;Begin != End; ++Begin)
112 LRStage[(*Begin)->reg] = NewStage;
113 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000114
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000115 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000116 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000117 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000118
119 /// All basic blocks where the current register is live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000120 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000121
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000122 typedef std::pair<SlotIndex, SlotIndex> IndexPair;
123
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000124 /// Global live range splitting candidate info.
125 struct GlobalSplitCandidate {
126 unsigned PhysReg;
127 SmallVector<IndexPair, 8> Interference;
128 BitVector LiveBundles;
129 };
130
131 /// Candidate info for for each PhysReg in AllocationOrder.
132 /// This vector never shrinks, but grows to the size of the largest register
133 /// class.
134 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
135
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000136 /// For every instruction in SA->UseSlots, store the previous non-copy
137 /// instruction.
138 SmallVector<SlotIndex, 8> PrevSlot;
139
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000140public:
141 RAGreedy();
142
143 /// Return the pass name.
144 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000145 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000146 }
147
148 /// RAGreedy analysis usage.
149 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000150 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000151 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000152 virtual void enqueue(LiveInterval *LI);
153 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000154 virtual unsigned selectOrSplit(LiveInterval&,
155 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000156
157 /// Perform register allocation.
158 virtual bool runOnMachineFunction(MachineFunction &mf);
159
160 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000161
162private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000163 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000164 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000165
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000166 bool checkUncachedInterference(LiveInterval&, unsigned);
167 LiveInterval *getSingleInterference(LiveInterval&, unsigned);
Andrew Trickb853e6c2010-12-09 18:15:21 +0000168 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000169
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000170 void mapGlobalInterference(unsigned, SmallVectorImpl<IndexPair>&);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000171 float calcSplitConstraints(const SmallVectorImpl<IndexPair>&);
172
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000173 float calcGlobalSplitCost(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 tryReassign(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000183 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000184 unsigned tryEvict(LiveInterval&, AllocationOrder&,
185 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000186 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
187 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000188 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
189 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000190 unsigned trySplit(LiveInterval&, AllocationOrder&,
191 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000192};
193} // end anonymous namespace
194
195char RAGreedy::ID = 0;
196
197FunctionPass* llvm::createGreedyRegisterAllocator() {
198 return new RAGreedy();
199}
200
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000201RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_Original) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000202 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000203 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
204 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
205 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
206 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
207 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
208 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
209 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
210 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000211 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000212 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000213 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
214 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000215}
216
217void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
218 AU.setPreservesCFG();
219 AU.addRequired<AliasAnalysis>();
220 AU.addPreserved<AliasAnalysis>();
221 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000222 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000223 AU.addPreserved<SlotIndexes>();
224 if (StrongPHIElim)
225 AU.addRequiredID(StrongPHIEliminationID);
226 AU.addRequiredTransitive<RegisterCoalescer>();
227 AU.addRequired<CalculateSpillWeights>();
228 AU.addRequired<LiveStacks>();
229 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000230 AU.addRequired<MachineDominatorTree>();
231 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000232 AU.addRequired<MachineLoopInfo>();
233 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000234 AU.addRequired<MachineLoopRanges>();
235 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000236 AU.addRequired<VirtRegMap>();
237 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000238 AU.addRequired<EdgeBundles>();
239 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000240 MachineFunctionPass::getAnalysisUsage(AU);
241}
242
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000243
244//===----------------------------------------------------------------------===//
245// LiveRangeEdit delegate methods
246//===----------------------------------------------------------------------===//
247
248void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
249 // LRE itself will remove from SlotIndexes and parent basic block.
250 VRM->RemoveMachineInstrFromMaps(MI);
251}
252
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000253bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
254 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
255 unassign(LIS->getInterval(VirtReg), PhysReg);
256 return true;
257 }
258 // Unassigned virtreg is probably in the priority queue.
259 // RegAllocBase will erase it after dequeueing.
260 return false;
261}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000262
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000263void RAGreedy::releaseMemory() {
264 SpillerInstance.reset(0);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000265 LRStage.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000266 RegAllocBase::releaseMemory();
267}
268
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000269void RAGreedy::enqueue(LiveInterval *LI) {
270 // Prioritize live ranges by size, assigning larger ranges first.
271 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000272 const unsigned Size = LI->getSize();
273 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000274 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
275 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000276 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000277
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000278 LRStage.grow(Reg);
279 if (LRStage[Reg] == RS_Original)
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000280 // 1st generation ranges are handled first, long -> short.
281 Prio = (1u << 31) + Size;
282 else
283 // Repeat offenders are handled second, short -> long
284 Prio = (1u << 30) - Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000285
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000286 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000287 const unsigned Hint = VRM->getRegAllocPref(Reg);
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000288 if (TargetRegisterInfo::isPhysicalRegister(Hint))
289 Prio |= (1u << 30);
290
291 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000292}
293
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000294LiveInterval *RAGreedy::dequeue() {
295 if (Queue.empty())
296 return 0;
297 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
298 Queue.pop();
299 return LI;
300}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000301
302//===----------------------------------------------------------------------===//
303// Register Reassignment
304//===----------------------------------------------------------------------===//
305
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000306// Check interference without using the cache.
307bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
308 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000309 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
310 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000311 if (subQ.checkInterference())
312 return true;
313 }
314 return false;
315}
316
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000317/// getSingleInterference - Return the single interfering virtual register
318/// assigned to PhysReg. Return 0 if more than one virtual register is
319/// interfering.
320LiveInterval *RAGreedy::getSingleInterference(LiveInterval &VirtReg,
321 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000322 // Check physreg and aliases.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000323 LiveInterval *Interference = 0;
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000324 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000325 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
326 if (Q.checkInterference()) {
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000327 if (Interference)
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000328 return 0;
Jakob Stoklund Olesen417df012011-02-23 00:29:55 +0000329 if (Q.collectInterferingVRegs(2) > 1)
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000330 return 0;
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000331 Interference = Q.interferingVRegs().front();
332 }
333 }
334 return Interference;
335}
336
Andrew Trickb853e6c2010-12-09 18:15:21 +0000337// Attempt to reassign this virtual register to a different physical register.
338//
339// FIXME: we are not yet caching these "second-level" interferences discovered
340// in the sub-queries. These interferences can change with each call to
341// selectOrSplit. However, we could implement a "may-interfere" cache that
342// could be conservatively dirtied when we reassign or split.
343//
344// FIXME: This may result in a lot of alias queries. We could summarize alias
345// live intervals in their parent register's live union, but it's messy.
346bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000347 unsigned WantedPhysReg) {
348 assert(TargetRegisterInfo::isVirtualRegister(InterferingVReg.reg) &&
349 "Can only reassign virtual registers");
350 assert(TRI->regsOverlap(WantedPhysReg, VRM->getPhys(InterferingVReg.reg)) &&
Andrew Trickb853e6c2010-12-09 18:15:21 +0000351 "inconsistent phys reg assigment");
352
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000353 AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
354 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000355 // Don't reassign to a WantedPhysReg alias.
356 if (TRI->regsOverlap(PhysReg, WantedPhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000357 continue;
358
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000359 if (checkUncachedInterference(InterferingVReg, PhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000360 continue;
361
Andrew Trickb853e6c2010-12-09 18:15:21 +0000362 // Reassign the interfering virtual reg to this physical reg.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000363 unsigned OldAssign = VRM->getPhys(InterferingVReg.reg);
364 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
365 TRI->getName(OldAssign) << " to " << TRI->getName(PhysReg) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000366 unassign(InterferingVReg, OldAssign);
367 assign(InterferingVReg, PhysReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000368 ++NumReassigned;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000369 return true;
370 }
371 return false;
372}
373
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000374/// tryReassign - Try to reassign a single interference to a different physreg.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000375/// @param VirtReg Currently unassigned virtual register.
376/// @param Order Physregs to try.
377/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000378unsigned RAGreedy::tryReassign(LiveInterval &VirtReg, AllocationOrder &Order,
379 SmallVectorImpl<LiveInterval*> &NewVRegs){
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000380 NamedRegionTimer T("Reassign", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000381
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000382 Order.rewind();
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000383 while (unsigned PhysReg = Order.next()) {
384 LiveInterval *InterferingVReg = getSingleInterference(VirtReg, PhysReg);
385 if (!InterferingVReg)
386 continue;
387 if (TargetRegisterInfo::isPhysicalRegister(InterferingVReg->reg))
388 continue;
389 if (reassignVReg(*InterferingVReg, PhysReg))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000390 return PhysReg;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000391 }
392 return 0;
393}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000394
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000395
396//===----------------------------------------------------------------------===//
397// Interference eviction
398//===----------------------------------------------------------------------===//
399
400/// canEvict - Return true if all interferences between VirtReg and PhysReg can
401/// be evicted. Set maxWeight to the maximal spill weight of an interference.
402bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000403 float &MaxWeight) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000404 float Weight = 0;
405 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
406 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
407 // If there is 10 or more interferences, chances are one is smaller.
408 if (Q.collectInterferingVRegs(10) >= 10)
409 return false;
410
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000411 // Check if any interfering live range is heavier than VirtReg.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000412 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
413 LiveInterval *Intf = Q.interferingVRegs()[i];
414 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
415 return false;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000416 if (Intf->weight >= VirtReg.weight)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000417 return false;
418 Weight = std::max(Weight, Intf->weight);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000419 }
420 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000421 MaxWeight = Weight;
422 return true;
423}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000424
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000425/// tryEvict - Try to evict all interferences for a physreg.
426/// @param VirtReg Currently unassigned virtual register.
427/// @param Order Physregs to try.
428/// @return Physreg to assign VirtReg, or 0.
429unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
430 AllocationOrder &Order,
431 SmallVectorImpl<LiveInterval*> &NewVRegs){
432 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
433
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000434 // Keep track of the lightest single interference seen so far.
435 float BestWeight = 0;
436 unsigned BestPhys = 0;
437
438 Order.rewind();
439 while (unsigned PhysReg = Order.next()) {
440 float Weight = 0;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000441 if (!canEvictInterference(VirtReg, PhysReg, Weight))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000442 continue;
443
444 // This is an eviction candidate.
445 DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
446 << Weight << '\n');
447 if (BestPhys && Weight >= BestWeight)
448 continue;
449
450 // Best so far.
451 BestPhys = PhysReg;
452 BestWeight = Weight;
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000453 // Stop if the hint can be used.
454 if (Order.isHint(PhysReg))
455 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000456 }
457
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000458 if (!BestPhys)
459 return 0;
460
461 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
462 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
463 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
464 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
465 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
466 LiveInterval *Intf = Q.interferingVRegs()[i];
467 unassign(*Intf, VRM->getPhys(Intf->reg));
468 ++NumEvicted;
469 NewVRegs.push_back(Intf);
470 }
471 }
472 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000473}
474
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000475
476//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000477// Region Splitting
478//===----------------------------------------------------------------------===//
479
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000480/// mapGlobalInterference - Compute a map of the interference from PhysReg and
481/// its aliases in each block in SA->LiveBlocks.
482/// If LiveBlocks[i] is live-in, Ranges[i].first is the first interference.
483/// If LiveBlocks[i] is live-out, Ranges[i].second is the last interference.
484void RAGreedy::mapGlobalInterference(unsigned PhysReg,
485 SmallVectorImpl<IndexPair> &Ranges) {
486 Ranges.assign(SA->LiveBlocks.size(), IndexPair());
487 LiveInterval &VirtReg = const_cast<LiveInterval&>(SA->getParent());
488 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
489 if (!query(VirtReg, *AI).checkInterference())
490 continue;
491 LiveIntervalUnion::SegmentIter IntI =
492 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
493 if (!IntI.valid())
494 continue;
495 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
496 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
497 IndexPair &IP = Ranges[i];
498
499 // Skip interference-free blocks.
500 if (IntI.start() >= BI.Stop)
501 continue;
502
503 // First interference in block.
504 if (BI.LiveIn) {
505 IntI.advanceTo(BI.Start);
506 if (!IntI.valid())
507 break;
508 if (IntI.start() >= BI.Stop)
509 continue;
510 if (!IP.first.isValid() || IntI.start() < IP.first)
511 IP.first = IntI.start();
512 }
513
514 // Last interference in block.
515 if (BI.LiveOut) {
516 IntI.advanceTo(BI.Stop);
517 if (!IntI.valid() || IntI.start() >= BI.Stop)
518 --IntI;
519 if (IntI.stop() <= BI.Start)
520 continue;
521 if (!IP.second.isValid() || IntI.stop() > IP.second)
522 IP.second = IntI.stop();
523 }
524 }
525 }
526}
527
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000528/// calcSplitConstraints - Fill out the SplitConstraints vector based on the
529/// interference pattern in Intf. Return the static cost of this split,
530/// assuming that all preferences in SplitConstraints are met.
531float RAGreedy::calcSplitConstraints(const SmallVectorImpl<IndexPair> &Intf) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000532 // Reset interference dependent info.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000533 SplitConstraints.resize(SA->LiveBlocks.size());
534 float StaticCost = 0;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000535 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
536 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000537 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
538 IndexPair IP = Intf[i];
539
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000540 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000541 BC.Entry = (BI.Uses && BI.LiveIn) ?
542 SpillPlacement::PrefReg : SpillPlacement::DontCare;
543 BC.Exit = (BI.Uses && BI.LiveOut) ?
544 SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000545
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000546 // Number of spill code instructions to insert.
547 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000548
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000549 // Interference for the live-in value.
550 if (IP.first.isValid()) {
551 if (IP.first <= BI.Start)
552 BC.Entry = SpillPlacement::MustSpill, Ins += BI.Uses;
553 else if (!BI.Uses)
554 BC.Entry = SpillPlacement::PrefSpill;
555 else if (IP.first < BI.FirstUse)
556 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
557 else if (IP.first < (BI.LiveThrough ? BI.LastUse : BI.Kill))
558 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000559 }
560
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000561 // Interference for the live-out value.
562 if (IP.second.isValid()) {
563 if (IP.second >= BI.LastSplitPoint)
564 BC.Exit = SpillPlacement::MustSpill, Ins += BI.Uses;
565 else if (!BI.Uses)
566 BC.Exit = SpillPlacement::PrefSpill;
567 else if (IP.second > BI.LastUse)
568 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
569 else if (IP.second > (BI.LiveThrough ? BI.FirstUse : BI.Def))
570 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000571 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000572
573 // Accumulate the total frequency of inserted spill code.
574 if (Ins)
575 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000576 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000577 return StaticCost;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000578}
579
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000580
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000581/// calcGlobalSplitCost - Return the global split cost of following the split
582/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000583/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000584///
585float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
586 float GlobalCost = 0;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000587 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
588 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000589 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000590 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
591 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
592 unsigned Ins = 0;
593
594 if (!BI.Uses)
595 Ins += RegIn != RegOut;
596 else {
597 if (BI.LiveIn)
598 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
599 if (BI.LiveOut)
600 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
601 }
602 if (Ins)
603 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000604 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000605 return GlobalCost;
606}
607
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000608/// splitAroundRegion - Split VirtReg around the region determined by
609/// LiveBundles. Make an effort to avoid interference from PhysReg.
610///
611/// The 'register' interval is going to contain as many uses as possible while
612/// avoiding interference. The 'stack' interval is the complement constructed by
613/// SplitEditor. It will contain the rest.
614///
615void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
616 const BitVector &LiveBundles,
617 SmallVectorImpl<LiveInterval*> &NewVRegs) {
618 DEBUG({
619 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
620 << " with bundles";
621 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
622 dbgs() << " EB#" << i;
623 dbgs() << ".\n";
624 });
625
626 // First compute interference ranges in the live blocks.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000627 SmallVector<IndexPair, 8> InterferenceRanges;
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000628 mapGlobalInterference(PhysReg, InterferenceRanges);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000629
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000630 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000631 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000632
633 // Create the main cross-block interval.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000634 SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000635
636 // First add all defs that are live out of a block.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000637 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
638 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000639 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
640 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
641
642 // Should the register be live out?
643 if (!BI.LiveOut || !RegOut)
644 continue;
645
646 IndexPair &IP = InterferenceRanges[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000647 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000648 << Bundles->getBundle(BI.MBB->getNumber(), 1)
649 << " intf [" << IP.first << ';' << IP.second << ')');
650
651 // The interference interval should either be invalid or overlap MBB.
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000652 assert((!IP.first.isValid() || IP.first < BI.Stop) && "Bad interference");
653 assert((!IP.second.isValid() || IP.second > BI.Start)
654 && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000655
656 // Check interference leaving the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000657 if (!IP.second.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000658 // Block is interference-free.
659 DEBUG(dbgs() << ", no interference");
660 if (!BI.Uses) {
661 assert(BI.LiveThrough && "No uses, but not live through block?");
662 // Block is live-through without interference.
663 DEBUG(dbgs() << ", no uses"
664 << (RegIn ? ", live-through.\n" : ", stack in.\n"));
665 if (!RegIn)
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000666 SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000667 continue;
668 }
669 if (!BI.LiveThrough) {
670 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000671 SE->useIntv(SE->enterIntvBefore(BI.Def), BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000672 continue;
673 }
674 if (!RegIn) {
675 // Block is live-through, but entry bundle is on the stack.
676 // Reload just before the first use.
677 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000678 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000679 continue;
680 }
681 DEBUG(dbgs() << ", live-through.\n");
682 continue;
683 }
684
685 // Block has interference.
686 DEBUG(dbgs() << ", interference to " << IP.second);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000687
688 if (!BI.LiveThrough && IP.second <= BI.Def) {
689 // The interference doesn't reach the outgoing segment.
690 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000691 SE->useIntv(BI.Def, BI.Stop);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000692 continue;
693 }
694
695
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000696 if (!BI.Uses) {
697 // No uses in block, avoid interference by reloading as late as possible.
698 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000699 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000700 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000701 continue;
702 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000703
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000704 if (IP.second.getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000705 // There are interference-free uses at the end of the block.
706 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000707 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000708 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
709 IP.second.getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000710 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
711 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000712 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000713 // Only attempt a split befroe the last split point.
714 if (Use.getBaseIndex() <= BI.LastSplitPoint) {
715 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000716 SlotIndex SegStart = SE->enterIntvBefore(Use);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000717 assert(SegStart >= IP.second && "Couldn't avoid interference");
718 assert(SegStart < BI.LastSplitPoint && "Impossible split point");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000719 SE->useIntv(SegStart, BI.Stop);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000720 continue;
721 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000722 }
723
724 // Interference is after the last use.
725 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000726 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000727 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000728 }
729
730 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000731 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
732 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000733 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
734 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
735
736 // Is the register live-in?
737 if (!BI.LiveIn || !RegIn)
738 continue;
739
740 // We have an incoming register. Check for interference.
741 IndexPair &IP = InterferenceRanges[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000742
743 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
744 << " -> BB#" << BI.MBB->getNumber());
745
746 // Check interference entering the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000747 if (!IP.first.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000748 // Block is interference-free.
749 DEBUG(dbgs() << ", no interference");
750 if (!BI.Uses) {
751 assert(BI.LiveThrough && "No uses, but not live through block?");
752 // Block is live-through without interference.
753 if (RegOut) {
754 DEBUG(dbgs() << ", no uses, live-through.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000755 SE->useIntv(BI.Start, BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000756 } else {
757 DEBUG(dbgs() << ", no uses, stack-out.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000758 SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000759 }
760 continue;
761 }
762 if (!BI.LiveThrough) {
763 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000764 SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000765 continue;
766 }
767 if (!RegOut) {
768 // Block is live-through, but exit bundle is on the stack.
769 // Spill immediately after the last use.
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000770 if (BI.LastUse < BI.LastSplitPoint) {
771 DEBUG(dbgs() << ", uses, stack-out.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000772 SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000773 continue;
774 }
775 // The last use is after the last split point, it is probably an
776 // indirect jump.
777 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
778 << BI.LastSplitPoint << ", stack-out.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000779 SlotIndex SegEnd = SE->leaveIntvBefore(BI.LastSplitPoint);
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000780 SE->useIntv(BI.Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000781 // Run a double interval from the split to the last use.
782 // This makes it possible to spill the complement without affecting the
783 // indirect branch.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000784 SE->overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000785 continue;
786 }
787 // Register is live-through.
788 DEBUG(dbgs() << ", uses, live-through.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000789 SE->useIntv(BI.Start, BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000790 continue;
791 }
792
793 // Block has interference.
794 DEBUG(dbgs() << ", interference from " << IP.first);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000795
796 if (!BI.LiveThrough && IP.first >= BI.Kill) {
797 // The interference doesn't reach the outgoing segment.
798 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000799 SE->useIntv(BI.Start, BI.Kill);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000800 continue;
801 }
802
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000803 if (!BI.Uses) {
804 // No uses in block, avoid interference by spilling as soon as possible.
805 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000806 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000807 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000808 continue;
809 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000810 if (IP.first.getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000811 // There are interference-free uses at the beginning of the block.
812 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000813 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000814 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
815 IP.first.getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000816 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
817 SlotIndex Use = (--UI)->getBoundaryIndex();
818 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000819 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000820 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000821 SE->useIntv(BI.Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000822 continue;
823 }
824
825 // Interference is before the first use.
826 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000827 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000828 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000829 }
830
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000831 SE->closeIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000832
833 // FIXME: Should we be more aggressive about splitting the stack region into
834 // per-block segments? The current approach allows the stack region to
835 // separate into connected components. Some components may be allocatable.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000836 SE->finish();
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000837 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000838
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000839 if (VerifyEnabled) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000840 MF->verify(this, "After splitting live range around region");
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000841
842#ifndef NDEBUG
843 // Make sure that at least one of the new intervals can allocate to PhysReg.
844 // That was the whole point of splitting the live range.
845 bool found = false;
846 for (LiveRangeEdit::iterator I = LREdit.begin(), E = LREdit.end(); I != E;
847 ++I)
848 if (!checkUncachedInterference(**I, PhysReg)) {
849 found = true;
850 break;
851 }
852 assert(found && "No allocatable intervals after pointless splitting");
853#endif
854 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000855}
856
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000857unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
858 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000859 BitVector LiveBundles, BestBundles;
860 float BestCost = 0;
861 unsigned BestReg = 0;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000862
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000863 Order.rewind();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000864 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
865 if (GlobalCand.size() <= Cand)
866 GlobalCand.resize(Cand+1);
867 GlobalCand[Cand].PhysReg = PhysReg;
868
869 mapGlobalInterference(PhysReg, GlobalCand[Cand].Interference);
870 float Cost = calcSplitConstraints(GlobalCand[Cand].Interference);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000871 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
872 if (BestReg && Cost >= BestCost) {
873 DEBUG(dbgs() << " higher.\n");
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000874 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000875 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000876
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000877 SpillPlacer->placeSpills(SplitConstraints, LiveBundles);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000878 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000879 if (!LiveBundles.any()) {
880 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000881 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000882 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000883
884 Cost += calcGlobalSplitCost(LiveBundles);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000885 DEBUG({
886 dbgs() << ", total = " << Cost << " with bundles";
887 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
888 dbgs() << " EB#" << i;
889 dbgs() << ".\n";
890 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000891 if (!BestReg || Cost < BestCost) {
892 BestReg = PhysReg;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000893 BestCost = 0.98f * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000894 BestBundles.swap(LiveBundles);
895 }
896 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000897
898 if (!BestReg)
899 return 0;
900
901 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000902 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000903 return 0;
904}
905
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000906
907//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000908// Local Splitting
909//===----------------------------------------------------------------------===//
910
911
912/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
913/// in order to use PhysReg between two entries in SA->UseSlots.
914///
915/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
916///
917void RAGreedy::calcGapWeights(unsigned PhysReg,
918 SmallVectorImpl<float> &GapWeight) {
919 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
920 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
921 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
922 const unsigned NumGaps = Uses.size()-1;
923
924 // Start and end points for the interference check.
925 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
926 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
927
928 GapWeight.assign(NumGaps, 0.0f);
929
930 // Add interference from each overlapping register.
931 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
932 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
933 .checkInterference())
934 continue;
935
936 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
937 // so we don't need InterferenceQuery.
938 //
939 // Interference that overlaps an instruction is counted in both gaps
940 // surrounding the instruction. The exception is interference before
941 // StartIdx and after StopIdx.
942 //
943 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
944 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
945 // Skip the gaps before IntI.
946 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
947 if (++Gap == NumGaps)
948 break;
949 if (Gap == NumGaps)
950 break;
951
952 // Update the gaps covered by IntI.
953 const float weight = IntI.value()->weight;
954 for (; Gap != NumGaps; ++Gap) {
955 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
956 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
957 break;
958 }
959 if (Gap == NumGaps)
960 break;
961 }
962 }
963}
964
965/// getPrevMappedIndex - Return the slot index of the last non-copy instruction
966/// before MI that has a slot index. If MI is the first mapped instruction in
967/// its block, return the block start index instead.
968///
969SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
970 assert(MI && "Missing MachineInstr");
971 const MachineBasicBlock *MBB = MI->getParent();
972 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
973 while (I != B)
974 if (!(--I)->isDebugValue() && !I->isCopy())
975 return Indexes->getInstructionIndex(I);
976 return Indexes->getMBBStartIdx(MBB);
977}
978
979/// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
980/// real non-copy instruction for each instruction in SA->UseSlots.
981///
982void RAGreedy::calcPrevSlots() {
983 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
984 PrevSlot.clear();
985 PrevSlot.reserve(Uses.size());
986 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
987 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
988 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
989 }
990}
991
992/// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
993/// be beneficial to split before UseSlots[i].
994///
995/// 0 is always a valid split point
996unsigned RAGreedy::nextSplitPoint(unsigned i) {
997 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
998 const unsigned Size = Uses.size();
999 assert(i != Size && "No split points after the end");
1000 // Allow split before i when Uses[i] is not adjacent to the previous use.
1001 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
1002 ;
1003 return i;
1004}
1005
1006/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1007/// basic block.
1008///
1009unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1010 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1011 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
1012 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
1013
1014 // Note that it is possible to have an interval that is live-in or live-out
1015 // while only covering a single block - A phi-def can use undef values from
1016 // predecessors, and the block could be a single-block loop.
1017 // We don't bother doing anything clever about such a case, we simply assume
1018 // that the interval is continuous from FirstUse to LastUse. We should make
1019 // sure that we don't do anything illegal to such an interval, though.
1020
1021 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1022 if (Uses.size() <= 2)
1023 return 0;
1024 const unsigned NumGaps = Uses.size()-1;
1025
1026 DEBUG({
1027 dbgs() << "tryLocalSplit: ";
1028 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1029 dbgs() << ' ' << SA->UseSlots[i];
1030 dbgs() << '\n';
1031 });
1032
1033 // For every use, find the previous mapped non-copy instruction.
1034 // We use this to detect valid split points, and to estimate new interval
1035 // sizes.
1036 calcPrevSlots();
1037
1038 unsigned BestBefore = NumGaps;
1039 unsigned BestAfter = 0;
1040 float BestDiff = 0;
1041
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001042 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001043 SmallVector<float, 8> GapWeight;
1044
1045 Order.rewind();
1046 while (unsigned PhysReg = Order.next()) {
1047 // Keep track of the largest spill weight that would need to be evicted in
1048 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1049 calcGapWeights(PhysReg, GapWeight);
1050
1051 // Try to find the best sequence of gaps to close.
1052 // The new spill weight must be larger than any gap interference.
1053
1054 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1055 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
1056
1057 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1058 // It is the spill weight that needs to be evicted.
1059 float MaxGap = GapWeight[0];
1060 for (unsigned i = 1; i != SplitAfter; ++i)
1061 MaxGap = std::max(MaxGap, GapWeight[i]);
1062
1063 for (;;) {
1064 // Live before/after split?
1065 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1066 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1067
1068 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1069 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1070 << " i=" << MaxGap);
1071
1072 // Stop before the interval gets so big we wouldn't be making progress.
1073 if (!LiveBefore && !LiveAfter) {
1074 DEBUG(dbgs() << " all\n");
1075 break;
1076 }
1077 // Should the interval be extended or shrunk?
1078 bool Shrink = true;
1079 if (MaxGap < HUGE_VALF) {
1080 // Estimate the new spill weight.
1081 //
1082 // Each instruction reads and writes the register, except the first
1083 // instr doesn't read when !FirstLive, and the last instr doesn't write
1084 // when !LastLive.
1085 //
1086 // We will be inserting copies before and after, so the total number of
1087 // reads and writes is 2 * EstUses.
1088 //
1089 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1090 2*(LiveBefore + LiveAfter);
1091
1092 // Try to guess the size of the new interval. This should be trivial,
1093 // but the slot index of an inserted copy can be a lot smaller than the
1094 // instruction it is inserted before if there are many dead indexes
1095 // between them.
1096 //
1097 // We measure the distance from the instruction before SplitBefore to
1098 // get a conservative estimate.
1099 //
1100 // The final distance can still be different if inserting copies
1101 // triggers a slot index renumbering.
1102 //
1103 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1104 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1105 // Would this split be possible to allocate?
1106 // Never allocate all gaps, we wouldn't be making progress.
1107 float Diff = EstWeight - MaxGap;
1108 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1109 if (Diff > 0) {
1110 Shrink = false;
1111 if (Diff > BestDiff) {
1112 DEBUG(dbgs() << " (best)");
1113 BestDiff = Diff;
1114 BestBefore = SplitBefore;
1115 BestAfter = SplitAfter;
1116 }
1117 }
1118 }
1119
1120 // Try to shrink.
1121 if (Shrink) {
1122 SplitBefore = nextSplitPoint(SplitBefore);
1123 if (SplitBefore < SplitAfter) {
1124 DEBUG(dbgs() << " shrink\n");
1125 // Recompute the max when necessary.
1126 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1127 MaxGap = GapWeight[SplitBefore];
1128 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1129 MaxGap = std::max(MaxGap, GapWeight[i]);
1130 }
1131 continue;
1132 }
1133 MaxGap = 0;
1134 }
1135
1136 // Try to extend the interval.
1137 if (SplitAfter >= NumGaps) {
1138 DEBUG(dbgs() << " end\n");
1139 break;
1140 }
1141
1142 DEBUG(dbgs() << " extend\n");
1143 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1144 SplitAfter != e; ++SplitAfter)
1145 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1146 continue;
1147 }
1148 }
1149
1150 // Didn't find any candidates?
1151 if (BestBefore == NumGaps)
1152 return 0;
1153
1154 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1155 << '-' << Uses[BestAfter] << ", " << BestDiff
1156 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1157
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001158 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001159 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001160
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001161 SE->openIntv();
1162 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1163 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1164 SE->useIntv(SegStart, SegStop);
1165 SE->closeIntv();
1166 SE->finish();
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001167 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001168 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001169
1170 return 0;
1171}
1172
1173//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001174// Live Range Splitting
1175//===----------------------------------------------------------------------===//
1176
1177/// trySplit - Try to split VirtReg or one of its interferences, making it
1178/// assignable.
1179/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1180unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1181 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001182 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001183 if (LIS->intervalIsInOneMBB(VirtReg)) {
1184 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001185 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001186 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001187 }
1188
1189 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001190
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001191 // Don't iterate global splitting.
1192 // Move straight to spilling if this range was produced by a global split.
1193 LiveRangeStage Stage = getStage(VirtReg);
1194 if (Stage >= RS_Block)
1195 return 0;
1196
1197 SA->analyze(&VirtReg);
1198
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001199 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001200 if (Stage < RS_Region) {
1201 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1202 if (PhysReg || !NewVRegs.empty())
1203 return PhysReg;
1204 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001205
1206 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001207 if (Stage < RS_Block) {
1208 SplitAnalysis::BlockPtrSet Blocks;
1209 if (SA->getMultiUseBlocks(Blocks)) {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001210 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001211 SE->reset(LREdit);
1212 SE->splitSingleBlocks(Blocks);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001213 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1214 if (VerifyEnabled)
1215 MF->verify(this, "After splitting live range around basic blocks");
1216 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001217 }
1218
1219 // Don't assign any physregs.
1220 return 0;
1221}
1222
1223
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001224//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001225// Main Entry Point
1226//===----------------------------------------------------------------------===//
1227
1228unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001229 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001230 LiveRangeStage Stage = getStage(VirtReg);
1231 if (Stage == RS_Original)
1232 LRStage[VirtReg.reg] = RS_Second;
1233
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001234 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001235 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1236 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001237 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001238 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001239 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00001240
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +00001241 if (unsigned PhysReg = tryReassign(VirtReg, Order, NewVRegs))
1242 return PhysReg;
1243
1244 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001245 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001246
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001247 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1248
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001249 // The first time we see a live range, don't try to split or spill.
1250 // Wait until the second time, when all smaller ranges have been allocated.
1251 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001252 if (Stage == RS_Original) {
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001253 NewVRegs.push_back(&VirtReg);
1254 return 0;
1255 }
1256
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001257 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1258
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001259 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001260 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1261 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001262 return PhysReg;
1263
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001264 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001265 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001266 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1267 spiller().spill(LRE);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001268
1269 // The live virtual register requesting allocation was spilled, so tell
1270 // the caller not to allocate anything during this round.
1271 return 0;
1272}
1273
1274bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1275 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1276 << "********** Function: "
1277 << ((Value*)mf.getFunction())->getName() << '\n');
1278
1279 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001280 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001281 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001282
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001283 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001284 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001285 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001286 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001287 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001288 Loops = &getAnalysis<MachineLoopInfo>();
1289 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001290 Bundles = &getAnalysis<EdgeBundles>();
1291 SpillPlacer = &getAnalysis<SpillPlacement>();
1292
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001293 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001294 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001295 LRStage.clear();
1296 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001297
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001298 allocatePhysRegs();
1299 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001300 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001301
1302 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001303 {
1304 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001305 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001306 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001307
1308 // The pass output is in VirtRegMap. Release all the transient data.
1309 releaseMemory();
1310
1311 return true;
1312}