blob: 7c2ed3fc4ee094bd22079b68aae8af693372a557 [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 Olesenf4afdfc2011-04-09 02:59:09 +000025#include "llvm/ADT/SparseBitVector.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000026#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000027#include "llvm/Analysis/AliasAnalysis.h"
28#include "llvm/Function.h"
29#include "llvm/PassAnalysisSupport.h"
30#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000031#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000032#include "llvm/CodeGen/LiveIntervalAnalysis.h"
33#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000034#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000036#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000037#include "llvm/CodeGen/MachineLoopRanges.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000038#include "llvm/CodeGen/MachineRegisterInfo.h"
39#include "llvm/CodeGen/Passes.h"
40#include "llvm/CodeGen/RegAllocRegistry.h"
41#include "llvm/CodeGen/RegisterCoalescer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000042#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000046#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000047
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000048#include <queue>
49
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000050using namespace llvm;
51
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000052STATISTIC(NumGlobalSplits, "Number of split global live ranges");
53STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000054STATISTIC(NumEvicted, "Number of interferences evicted");
55
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000056static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
57 createGreedyRegisterAllocator);
58
59namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000060class RAGreedy : public MachineFunctionPass,
61 public RegAllocBase,
62 private LiveRangeEdit::Delegate {
63
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000064 // context
65 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000066 BitVector ReservedRegs;
67
68 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000069 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000070 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000071 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000072 MachineLoopInfo *Loops;
73 MachineLoopRanges *LoopRanges;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000074 EdgeBundles *Bundles;
75 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000076
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000077 // state
78 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000079 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000080
81 // Live ranges pass through a number of stages as we try to allocate them.
82 // Some of the stages may also create new live ranges:
83 //
84 // - Region splitting.
85 // - Per-block splitting.
86 // - Local splitting.
87 // - Spilling.
88 //
89 // Ranges produced by one of the stages skip the previous stages when they are
90 // dequeued. This improves performance because we can skip interference checks
91 // that are unlikely to give any results. It also guarantees that the live
92 // range splitting algorithm terminates, something that is otherwise hard to
93 // ensure.
94 enum LiveRangeStage {
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +000095 RS_New, ///< Never seen before.
96 RS_First, ///< First time in the queue.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000097 RS_Second, ///< Second time in the queue.
98 RS_Region, ///< Produced by region splitting.
99 RS_Block, ///< Produced by per-block splitting.
100 RS_Local, ///< Produced by local splitting.
101 RS_Spill ///< Produced by spilling.
102 };
103
104 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
105
106 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
107 return LiveRangeStage(LRStage[VirtReg.reg]);
108 }
109
110 template<typename Iterator>
111 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
112 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000113 for (;Begin != End; ++Begin) {
114 unsigned Reg = (*Begin)->reg;
115 if (LRStage[Reg] == RS_New)
116 LRStage[Reg] = NewStage;
117 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000118 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000119
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000120 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000121 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000122 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000123
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000124 /// Cached per-block interference maps
125 InterferenceCache IntfCache;
126
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000127 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000128 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000129
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000130 /// Live-through blocks that have already been added to SpillPlacer.
131 SparseBitVector<> ActiveThroughBlocks;
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000132
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 Olesenf4afdfc2011-04-09 02:59:09 +0000176 bool addSplitConstraints(InterferenceCache::Cursor, float&);
177 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
178 void growRegion(InterferenceCache::Cursor);
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000179 float calcGlobalSplitCost(unsigned, const BitVector&);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000180 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
181 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000182 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
183 SlotIndex getPrevMappedIndex(const MachineInstr*);
184 void calcPrevSlots();
185 unsigned nextSplitPoint(unsigned);
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000186 bool canEvictInterference(LiveInterval&, unsigned, float&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000187
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000188 unsigned tryEvict(LiveInterval&, AllocationOrder&,
189 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000190 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
191 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000192 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
193 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000194 unsigned trySplit(LiveInterval&, AllocationOrder&,
195 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000196};
197} // end anonymous namespace
198
199char RAGreedy::ID = 0;
200
201FunctionPass* llvm::createGreedyRegisterAllocator() {
202 return new RAGreedy();
203}
204
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000205RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_New) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000206 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000207 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000208 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
209 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
210 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
211 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
212 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
213 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
214 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
215 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000216 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000217 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000218 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
219 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000220}
221
222void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
223 AU.setPreservesCFG();
224 AU.addRequired<AliasAnalysis>();
225 AU.addPreserved<AliasAnalysis>();
226 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000227 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000228 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000229 AU.addRequired<LiveDebugVariables>();
230 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000231 if (StrongPHIElim)
232 AU.addRequiredID(StrongPHIEliminationID);
233 AU.addRequiredTransitive<RegisterCoalescer>();
234 AU.addRequired<CalculateSpillWeights>();
235 AU.addRequired<LiveStacks>();
236 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000237 AU.addRequired<MachineDominatorTree>();
238 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000239 AU.addRequired<MachineLoopInfo>();
240 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000241 AU.addRequired<MachineLoopRanges>();
242 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000243 AU.addRequired<VirtRegMap>();
244 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000245 AU.addRequired<EdgeBundles>();
246 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000247 MachineFunctionPass::getAnalysisUsage(AU);
248}
249
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000250
251//===----------------------------------------------------------------------===//
252// LiveRangeEdit delegate methods
253//===----------------------------------------------------------------------===//
254
255void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
256 // LRE itself will remove from SlotIndexes and parent basic block.
257 VRM->RemoveMachineInstrFromMaps(MI);
258}
259
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000260bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
261 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
262 unassign(LIS->getInterval(VirtReg), PhysReg);
263 return true;
264 }
265 // Unassigned virtreg is probably in the priority queue.
266 // RegAllocBase will erase it after dequeueing.
267 return false;
268}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000269
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000270void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
271 unsigned PhysReg = VRM->getPhys(VirtReg);
272 if (!PhysReg)
273 return;
274
275 // Register is assigned, put it back on the queue for reassignment.
276 LiveInterval &LI = LIS->getInterval(VirtReg);
277 unassign(LI, PhysReg);
278 enqueue(&LI);
279}
280
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000281void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
282 // LRE may clone a virtual register because dead code elimination causes it to
283 // be split into connected components. Ensure that the new register gets the
284 // same stage as the parent.
285 LRStage.grow(New);
286 LRStage[New] = LRStage[Old];
287}
288
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000289void RAGreedy::releaseMemory() {
290 SpillerInstance.reset(0);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000291 LRStage.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000292 RegAllocBase::releaseMemory();
293}
294
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000295void RAGreedy::enqueue(LiveInterval *LI) {
296 // Prioritize live ranges by size, assigning larger ranges first.
297 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000298 const unsigned Size = LI->getSize();
299 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000300 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
301 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000302 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000303
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000304 LRStage.grow(Reg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000305 if (LRStage[Reg] == RS_New)
306 LRStage[Reg] = RS_First;
307
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000308 if (LRStage[Reg] == RS_Second)
309 // Unsplit ranges that couldn't be allocated immediately are deferred until
310 // everything else has been allocated. Long ranges are allocated last so
311 // they are split against realistic interference.
312 Prio = (1u << 31) - Size;
313 else {
314 // Everything else is allocated in long->short order. Long ranges that don't
315 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000316 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000317
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000318 // Boost ranges that have a physical register hint.
319 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
320 Prio |= (1u << 30);
321 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000322
323 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000324}
325
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000326LiveInterval *RAGreedy::dequeue() {
327 if (Queue.empty())
328 return 0;
329 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
330 Queue.pop();
331 return LI;
332}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000333
334//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000335// Interference eviction
336//===----------------------------------------------------------------------===//
337
338/// canEvict - Return true if all interferences between VirtReg and PhysReg can
339/// be evicted. Set maxWeight to the maximal spill weight of an interference.
340bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000341 float &MaxWeight) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000342 float Weight = 0;
343 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
344 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
345 // If there is 10 or more interferences, chances are one is smaller.
346 if (Q.collectInterferingVRegs(10) >= 10)
347 return false;
348
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000349 // Check if any interfering live range is heavier than VirtReg.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000350 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
351 LiveInterval *Intf = Q.interferingVRegs()[i];
352 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
353 return false;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000354 if (Intf->weight >= VirtReg.weight)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000355 return false;
356 Weight = std::max(Weight, Intf->weight);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000357 }
358 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000359 MaxWeight = Weight;
360 return true;
361}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000362
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000363/// tryEvict - Try to evict all interferences for a physreg.
364/// @param VirtReg Currently unassigned virtual register.
365/// @param Order Physregs to try.
366/// @return Physreg to assign VirtReg, or 0.
367unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
368 AllocationOrder &Order,
369 SmallVectorImpl<LiveInterval*> &NewVRegs){
370 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
371
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000372 // Keep track of the lightest single interference seen so far.
373 float BestWeight = 0;
374 unsigned BestPhys = 0;
375
376 Order.rewind();
377 while (unsigned PhysReg = Order.next()) {
378 float Weight = 0;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000379 if (!canEvictInterference(VirtReg, PhysReg, Weight))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000380 continue;
381
382 // This is an eviction candidate.
383 DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
384 << Weight << '\n');
385 if (BestPhys && Weight >= BestWeight)
386 continue;
387
388 // Best so far.
389 BestPhys = PhysReg;
390 BestWeight = Weight;
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000391 // Stop if the hint can be used.
392 if (Order.isHint(PhysReg))
393 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000394 }
395
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000396 if (!BestPhys)
397 return 0;
398
399 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
400 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
401 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
402 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
403 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
404 LiveInterval *Intf = Q.interferingVRegs()[i];
405 unassign(*Intf, VRM->getPhys(Intf->reg));
406 ++NumEvicted;
407 NewVRegs.push_back(Intf);
408 }
409 }
410 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000411}
412
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000413
414//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000415// Region Splitting
416//===----------------------------------------------------------------------===//
417
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000418/// addSplitConstraints - Fill out the SplitConstraints vector based on the
419/// interference pattern in Physreg and its aliases. Add the constraints to
420/// SpillPlacement and return the static cost of this split in Cost, assuming
421/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000422/// Return false if there are no bundles with positive bias.
423bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
424 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000425 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000426
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000427 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000428 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000429 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000430 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
431 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000432 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000433
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000434 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000435 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000436 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
437 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000438
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000439 if (!Intf.hasInterference())
440 continue;
441
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000442 // Number of spill code instructions to insert.
443 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000444
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000445 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000446 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000447 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000448 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000449 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000450 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000451 else if (Intf.first() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000452 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000453 }
454
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000455 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000456 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000457 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000458 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000459 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000460 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000461 else if (Intf.last() > (BI.LiveThrough ? BI.FirstUse : BI.Def))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000462 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000463 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000464
465 // Accumulate the total frequency of inserted spill code.
466 if (Ins)
467 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000468 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000469 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000470
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000471 // Add constraints for use-blocks. Note that these are the only constraints
472 // that may add a positive bias, it is downhill from here.
473 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000474 return SpillPlacer->scanActiveBundles();
475}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000476
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000477
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000478/// addThroughConstraints - Add constraints and links to SpillPlacer from the
479/// live-through blocks in Blocks.
480void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
481 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000482 const unsigned GroupSize = 8;
483 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000484 unsigned TBS[GroupSize];
485 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000486
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000487 for (unsigned i = 0; i != Blocks.size(); ++i) {
488 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000489 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000490
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000491 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000492 assert(T < GroupSize && "Array overflow");
493 TBS[T] = Number;
494 if (++T == GroupSize) {
495 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
496 T = 0;
497 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000498 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000499 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000500
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000501 assert(B < GroupSize && "Array overflow");
502 BCS[B].Number = Number;
503
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000504 // Interference for the live-in value.
505 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
506 BCS[B].Entry = SpillPlacement::MustSpill;
507 else
508 BCS[B].Entry = SpillPlacement::PrefSpill;
509
510 // Interference for the live-out value.
511 if (Intf.last() >= SA->getLastSplitPoint(Number))
512 BCS[B].Exit = SpillPlacement::MustSpill;
513 else
514 BCS[B].Exit = SpillPlacement::PrefSpill;
515
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000516 if (++B == GroupSize) {
517 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
518 SpillPlacer->addConstraints(Array);
519 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000520 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000521 }
522
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000523 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
524 SpillPlacer->addConstraints(Array);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000525 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000526}
527
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000528void RAGreedy::growRegion(InterferenceCache::Cursor Intf) {
529 // Keep track of through blocks that have already been added to SpillPlacer.
530 SparseBitVector<> Added;
531 SmallVector<unsigned, 16> ThroughBlocks;
532#ifndef NDEBUG
533 unsigned Visited = 0;
534#endif
535 for (;;) {
536 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
537 if (NewBundles.empty())
538 break;
539 // Find new through blocks in the periphery of PrefRegBundles.
540 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
541 unsigned Bundle = NewBundles[i];
542 // Look at all blocks connected to Bundle in the full graph.
543 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
544 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
545 I != E; ++I) {
546 unsigned Block = *I;
547 if (!SA->isThroughBlock(Block) || !Added.test_and_set(Block))
548 continue;
549 // This is a new through block. Add it to SpillPlacer later.
550 ThroughBlocks.push_back(Block);
551#ifndef NDEBUG
552 ++Visited;
553#endif
554 }
555 }
556 // Any new blocks to add?
557 if (!ThroughBlocks.empty()) {
558 addThroughConstraints(Intf, ThroughBlocks);
559 ThroughBlocks.clear();
560 }
561 // Perhaps iterating can enable more bundles?
562 SpillPlacer->iterate();
563 }
564
565 // Rememeber the relevant set of through blocks for splitAroundRegion().
566 ActiveThroughBlocks |= Added;
567 DEBUG(dbgs() << ", v=" << Visited);
568}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000569
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000570/// calcGlobalSplitCost - Return the global split cost of following the split
571/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000572/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000573///
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000574float RAGreedy::calcGlobalSplitCost(unsigned PhysReg,
575 const BitVector &LiveBundles) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000576 float GlobalCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000577 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
578 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
579 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000580 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000581 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
582 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
583 unsigned Ins = 0;
584
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000585 if (BI.LiveIn)
586 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
587 if (BI.LiveOut)
588 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000589 if (Ins)
590 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000591 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000592
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000593 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000594 for (SparseBitVector<>::iterator I = ActiveThroughBlocks.begin(),
595 E = ActiveThroughBlocks.end(); I != E; ++I) {
596 unsigned Number = *I;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000597 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
598 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000599 if (!RegIn && !RegOut)
600 continue;
601 if (RegIn && RegOut) {
602 // We need double spill code if this block has interference.
603 Intf.moveToBlock(Number);
604 if (Intf.hasInterference())
605 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
606 continue;
607 }
608 // live-in / stack-out or stack-in live-out.
609 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000610 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000611 return GlobalCost;
612}
613
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000614/// splitAroundRegion - Split VirtReg around the region determined by
615/// LiveBundles. Make an effort to avoid interference from PhysReg.
616///
617/// The 'register' interval is going to contain as many uses as possible while
618/// avoiding interference. The 'stack' interval is the complement constructed by
619/// SplitEditor. It will contain the rest.
620///
621void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
622 const BitVector &LiveBundles,
623 SmallVectorImpl<LiveInterval*> &NewVRegs) {
624 DEBUG({
625 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
626 << " with bundles";
627 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
628 dbgs() << " EB#" << i;
629 dbgs() << ".\n";
630 });
631
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000632 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000633 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000634 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000635
636 // Create the main cross-block interval.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000637 SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000638
639 // First add all defs that are live out of a block.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000640 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
641 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
642 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000643 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
644 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
645
646 // Should the register be live out?
647 if (!BI.LiveOut || !RegOut)
648 continue;
649
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000650 SlotIndex Start, Stop;
651 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000652 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000653 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000654 << Bundles->getBundle(BI.MBB->getNumber(), 1)
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000655 << " [" << Start << ';'
656 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
657 << ") intf [" << Intf.first() << ';' << Intf.last() << ')');
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000658
659 // The interference interval should either be invalid or overlap MBB.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000660 assert((!Intf.hasInterference() || Intf.first() < Stop)
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000661 && "Bad interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000662 assert((!Intf.hasInterference() || Intf.last() > Start)
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000663 && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000664
665 // Check interference leaving the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000666 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000667 // Block is interference-free.
668 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000669 if (!BI.LiveThrough) {
670 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000671 SE->useIntv(SE->enterIntvBefore(BI.Def), 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 Olesen6c8afd72011-04-04 15:32:15 +0000678 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), 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.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000686 DEBUG(dbgs() << ", interference to " << Intf.last());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000687
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000688 if (!BI.LiveThrough && Intf.last() <= BI.Def) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000689 // The interference doesn't reach the outgoing segment.
690 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000691 SE->useIntv(BI.Def, Stop);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000692 continue;
693 }
694
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000695 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000696 if (Intf.last().getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000697 // There are interference-free uses at the end of the block.
698 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000699 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000700 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000701 Intf.last().getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000702 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
703 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000704 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000705 // Only attempt a split befroe the last split point.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000706 if (Use.getBaseIndex() <= LastSplitPoint) {
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000707 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000708 SlotIndex SegStart = SE->enterIntvBefore(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000709 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000710 assert(SegStart < LastSplitPoint && "Impossible split point");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000711 SE->useIntv(SegStart, Stop);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000712 continue;
713 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000714 }
715
716 // Interference is after the last use.
717 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000718 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000719 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000720 }
721
722 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000723 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
724 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000725 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
726 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
727
728 // Is the register live-in?
729 if (!BI.LiveIn || !RegIn)
730 continue;
731
732 // We have an incoming register. Check for interference.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000733 SlotIndex Start, Stop;
734 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000735 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000736 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000737 << " -> BB#" << BI.MBB->getNumber() << " [" << Start << ';'
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000738 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
739 << ')');
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000740
741 // Check interference entering the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000742 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000743 // Block is interference-free.
744 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000745 if (!BI.LiveThrough) {
746 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000747 SE->useIntv(Start, SE->leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000748 continue;
749 }
750 if (!RegOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000751 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000752 // Block is live-through, but exit bundle is on the stack.
753 // Spill immediately after the last use.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000754 if (BI.LastUse < LastSplitPoint) {
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000755 DEBUG(dbgs() << ", uses, stack-out.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000756 SE->useIntv(Start, SE->leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000757 continue;
758 }
759 // The last use is after the last split point, it is probably an
760 // indirect jump.
761 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000762 << LastSplitPoint << ", stack-out.\n");
763 SlotIndex SegEnd = SE->leaveIntvBefore(LastSplitPoint);
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000764 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000765 // Run a double interval from the split to the last use.
766 // This makes it possible to spill the complement without affecting the
767 // indirect branch.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000768 SE->overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000769 continue;
770 }
771 // Register is live-through.
772 DEBUG(dbgs() << ", uses, live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000773 SE->useIntv(Start, Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000774 continue;
775 }
776
777 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000778 DEBUG(dbgs() << ", interference from " << Intf.first());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000779
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000780 if (!BI.LiveThrough && Intf.first() >= BI.Kill) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000781 // The interference doesn't reach the outgoing segment.
782 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000783 SE->useIntv(Start, BI.Kill);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000784 continue;
785 }
786
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000787 if (Intf.first().getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000788 // There are interference-free uses at the beginning of the block.
789 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000790 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000791 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000792 Intf.first().getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000793 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
794 SlotIndex Use = (--UI)->getBoundaryIndex();
795 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000796 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000797 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000798 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000799 continue;
800 }
801
802 // Interference is before the first use.
803 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000804 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000805 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000806 }
807
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000808 // Handle live-through blocks.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000809 for (SparseBitVector<>::iterator I = ActiveThroughBlocks.begin(),
810 E = ActiveThroughBlocks.end(); I != E; ++I) {
811 unsigned Number = *I;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000812 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
813 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
814 DEBUG(dbgs() << "Live through BB#" << Number << '\n');
815 if (RegIn && RegOut) {
816 Intf.moveToBlock(Number);
817 if (!Intf.hasInterference()) {
818 SE->useIntv(Indexes->getMBBStartIdx(Number),
819 Indexes->getMBBEndIdx(Number));
820 continue;
821 }
822 }
823 MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
824 if (RegIn)
825 SE->leaveIntvAtTop(*MBB);
826 if (RegOut)
827 SE->enterIntvAtEnd(*MBB);
828 }
829
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000830 SE->closeIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000831
832 // FIXME: Should we be more aggressive about splitting the stack region into
833 // per-block segments? The current approach allows the stack region to
834 // separate into connected components. Some components may be allocatable.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000835 SE->finish();
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000836 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000837
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000838 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000839 MF->verify(this, "After splitting live range around region");
840}
841
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000842unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
843 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000844 BitVector LiveBundles, BestBundles;
845 float BestCost = 0;
846 unsigned BestReg = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000847 ActiveThroughBlocks.clear();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000848
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000849 Order.rewind();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000850 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
851 if (GlobalCand.size() <= Cand)
852 GlobalCand.resize(Cand+1);
853 GlobalCand[Cand].PhysReg = PhysReg;
854
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000855 SpillPlacer->prepare(LiveBundles);
856 float Cost;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000857 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
858 if (!addSplitConstraints(Intf, Cost)) {
859 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000860 continue;
861 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000862 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000863 if (BestReg && Cost >= BestCost) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000864 DEBUG(dbgs() << " worse than " << PrintReg(BestReg, TRI) << '\n');
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000865 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000866 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000867 growRegion(Intf);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000868
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000869 SpillPlacer->finish();
870
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000871 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000872 if (!LiveBundles.any()) {
873 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000874 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000875 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000876
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000877 Cost += calcGlobalSplitCost(PhysReg, LiveBundles);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000878 DEBUG({
879 dbgs() << ", total = " << Cost << " with bundles";
880 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
881 dbgs() << " EB#" << i;
882 dbgs() << ".\n";
883 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000884 if (!BestReg || Cost < BestCost) {
885 BestReg = PhysReg;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000886 BestCost = 0.98f * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000887 BestBundles.swap(LiveBundles);
888 }
889 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000890
891 if (!BestReg)
892 return 0;
893
894 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000895 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000896 return 0;
897}
898
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000899
900//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000901// Local Splitting
902//===----------------------------------------------------------------------===//
903
904
905/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
906/// in order to use PhysReg between two entries in SA->UseSlots.
907///
908/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
909///
910void RAGreedy::calcGapWeights(unsigned PhysReg,
911 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000912 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
913 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000914 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
915 const unsigned NumGaps = Uses.size()-1;
916
917 // Start and end points for the interference check.
918 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
919 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
920
921 GapWeight.assign(NumGaps, 0.0f);
922
923 // Add interference from each overlapping register.
924 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
925 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
926 .checkInterference())
927 continue;
928
929 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
930 // so we don't need InterferenceQuery.
931 //
932 // Interference that overlaps an instruction is counted in both gaps
933 // surrounding the instruction. The exception is interference before
934 // StartIdx and after StopIdx.
935 //
936 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
937 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
938 // Skip the gaps before IntI.
939 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
940 if (++Gap == NumGaps)
941 break;
942 if (Gap == NumGaps)
943 break;
944
945 // Update the gaps covered by IntI.
946 const float weight = IntI.value()->weight;
947 for (; Gap != NumGaps; ++Gap) {
948 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
949 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
950 break;
951 }
952 if (Gap == NumGaps)
953 break;
954 }
955 }
956}
957
958/// getPrevMappedIndex - Return the slot index of the last non-copy instruction
959/// before MI that has a slot index. If MI is the first mapped instruction in
960/// its block, return the block start index instead.
961///
962SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
963 assert(MI && "Missing MachineInstr");
964 const MachineBasicBlock *MBB = MI->getParent();
965 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
966 while (I != B)
967 if (!(--I)->isDebugValue() && !I->isCopy())
968 return Indexes->getInstructionIndex(I);
969 return Indexes->getMBBStartIdx(MBB);
970}
971
972/// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
973/// real non-copy instruction for each instruction in SA->UseSlots.
974///
975void RAGreedy::calcPrevSlots() {
976 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
977 PrevSlot.clear();
978 PrevSlot.reserve(Uses.size());
979 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
980 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
981 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
982 }
983}
984
985/// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
986/// be beneficial to split before UseSlots[i].
987///
988/// 0 is always a valid split point
989unsigned RAGreedy::nextSplitPoint(unsigned i) {
990 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
991 const unsigned Size = Uses.size();
992 assert(i != Size && "No split points after the end");
993 // Allow split before i when Uses[i] is not adjacent to the previous use.
994 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
995 ;
996 return i;
997}
998
999/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1000/// basic block.
1001///
1002unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1003 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001004 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1005 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001006
1007 // Note that it is possible to have an interval that is live-in or live-out
1008 // while only covering a single block - A phi-def can use undef values from
1009 // predecessors, and the block could be a single-block loop.
1010 // We don't bother doing anything clever about such a case, we simply assume
1011 // that the interval is continuous from FirstUse to LastUse. We should make
1012 // sure that we don't do anything illegal to such an interval, though.
1013
1014 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1015 if (Uses.size() <= 2)
1016 return 0;
1017 const unsigned NumGaps = Uses.size()-1;
1018
1019 DEBUG({
1020 dbgs() << "tryLocalSplit: ";
1021 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1022 dbgs() << ' ' << SA->UseSlots[i];
1023 dbgs() << '\n';
1024 });
1025
1026 // For every use, find the previous mapped non-copy instruction.
1027 // We use this to detect valid split points, and to estimate new interval
1028 // sizes.
1029 calcPrevSlots();
1030
1031 unsigned BestBefore = NumGaps;
1032 unsigned BestAfter = 0;
1033 float BestDiff = 0;
1034
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001035 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001036 SmallVector<float, 8> GapWeight;
1037
1038 Order.rewind();
1039 while (unsigned PhysReg = Order.next()) {
1040 // Keep track of the largest spill weight that would need to be evicted in
1041 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1042 calcGapWeights(PhysReg, GapWeight);
1043
1044 // Try to find the best sequence of gaps to close.
1045 // The new spill weight must be larger than any gap interference.
1046
1047 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1048 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
1049
1050 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1051 // It is the spill weight that needs to be evicted.
1052 float MaxGap = GapWeight[0];
1053 for (unsigned i = 1; i != SplitAfter; ++i)
1054 MaxGap = std::max(MaxGap, GapWeight[i]);
1055
1056 for (;;) {
1057 // Live before/after split?
1058 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1059 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1060
1061 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1062 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1063 << " i=" << MaxGap);
1064
1065 // Stop before the interval gets so big we wouldn't be making progress.
1066 if (!LiveBefore && !LiveAfter) {
1067 DEBUG(dbgs() << " all\n");
1068 break;
1069 }
1070 // Should the interval be extended or shrunk?
1071 bool Shrink = true;
1072 if (MaxGap < HUGE_VALF) {
1073 // Estimate the new spill weight.
1074 //
1075 // Each instruction reads and writes the register, except the first
1076 // instr doesn't read when !FirstLive, and the last instr doesn't write
1077 // when !LastLive.
1078 //
1079 // We will be inserting copies before and after, so the total number of
1080 // reads and writes is 2 * EstUses.
1081 //
1082 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1083 2*(LiveBefore + LiveAfter);
1084
1085 // Try to guess the size of the new interval. This should be trivial,
1086 // but the slot index of an inserted copy can be a lot smaller than the
1087 // instruction it is inserted before if there are many dead indexes
1088 // between them.
1089 //
1090 // We measure the distance from the instruction before SplitBefore to
1091 // get a conservative estimate.
1092 //
1093 // The final distance can still be different if inserting copies
1094 // triggers a slot index renumbering.
1095 //
1096 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1097 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1098 // Would this split be possible to allocate?
1099 // Never allocate all gaps, we wouldn't be making progress.
1100 float Diff = EstWeight - MaxGap;
1101 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1102 if (Diff > 0) {
1103 Shrink = false;
1104 if (Diff > BestDiff) {
1105 DEBUG(dbgs() << " (best)");
1106 BestDiff = Diff;
1107 BestBefore = SplitBefore;
1108 BestAfter = SplitAfter;
1109 }
1110 }
1111 }
1112
1113 // Try to shrink.
1114 if (Shrink) {
1115 SplitBefore = nextSplitPoint(SplitBefore);
1116 if (SplitBefore < SplitAfter) {
1117 DEBUG(dbgs() << " shrink\n");
1118 // Recompute the max when necessary.
1119 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1120 MaxGap = GapWeight[SplitBefore];
1121 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1122 MaxGap = std::max(MaxGap, GapWeight[i]);
1123 }
1124 continue;
1125 }
1126 MaxGap = 0;
1127 }
1128
1129 // Try to extend the interval.
1130 if (SplitAfter >= NumGaps) {
1131 DEBUG(dbgs() << " end\n");
1132 break;
1133 }
1134
1135 DEBUG(dbgs() << " extend\n");
1136 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1137 SplitAfter != e; ++SplitAfter)
1138 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1139 continue;
1140 }
1141 }
1142
1143 // Didn't find any candidates?
1144 if (BestBefore == NumGaps)
1145 return 0;
1146
1147 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1148 << '-' << Uses[BestAfter] << ", " << BestDiff
1149 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1150
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001151 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001152 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001153
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001154 SE->openIntv();
1155 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1156 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1157 SE->useIntv(SegStart, SegStop);
1158 SE->closeIntv();
1159 SE->finish();
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001160 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001161 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001162
1163 return 0;
1164}
1165
1166//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001167// Live Range Splitting
1168//===----------------------------------------------------------------------===//
1169
1170/// trySplit - Try to split VirtReg or one of its interferences, making it
1171/// assignable.
1172/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1173unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1174 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001175 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001176 if (LIS->intervalIsInOneMBB(VirtReg)) {
1177 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001178 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001179 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001180 }
1181
1182 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001183
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001184 // Don't iterate global splitting.
1185 // Move straight to spilling if this range was produced by a global split.
1186 LiveRangeStage Stage = getStage(VirtReg);
1187 if (Stage >= RS_Block)
1188 return 0;
1189
1190 SA->analyze(&VirtReg);
1191
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001192 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001193 if (Stage < RS_Region) {
1194 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1195 if (PhysReg || !NewVRegs.empty())
1196 return PhysReg;
1197 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001198
1199 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001200 if (Stage < RS_Block) {
1201 SplitAnalysis::BlockPtrSet Blocks;
1202 if (SA->getMultiUseBlocks(Blocks)) {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001203 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001204 SE->reset(LREdit);
1205 SE->splitSingleBlocks(Blocks);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001206 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1207 if (VerifyEnabled)
1208 MF->verify(this, "After splitting live range around basic blocks");
1209 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001210 }
1211
1212 // Don't assign any physregs.
1213 return 0;
1214}
1215
1216
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001217//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001218// Main Entry Point
1219//===----------------------------------------------------------------------===//
1220
1221unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001222 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001223 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001224 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1225 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001226 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001227 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001228 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00001229
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +00001230 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001231 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001232
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001233 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1234
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001235 // The first time we see a live range, don't try to split or spill.
1236 // Wait until the second time, when all smaller ranges have been allocated.
1237 // This gives a better picture of the interference to split around.
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001238 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +00001239 if (Stage == RS_First) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001240 LRStage[VirtReg.reg] = RS_Second;
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001241 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001242 NewVRegs.push_back(&VirtReg);
1243 return 0;
1244 }
1245
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001246 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1247
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001248 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001249 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1250 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001251 return PhysReg;
1252
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001253 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001254 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001255 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1256 spiller().spill(LRE);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001257 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001258
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001259 if (VerifyEnabled)
1260 MF->verify(this, "After spilling");
1261
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001262 // The live virtual register requesting allocation was spilled, so tell
1263 // the caller not to allocate anything during this round.
1264 return 0;
1265}
1266
1267bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1268 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1269 << "********** Function: "
1270 << ((Value*)mf.getFunction())->getName() << '\n');
1271
1272 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001273 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001274 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001275
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001276 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001277 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001278 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001279 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001280 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001281 Loops = &getAnalysis<MachineLoopInfo>();
1282 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001283 Bundles = &getAnalysis<EdgeBundles>();
1284 SpillPlacer = &getAnalysis<SpillPlacement>();
1285
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001286 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001287 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001288 LRStage.clear();
1289 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001290 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001291
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001292 allocatePhysRegs();
1293 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001294 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001295
1296 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001297 {
1298 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001299 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001300 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001301
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001302 // Write out new DBG_VALUE instructions.
1303 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
1304
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001305 // The pass output is in VirtRegMap. Release all the transient data.
1306 releaseMemory();
1307
1308 return true;
1309}