blob: 8b5c1b0aa80004f031170da28e909648eeb2ee52 [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.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +000098 RS_Global, ///< Produced by global splitting.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000099 RS_Local, ///< Produced by local splitting.
100 RS_Spill ///< Produced by spilling.
101 };
102
103 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
104
105 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
106 return LiveRangeStage(LRStage[VirtReg.reg]);
107 }
108
109 template<typename Iterator>
110 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
111 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000112 for (;Begin != End; ++Begin) {
113 unsigned Reg = (*Begin)->reg;
114 if (LRStage[Reg] == RS_New)
115 LRStage[Reg] = NewStage;
116 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000117 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000118
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000119 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000120 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000121 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000122
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000123 /// Cached per-block interference maps
124 InterferenceCache IntfCache;
125
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000126 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000127 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000128
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000129 /// Live-through blocks that have already been added to SpillPlacer.
130 SparseBitVector<> ActiveThroughBlocks;
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000131
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000132 /// Global live range splitting candidate info.
133 struct GlobalSplitCandidate {
134 unsigned PhysReg;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000135 BitVector LiveBundles;
136 };
137
138 /// Candidate info for for each PhysReg in AllocationOrder.
139 /// This vector never shrinks, but grows to the size of the largest register
140 /// class.
141 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
142
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000143 /// For every instruction in SA->UseSlots, store the previous non-copy
144 /// instruction.
145 SmallVector<SlotIndex, 8> PrevSlot;
146
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000147public:
148 RAGreedy();
149
150 /// Return the pass name.
151 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000152 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000153 }
154
155 /// RAGreedy analysis usage.
156 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000157 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000158 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000159 virtual void enqueue(LiveInterval *LI);
160 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000161 virtual unsigned selectOrSplit(LiveInterval&,
162 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000163
164 /// Perform register allocation.
165 virtual bool runOnMachineFunction(MachineFunction &mf);
166
167 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000168
169private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000170 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000171 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000172 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000173 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000174
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000175 bool addSplitConstraints(InterferenceCache::Cursor, float&);
176 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
177 void growRegion(InterferenceCache::Cursor);
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000178 float calcGlobalSplitCost(unsigned, const BitVector&);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000179 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
180 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000181 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
182 SlotIndex getPrevMappedIndex(const MachineInstr*);
183 void calcPrevSlots();
184 unsigned nextSplitPoint(unsigned);
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000185 bool canEvictInterference(LiveInterval&, unsigned, float&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000186
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000187 unsigned tryEvict(LiveInterval&, AllocationOrder&,
188 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000189 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
190 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000191 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
192 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000193 unsigned trySplit(LiveInterval&, AllocationOrder&,
194 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000195};
196} // end anonymous namespace
197
198char RAGreedy::ID = 0;
199
200FunctionPass* llvm::createGreedyRegisterAllocator() {
201 return new RAGreedy();
202}
203
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000204RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_New) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000205 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000206 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000207 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
208 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
209 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
210 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
211 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
212 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
213 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
214 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000215 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000216 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000217 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
218 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000219}
220
221void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
222 AU.setPreservesCFG();
223 AU.addRequired<AliasAnalysis>();
224 AU.addPreserved<AliasAnalysis>();
225 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000226 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000227 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000228 AU.addRequired<LiveDebugVariables>();
229 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000230 if (StrongPHIElim)
231 AU.addRequiredID(StrongPHIEliminationID);
232 AU.addRequiredTransitive<RegisterCoalescer>();
233 AU.addRequired<CalculateSpillWeights>();
234 AU.addRequired<LiveStacks>();
235 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000236 AU.addRequired<MachineDominatorTree>();
237 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000238 AU.addRequired<MachineLoopInfo>();
239 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000240 AU.addRequired<MachineLoopRanges>();
241 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000242 AU.addRequired<VirtRegMap>();
243 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000244 AU.addRequired<EdgeBundles>();
245 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000246 MachineFunctionPass::getAnalysisUsage(AU);
247}
248
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000249
250//===----------------------------------------------------------------------===//
251// LiveRangeEdit delegate methods
252//===----------------------------------------------------------------------===//
253
254void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
255 // LRE itself will remove from SlotIndexes and parent basic block.
256 VRM->RemoveMachineInstrFromMaps(MI);
257}
258
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000259bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
260 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
261 unassign(LIS->getInterval(VirtReg), PhysReg);
262 return true;
263 }
264 // Unassigned virtreg is probably in the priority queue.
265 // RegAllocBase will erase it after dequeueing.
266 return false;
267}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000268
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000269void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
270 unsigned PhysReg = VRM->getPhys(VirtReg);
271 if (!PhysReg)
272 return;
273
274 // Register is assigned, put it back on the queue for reassignment.
275 LiveInterval &LI = LIS->getInterval(VirtReg);
276 unassign(LI, PhysReg);
277 enqueue(&LI);
278}
279
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000280void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
281 // LRE may clone a virtual register because dead code elimination causes it to
282 // be split into connected components. Ensure that the new register gets the
283 // same stage as the parent.
284 LRStage.grow(New);
285 LRStage[New] = LRStage[Old];
286}
287
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000288void RAGreedy::releaseMemory() {
289 SpillerInstance.reset(0);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000290 LRStage.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000291 RegAllocBase::releaseMemory();
292}
293
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000294void RAGreedy::enqueue(LiveInterval *LI) {
295 // Prioritize live ranges by size, assigning larger ranges first.
296 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000297 const unsigned Size = LI->getSize();
298 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000299 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
300 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000301 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000302
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000303 LRStage.grow(Reg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000304 if (LRStage[Reg] == RS_New)
305 LRStage[Reg] = RS_First;
306
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000307 if (LRStage[Reg] == RS_Second)
308 // Unsplit ranges that couldn't be allocated immediately are deferred until
309 // everything else has been allocated. Long ranges are allocated last so
310 // they are split against realistic interference.
311 Prio = (1u << 31) - Size;
312 else {
313 // Everything else is allocated in long->short order. Long ranges that don't
314 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000315 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000316
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000317 // Boost ranges that have a physical register hint.
318 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
319 Prio |= (1u << 30);
320 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000321
322 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000323}
324
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000325LiveInterval *RAGreedy::dequeue() {
326 if (Queue.empty())
327 return 0;
328 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
329 Queue.pop();
330 return LI;
331}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000332
333//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000334// Interference eviction
335//===----------------------------------------------------------------------===//
336
337/// canEvict - Return true if all interferences between VirtReg and PhysReg can
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000338/// be evicted.
339/// Return false if any interference is heavier than MaxWeight.
340/// On return, set MaxWeight to the maximal spill weight of an interference.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000341bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000342 float &MaxWeight) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000343 float Weight = 0;
344 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
345 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000346 // If there is 10 or more interferences, chances are one is heavier.
347 if (Q.collectInterferingVRegs(10, MaxWeight) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000348 return false;
349
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000350 // Check if any interfering live range is heavier than MaxWeight.
351 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
352 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000353 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
354 return false;
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000355 if (Intf->weight >= MaxWeight)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000356 return false;
357 Weight = std::max(Weight, Intf->weight);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000358 }
359 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000360 MaxWeight = Weight;
361 return true;
362}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000363
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000364/// tryEvict - Try to evict all interferences for a physreg.
365/// @param VirtReg Currently unassigned virtual register.
366/// @param Order Physregs to try.
367/// @return Physreg to assign VirtReg, or 0.
368unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
369 AllocationOrder &Order,
370 SmallVectorImpl<LiveInterval*> &NewVRegs){
371 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
372
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000373 // Keep track of the lightest single interference seen so far.
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000374 float BestWeight = VirtReg.weight;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000375 unsigned BestPhys = 0;
376
377 Order.rewind();
378 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000379 float Weight = BestWeight;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000380 if (!canEvictInterference(VirtReg, PhysReg, Weight))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000381 continue;
382
383 // This is an eviction candidate.
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000384 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " interference = "
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000385 << Weight << '\n');
386 if (BestPhys && Weight >= BestWeight)
387 continue;
388
389 // Best so far.
390 BestPhys = PhysReg;
391 BestWeight = Weight;
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000392 // Stop if the hint can be used.
393 if (Order.isHint(PhysReg))
394 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000395 }
396
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000397 if (!BestPhys)
398 return 0;
399
400 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
401 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
402 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
403 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
404 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
405 LiveInterval *Intf = Q.interferingVRegs()[i];
406 unassign(*Intf, VRM->getPhys(Intf->reg));
407 ++NumEvicted;
408 NewVRegs.push_back(Intf);
409 }
410 }
411 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000412}
413
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000414
415//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000416// Region Splitting
417//===----------------------------------------------------------------------===//
418
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000419/// addSplitConstraints - Fill out the SplitConstraints vector based on the
420/// interference pattern in Physreg and its aliases. Add the constraints to
421/// SpillPlacement and return the static cost of this split in Cost, assuming
422/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000423/// Return false if there are no bundles with positive bias.
424bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
425 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000426 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000427
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000428 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000429 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000430 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000431 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
432 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000433 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000434
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000435 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000436 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000437 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
438 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000439
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000440 if (!Intf.hasInterference())
441 continue;
442
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000443 // Number of spill code instructions to insert.
444 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000445
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000446 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000447 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000448 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000449 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000450 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000451 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000452 else if (Intf.first() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000453 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000454 }
455
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000456 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000457 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000458 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000459 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000460 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000461 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000462 else if (Intf.last() > (BI.LiveThrough ? BI.FirstUse : BI.Def))
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000463 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000464 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000465
466 // Accumulate the total frequency of inserted spill code.
467 if (Ins)
468 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000469 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000470 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000471
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000472 // Add constraints for use-blocks. Note that these are the only constraints
473 // that may add a positive bias, it is downhill from here.
474 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000475 return SpillPlacer->scanActiveBundles();
476}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000477
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000478
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000479/// addThroughConstraints - Add constraints and links to SpillPlacer from the
480/// live-through blocks in Blocks.
481void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
482 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000483 const unsigned GroupSize = 8;
484 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000485 unsigned TBS[GroupSize];
486 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000487
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000488 for (unsigned i = 0; i != Blocks.size(); ++i) {
489 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000490 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000491
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000492 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000493 assert(T < GroupSize && "Array overflow");
494 TBS[T] = Number;
495 if (++T == GroupSize) {
496 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
497 T = 0;
498 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000499 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000500 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000501
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000502 assert(B < GroupSize && "Array overflow");
503 BCS[B].Number = Number;
504
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000505 // Interference for the live-in value.
506 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
507 BCS[B].Entry = SpillPlacement::MustSpill;
508 else
509 BCS[B].Entry = SpillPlacement::PrefSpill;
510
511 // Interference for the live-out value.
512 if (Intf.last() >= SA->getLastSplitPoint(Number))
513 BCS[B].Exit = SpillPlacement::MustSpill;
514 else
515 BCS[B].Exit = SpillPlacement::PrefSpill;
516
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000517 if (++B == GroupSize) {
518 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
519 SpillPlacer->addConstraints(Array);
520 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000521 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000522 }
523
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000524 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
525 SpillPlacer->addConstraints(Array);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000526 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000527}
528
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000529void RAGreedy::growRegion(InterferenceCache::Cursor Intf) {
530 // Keep track of through blocks that have already been added to SpillPlacer.
531 SparseBitVector<> Added;
532 SmallVector<unsigned, 16> ThroughBlocks;
533#ifndef NDEBUG
534 unsigned Visited = 0;
535#endif
536 for (;;) {
537 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
538 if (NewBundles.empty())
539 break;
540 // Find new through blocks in the periphery of PrefRegBundles.
541 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
542 unsigned Bundle = NewBundles[i];
543 // Look at all blocks connected to Bundle in the full graph.
544 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
545 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
546 I != E; ++I) {
547 unsigned Block = *I;
548 if (!SA->isThroughBlock(Block) || !Added.test_and_set(Block))
549 continue;
550 // This is a new through block. Add it to SpillPlacer later.
551 ThroughBlocks.push_back(Block);
552#ifndef NDEBUG
553 ++Visited;
554#endif
555 }
556 }
557 // Any new blocks to add?
558 if (!ThroughBlocks.empty()) {
559 addThroughConstraints(Intf, ThroughBlocks);
560 ThroughBlocks.clear();
561 }
562 // Perhaps iterating can enable more bundles?
563 SpillPlacer->iterate();
564 }
565
566 // Rememeber the relevant set of through blocks for splitAroundRegion().
567 ActiveThroughBlocks |= Added;
568 DEBUG(dbgs() << ", v=" << Visited);
569}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000570
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000571/// calcGlobalSplitCost - Return the global split cost of following the split
572/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000573/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000574///
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000575float RAGreedy::calcGlobalSplitCost(unsigned PhysReg,
576 const BitVector &LiveBundles) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000577 float GlobalCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000578 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
579 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
580 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000581 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000582 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
583 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
584 unsigned Ins = 0;
585
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000586 if (BI.LiveIn)
587 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
588 if (BI.LiveOut)
589 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000590 if (Ins)
591 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000592 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000593
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000594 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000595 for (SparseBitVector<>::iterator I = ActiveThroughBlocks.begin(),
596 E = ActiveThroughBlocks.end(); I != E; ++I) {
597 unsigned Number = *I;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000598 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
599 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000600 if (!RegIn && !RegOut)
601 continue;
602 if (RegIn && RegOut) {
603 // We need double spill code if this block has interference.
604 Intf.moveToBlock(Number);
605 if (Intf.hasInterference())
606 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
607 continue;
608 }
609 // live-in / stack-out or stack-in live-out.
610 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000611 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000612 return GlobalCost;
613}
614
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000615/// splitAroundRegion - Split VirtReg around the region determined by
616/// LiveBundles. Make an effort to avoid interference from PhysReg.
617///
618/// The 'register' interval is going to contain as many uses as possible while
619/// avoiding interference. The 'stack' interval is the complement constructed by
620/// SplitEditor. It will contain the rest.
621///
622void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
623 const BitVector &LiveBundles,
624 SmallVectorImpl<LiveInterval*> &NewVRegs) {
625 DEBUG({
626 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
627 << " with bundles";
628 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
629 dbgs() << " EB#" << i;
630 dbgs() << ".\n";
631 });
632
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000633 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000634 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000635 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000636
637 // Create the main cross-block interval.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000638 const unsigned MainIntv = SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000639
640 // First add all defs that are live out of a block.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000641 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
642 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
643 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000644 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
645 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
646
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000647 // Create separate intervals for isolated blocks with multiple uses.
648 if (!RegIn && !RegOut && BI.FirstUse != BI.LastUse) {
649 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
650 SE->splitSingleBlock(BI);
651 SE->selectIntv(MainIntv);
652 continue;
653 }
654
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000655 // Should the register be live out?
656 if (!BI.LiveOut || !RegOut)
657 continue;
658
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000659 SlotIndex Start, Stop;
660 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000661 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000662 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000663 << Bundles->getBundle(BI.MBB->getNumber(), 1)
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000664 << " [" << Start << ';'
665 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
666 << ") intf [" << Intf.first() << ';' << Intf.last() << ')');
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000667
668 // The interference interval should either be invalid or overlap MBB.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000669 assert((!Intf.hasInterference() || Intf.first() < Stop)
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000670 && "Bad interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000671 assert((!Intf.hasInterference() || Intf.last() > Start)
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000672 && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000673
674 // Check interference leaving the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000675 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000676 // Block is interference-free.
677 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000678 if (!BI.LiveThrough) {
679 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000680 SE->useIntv(SE->enterIntvBefore(BI.Def), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000681 continue;
682 }
683 if (!RegIn) {
684 // Block is live-through, but entry bundle is on the stack.
685 // Reload just before the first use.
686 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000687 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000688 continue;
689 }
690 DEBUG(dbgs() << ", live-through.\n");
691 continue;
692 }
693
694 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000695 DEBUG(dbgs() << ", interference to " << Intf.last());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000696
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000697 if (!BI.LiveThrough && Intf.last() <= BI.Def) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000698 // The interference doesn't reach the outgoing segment.
699 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000700 SE->useIntv(BI.Def, Stop);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000701 continue;
702 }
703
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000704 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000705 if (Intf.last().getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000706 // There are interference-free uses at the end of the block.
707 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000708 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000709 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000710 Intf.last().getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000711 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
712 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000713 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000714 // Only attempt a split befroe the last split point.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000715 if (Use.getBaseIndex() <= LastSplitPoint) {
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000716 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000717 SlotIndex SegStart = SE->enterIntvBefore(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000718 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000719 assert(SegStart < LastSplitPoint && "Impossible split point");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000720 SE->useIntv(SegStart, Stop);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000721 continue;
722 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000723 }
724
725 // Interference is after the last use.
726 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000727 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000728 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000729 }
730
731 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000732 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
733 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000734 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
735 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
736
737 // Is the register live-in?
738 if (!BI.LiveIn || !RegIn)
739 continue;
740
741 // We have an incoming register. Check for interference.
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000742 SlotIndex Start, Stop;
743 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000744 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000745 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000746 << " -> BB#" << BI.MBB->getNumber() << " [" << Start << ';'
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000747 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
748 << ')');
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000749
750 // Check interference entering the block.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000751 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000752 // Block is interference-free.
753 DEBUG(dbgs() << ", no interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000754 if (!BI.LiveThrough) {
755 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000756 SE->useIntv(Start, SE->leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000757 continue;
758 }
759 if (!RegOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000760 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000761 // Block is live-through, but exit bundle is on the stack.
762 // Spill immediately after the last use.
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000763 if (BI.LastUse < LastSplitPoint) {
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000764 DEBUG(dbgs() << ", uses, stack-out.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000765 SE->useIntv(Start, SE->leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000766 continue;
767 }
768 // The last use is after the last split point, it is probably an
769 // indirect jump.
770 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000771 << LastSplitPoint << ", stack-out.\n");
772 SlotIndex SegEnd = SE->leaveIntvBefore(LastSplitPoint);
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000773 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000774 // Run a double interval from the split to the last use.
775 // This makes it possible to spill the complement without affecting the
776 // indirect branch.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000777 SE->overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000778 continue;
779 }
780 // Register is live-through.
781 DEBUG(dbgs() << ", uses, live-through.\n");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000782 SE->useIntv(Start, Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000783 continue;
784 }
785
786 // Block has interference.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000787 DEBUG(dbgs() << ", interference from " << Intf.first());
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000788
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000789 if (!BI.LiveThrough && Intf.first() >= BI.Kill) {
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000790 // The interference doesn't reach the outgoing segment.
791 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000792 SE->useIntv(Start, BI.Kill);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000793 continue;
794 }
795
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000796 if (Intf.first().getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000797 // There are interference-free uses at the beginning of the block.
798 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000799 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000800 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000801 Intf.first().getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000802 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
803 SlotIndex Use = (--UI)->getBoundaryIndex();
804 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000805 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000806 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000807 SE->useIntv(Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000808 continue;
809 }
810
811 // Interference is before the first use.
812 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000813 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000814 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000815 }
816
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000817 // Handle live-through blocks.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000818 for (SparseBitVector<>::iterator I = ActiveThroughBlocks.begin(),
819 E = ActiveThroughBlocks.end(); I != E; ++I) {
820 unsigned Number = *I;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000821 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
822 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
823 DEBUG(dbgs() << "Live through BB#" << Number << '\n');
824 if (RegIn && RegOut) {
825 Intf.moveToBlock(Number);
826 if (!Intf.hasInterference()) {
827 SE->useIntv(Indexes->getMBBStartIdx(Number),
828 Indexes->getMBBEndIdx(Number));
829 continue;
830 }
831 }
832 MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
833 if (RegIn)
834 SE->leaveIntvAtTop(*MBB);
835 if (RegOut)
836 SE->enterIntvAtEnd(*MBB);
837 }
838
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000839 SE->closeIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000840
841 // FIXME: Should we be more aggressive about splitting the stack region into
842 // per-block segments? The current approach allows the stack region to
843 // separate into connected components. Some components may be allocatable.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000844 SE->finish();
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000845 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000846
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000847 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000848 MF->verify(this, "After splitting live range around region");
849}
850
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000851unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
852 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000853 BitVector LiveBundles, BestBundles;
854 float BestCost = 0;
855 unsigned BestReg = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000856 ActiveThroughBlocks.clear();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000857
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000858 Order.rewind();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000859 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
860 if (GlobalCand.size() <= Cand)
861 GlobalCand.resize(Cand+1);
862 GlobalCand[Cand].PhysReg = PhysReg;
863
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000864 SpillPlacer->prepare(LiveBundles);
865 float Cost;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000866 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
867 if (!addSplitConstraints(Intf, Cost)) {
868 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000869 continue;
870 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000871 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000872 if (BestReg && Cost >= BestCost) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000873 DEBUG(dbgs() << " worse than " << PrintReg(BestReg, TRI) << '\n');
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000874 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000875 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000876 growRegion(Intf);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000877
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000878 SpillPlacer->finish();
879
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000880 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000881 if (!LiveBundles.any()) {
882 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000883 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000884 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000885
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000886 Cost += calcGlobalSplitCost(PhysReg, LiveBundles);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000887 DEBUG({
888 dbgs() << ", total = " << Cost << " with bundles";
889 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
890 dbgs() << " EB#" << i;
891 dbgs() << ".\n";
892 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000893 if (!BestReg || Cost < BestCost) {
894 BestReg = PhysReg;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000895 BestCost = 0.98f * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000896 BestBundles.swap(LiveBundles);
897 }
898 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000899
900 if (!BestReg)
901 return 0;
902
903 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000904 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Global);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000905 return 0;
906}
907
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000908
909//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000910// Local Splitting
911//===----------------------------------------------------------------------===//
912
913
914/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
915/// in order to use PhysReg between two entries in SA->UseSlots.
916///
917/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
918///
919void RAGreedy::calcGapWeights(unsigned PhysReg,
920 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000921 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
922 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000923 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
924 const unsigned NumGaps = Uses.size()-1;
925
926 // Start and end points for the interference check.
927 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
928 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
929
930 GapWeight.assign(NumGaps, 0.0f);
931
932 // Add interference from each overlapping register.
933 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
934 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
935 .checkInterference())
936 continue;
937
938 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
939 // so we don't need InterferenceQuery.
940 //
941 // Interference that overlaps an instruction is counted in both gaps
942 // surrounding the instruction. The exception is interference before
943 // StartIdx and after StopIdx.
944 //
945 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
946 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
947 // Skip the gaps before IntI.
948 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
949 if (++Gap == NumGaps)
950 break;
951 if (Gap == NumGaps)
952 break;
953
954 // Update the gaps covered by IntI.
955 const float weight = IntI.value()->weight;
956 for (; Gap != NumGaps; ++Gap) {
957 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
958 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
959 break;
960 }
961 if (Gap == NumGaps)
962 break;
963 }
964 }
965}
966
967/// getPrevMappedIndex - Return the slot index of the last non-copy instruction
968/// before MI that has a slot index. If MI is the first mapped instruction in
969/// its block, return the block start index instead.
970///
971SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
972 assert(MI && "Missing MachineInstr");
973 const MachineBasicBlock *MBB = MI->getParent();
974 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
975 while (I != B)
976 if (!(--I)->isDebugValue() && !I->isCopy())
977 return Indexes->getInstructionIndex(I);
978 return Indexes->getMBBStartIdx(MBB);
979}
980
981/// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
982/// real non-copy instruction for each instruction in SA->UseSlots.
983///
984void RAGreedy::calcPrevSlots() {
985 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
986 PrevSlot.clear();
987 PrevSlot.reserve(Uses.size());
988 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
989 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
990 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
991 }
992}
993
994/// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
995/// be beneficial to split before UseSlots[i].
996///
997/// 0 is always a valid split point
998unsigned RAGreedy::nextSplitPoint(unsigned i) {
999 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1000 const unsigned Size = Uses.size();
1001 assert(i != Size && "No split points after the end");
1002 // Allow split before i when Uses[i] is not adjacent to the previous use.
1003 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
1004 ;
1005 return i;
1006}
1007
1008/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1009/// basic block.
1010///
1011unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1012 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001013 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1014 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001015
1016 // Note that it is possible to have an interval that is live-in or live-out
1017 // while only covering a single block - A phi-def can use undef values from
1018 // predecessors, and the block could be a single-block loop.
1019 // We don't bother doing anything clever about such a case, we simply assume
1020 // that the interval is continuous from FirstUse to LastUse. We should make
1021 // sure that we don't do anything illegal to such an interval, though.
1022
1023 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1024 if (Uses.size() <= 2)
1025 return 0;
1026 const unsigned NumGaps = Uses.size()-1;
1027
1028 DEBUG({
1029 dbgs() << "tryLocalSplit: ";
1030 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1031 dbgs() << ' ' << SA->UseSlots[i];
1032 dbgs() << '\n';
1033 });
1034
1035 // For every use, find the previous mapped non-copy instruction.
1036 // We use this to detect valid split points, and to estimate new interval
1037 // sizes.
1038 calcPrevSlots();
1039
1040 unsigned BestBefore = NumGaps;
1041 unsigned BestAfter = 0;
1042 float BestDiff = 0;
1043
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001044 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001045 SmallVector<float, 8> GapWeight;
1046
1047 Order.rewind();
1048 while (unsigned PhysReg = Order.next()) {
1049 // Keep track of the largest spill weight that would need to be evicted in
1050 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1051 calcGapWeights(PhysReg, GapWeight);
1052
1053 // Try to find the best sequence of gaps to close.
1054 // The new spill weight must be larger than any gap interference.
1055
1056 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1057 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
1058
1059 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1060 // It is the spill weight that needs to be evicted.
1061 float MaxGap = GapWeight[0];
1062 for (unsigned i = 1; i != SplitAfter; ++i)
1063 MaxGap = std::max(MaxGap, GapWeight[i]);
1064
1065 for (;;) {
1066 // Live before/after split?
1067 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1068 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1069
1070 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1071 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1072 << " i=" << MaxGap);
1073
1074 // Stop before the interval gets so big we wouldn't be making progress.
1075 if (!LiveBefore && !LiveAfter) {
1076 DEBUG(dbgs() << " all\n");
1077 break;
1078 }
1079 // Should the interval be extended or shrunk?
1080 bool Shrink = true;
1081 if (MaxGap < HUGE_VALF) {
1082 // Estimate the new spill weight.
1083 //
1084 // Each instruction reads and writes the register, except the first
1085 // instr doesn't read when !FirstLive, and the last instr doesn't write
1086 // when !LastLive.
1087 //
1088 // We will be inserting copies before and after, so the total number of
1089 // reads and writes is 2 * EstUses.
1090 //
1091 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1092 2*(LiveBefore + LiveAfter);
1093
1094 // Try to guess the size of the new interval. This should be trivial,
1095 // but the slot index of an inserted copy can be a lot smaller than the
1096 // instruction it is inserted before if there are many dead indexes
1097 // between them.
1098 //
1099 // We measure the distance from the instruction before SplitBefore to
1100 // get a conservative estimate.
1101 //
1102 // The final distance can still be different if inserting copies
1103 // triggers a slot index renumbering.
1104 //
1105 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1106 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1107 // Would this split be possible to allocate?
1108 // Never allocate all gaps, we wouldn't be making progress.
1109 float Diff = EstWeight - MaxGap;
1110 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1111 if (Diff > 0) {
1112 Shrink = false;
1113 if (Diff > BestDiff) {
1114 DEBUG(dbgs() << " (best)");
1115 BestDiff = Diff;
1116 BestBefore = SplitBefore;
1117 BestAfter = SplitAfter;
1118 }
1119 }
1120 }
1121
1122 // Try to shrink.
1123 if (Shrink) {
1124 SplitBefore = nextSplitPoint(SplitBefore);
1125 if (SplitBefore < SplitAfter) {
1126 DEBUG(dbgs() << " shrink\n");
1127 // Recompute the max when necessary.
1128 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1129 MaxGap = GapWeight[SplitBefore];
1130 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1131 MaxGap = std::max(MaxGap, GapWeight[i]);
1132 }
1133 continue;
1134 }
1135 MaxGap = 0;
1136 }
1137
1138 // Try to extend the interval.
1139 if (SplitAfter >= NumGaps) {
1140 DEBUG(dbgs() << " end\n");
1141 break;
1142 }
1143
1144 DEBUG(dbgs() << " extend\n");
1145 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1146 SplitAfter != e; ++SplitAfter)
1147 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1148 continue;
1149 }
1150 }
1151
1152 // Didn't find any candidates?
1153 if (BestBefore == NumGaps)
1154 return 0;
1155
1156 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1157 << '-' << Uses[BestAfter] << ", " << BestDiff
1158 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1159
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001160 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001161 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001162
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001163 SE->openIntv();
1164 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1165 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1166 SE->useIntv(SegStart, SegStop);
1167 SE->closeIntv();
1168 SE->finish();
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001169 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001170 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001171
1172 return 0;
1173}
1174
1175//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001176// Live Range Splitting
1177//===----------------------------------------------------------------------===//
1178
1179/// trySplit - Try to split VirtReg or one of its interferences, making it
1180/// assignable.
1181/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1182unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1183 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001184 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001185 if (LIS->intervalIsInOneMBB(VirtReg)) {
1186 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001187 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001188 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001189 }
1190
1191 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001192
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001193 // Don't iterate global splitting.
1194 // Move straight to spilling if this range was produced by a global split.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001195 if (getStage(VirtReg) >= RS_Global)
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001196 return 0;
1197
1198 SA->analyze(&VirtReg);
1199
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001200 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001201 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1202 if (PhysReg || !NewVRegs.empty())
1203 return PhysReg;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001204
1205 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001206 SplitAnalysis::BlockPtrSet Blocks;
1207 if (SA->getMultiUseBlocks(Blocks)) {
1208 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1209 SE->reset(LREdit);
1210 SE->splitSingleBlocks(Blocks);
1211 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Global);
1212 if (VerifyEnabled)
1213 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001214 }
1215
1216 // Don't assign any physregs.
1217 return 0;
1218}
1219
1220
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001221//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001222// Main Entry Point
1223//===----------------------------------------------------------------------===//
1224
1225unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001226 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001227 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001228 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1229 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001230 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001231 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001232 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00001233
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +00001234 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001235 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001236
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001237 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1238
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001239 // The first time we see a live range, don't try to split or spill.
1240 // Wait until the second time, when all smaller ranges have been allocated.
1241 // This gives a better picture of the interference to split around.
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001242 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +00001243 if (Stage == RS_First) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001244 LRStage[VirtReg.reg] = RS_Second;
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001245 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001246 NewVRegs.push_back(&VirtReg);
1247 return 0;
1248 }
1249
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001250 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1251
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001252 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001253 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1254 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001255 return PhysReg;
1256
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001257 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001258 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001259 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1260 spiller().spill(LRE);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001261 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001262
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001263 if (VerifyEnabled)
1264 MF->verify(this, "After spilling");
1265
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001266 // The live virtual register requesting allocation was spilled, so tell
1267 // the caller not to allocate anything during this round.
1268 return 0;
1269}
1270
1271bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1272 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1273 << "********** Function: "
1274 << ((Value*)mf.getFunction())->getName() << '\n');
1275
1276 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001277 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001278 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001279
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001280 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001281 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001282 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001283 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001284 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001285 Loops = &getAnalysis<MachineLoopInfo>();
1286 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001287 Bundles = &getAnalysis<EdgeBundles>();
1288 SpillPlacer = &getAnalysis<SpillPlacement>();
1289
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001290 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001291 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001292 LRStage.clear();
1293 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001294 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001295
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001296 allocatePhysRegs();
1297 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001298 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001299
1300 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001301 {
1302 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001303 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001304 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001305
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001306 // Write out new DBG_VALUE instructions.
1307 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
1308
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001309 // The pass output is in VirtRegMap. Release all the transient data.
1310 releaseMemory();
1311
1312 return true;
1313}