blob: 97d4728348e561c15d99503f933b20e2c35b2b8c [file] [log] [blame]
Evan Cheng09e8ca82008-10-20 21:44:59 +00001//===-- PreAllocSplitting.cpp - Pre-allocation Interval Spltting Pass. ----===//
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 implements the machine instruction level pre-register allocation
11// live interval splitting pass. It finds live interval barriers, i.e.
12// instructions which will kill all physical registers in certain register
13// classes, and split all live intervals which cross the barrier.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "pre-alloc-split"
Owen Anderson420dd372009-03-14 21:40:05 +000018#include "VirtRegMap.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Evan Chengd0e32c52008-10-29 05:06:14 +000020#include "llvm/CodeGen/LiveStackAnalysis.h"
Owen Andersonf1f75b12008-11-04 22:22:41 +000021#include "llvm/CodeGen/MachineDominators.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000022#include "llvm/CodeGen/MachineFrameInfo.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/CodeGen/MachineLoopInfo.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/Passes.h"
27#include "llvm/CodeGen/RegisterCoalescer.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000028#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000029#include "llvm/Target/TargetMachine.h"
30#include "llvm/Target/TargetOptions.h"
31#include "llvm/Target/TargetRegisterInfo.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
Evan Chengd0e32c52008-10-29 05:06:14 +000034#include "llvm/ADT/DenseMap.h"
Evan Cheng54898932008-10-29 08:39:34 +000035#include "llvm/ADT/DepthFirstIterator.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000036#include "llvm/ADT/SmallPtrSet.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000037#include "llvm/ADT/Statistic.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000038using namespace llvm;
39
Evan Chengae7fa5b2008-10-28 01:48:24 +000040static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
Owen Anderson45e68552009-01-29 05:28:55 +000041static cl::opt<int> DeadSplitLimit("dead-split-limit", cl::init(-1), cl::Hidden);
Owen Anderson323c58d2009-03-05 07:19:18 +000042static cl::opt<int> RestoreFoldLimit("restore-fold-limit", cl::init(-1), cl::Hidden);
Evan Chengae7fa5b2008-10-28 01:48:24 +000043
Owen Anderson45e68552009-01-29 05:28:55 +000044STATISTIC(NumSplits, "Number of intervals split");
Owen Anderson75fa96b2008-11-19 04:28:29 +000045STATISTIC(NumRemats, "Number of intervals split by rematerialization");
Owen Anderson7b9d67c2008-12-02 18:53:47 +000046STATISTIC(NumFolds, "Number of intervals split with spill folding");
Owen Anderson323c58d2009-03-05 07:19:18 +000047STATISTIC(NumRestoreFolds, "Number of intervals split with restore folding");
Owen Anderson2ebf63f2008-12-18 01:27:19 +000048STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
Owen Anderson956ec272009-01-23 00:23:32 +000049STATISTIC(NumDeadSpills, "Number of dead spills removed");
Evan Chengf5cd4f02008-10-23 20:43:13 +000050
Evan Cheng09e8ca82008-10-20 21:44:59 +000051namespace {
52 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
Evan Chengd0e32c52008-10-29 05:06:14 +000053 MachineFunction *CurrMF;
Evan Chengf5cd4f02008-10-23 20:43:13 +000054 const TargetMachine *TM;
55 const TargetInstrInfo *TII;
Owen Anderson3ef45492009-01-29 22:13:06 +000056 const TargetRegisterInfo* TRI;
Evan Chengf5cd4f02008-10-23 20:43:13 +000057 MachineFrameInfo *MFI;
58 MachineRegisterInfo *MRI;
59 LiveIntervals *LIs;
Evan Chengd0e32c52008-10-29 05:06:14 +000060 LiveStacks *LSs;
Owen Anderson420dd372009-03-14 21:40:05 +000061 VirtRegMap *VRM;
Evan Cheng09e8ca82008-10-20 21:44:59 +000062
Evan Chengf5cd4f02008-10-23 20:43:13 +000063 // Barrier - Current barrier being processed.
64 MachineInstr *Barrier;
65
66 // BarrierMBB - Basic block where the barrier resides in.
67 MachineBasicBlock *BarrierMBB;
68
69 // Barrier - Current barrier index.
70 unsigned BarrierIdx;
71
72 // CurrLI - Current live interval being split.
73 LiveInterval *CurrLI;
74
Evan Chengd0e32c52008-10-29 05:06:14 +000075 // CurrSLI - Current stack slot live interval.
76 LiveInterval *CurrSLI;
77
78 // CurrSValNo - Current val# for the stack slot live interval.
79 VNInfo *CurrSValNo;
80
81 // IntervalSSMap - A map from live interval to spill slots.
82 DenseMap<unsigned, int> IntervalSSMap;
Evan Chengf5cd4f02008-10-23 20:43:13 +000083
Evan Cheng54898932008-10-29 08:39:34 +000084 // Def2SpillMap - A map from a def instruction index to spill index.
85 DenseMap<unsigned, unsigned> Def2SpillMap;
Evan Cheng06587492008-10-24 02:05:00 +000086
Evan Cheng09e8ca82008-10-20 21:44:59 +000087 public:
88 static char ID;
89 PreAllocSplitting() : MachineFunctionPass(&ID) {}
90
91 virtual bool runOnMachineFunction(MachineFunction &MF);
92
93 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
94 AU.addRequired<LiveIntervals>();
95 AU.addPreserved<LiveIntervals>();
Evan Chengd0e32c52008-10-29 05:06:14 +000096 AU.addRequired<LiveStacks>();
97 AU.addPreserved<LiveStacks>();
Evan Cheng09e8ca82008-10-20 21:44:59 +000098 AU.addPreserved<RegisterCoalescer>();
99 if (StrongPHIElim)
100 AU.addPreservedID(StrongPHIEliminationID);
101 else
102 AU.addPreservedID(PHIEliminationID);
Owen Andersonf1f75b12008-11-04 22:22:41 +0000103 AU.addRequired<MachineDominatorTree>();
104 AU.addRequired<MachineLoopInfo>();
Owen Anderson420dd372009-03-14 21:40:05 +0000105 AU.addRequired<VirtRegMap>();
Owen Andersonf1f75b12008-11-04 22:22:41 +0000106 AU.addPreserved<MachineDominatorTree>();
107 AU.addPreserved<MachineLoopInfo>();
Owen Anderson420dd372009-03-14 21:40:05 +0000108 AU.addPreserved<VirtRegMap>();
Evan Cheng09e8ca82008-10-20 21:44:59 +0000109 MachineFunctionPass::getAnalysisUsage(AU);
110 }
111
112 virtual void releaseMemory() {
Evan Chengd0e32c52008-10-29 05:06:14 +0000113 IntervalSSMap.clear();
Evan Cheng54898932008-10-29 08:39:34 +0000114 Def2SpillMap.clear();
Evan Cheng09e8ca82008-10-20 21:44:59 +0000115 }
116
117 virtual const char *getPassName() const {
118 return "Pre-Register Allocaton Live Interval Splitting";
119 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000120
121 /// print - Implement the dump method.
122 virtual void print(std::ostream &O, const Module* M = 0) const {
123 LIs->print(O, M);
124 }
125
126 void print(std::ostream *O, const Module* M = 0) const {
127 if (O) print(*O, M);
128 }
129
130 private:
131 MachineBasicBlock::iterator
132 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
133 unsigned&);
134
135 MachineBasicBlock::iterator
Evan Cheng1f08cc22008-10-28 05:28:21 +0000136 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000137 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
138
139 MachineBasicBlock::iterator
Evan Chengf62ce372008-10-28 00:47:49 +0000140 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000141 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
142
Evan Chengd0e32c52008-10-29 05:06:14 +0000143 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000144
Evan Cheng54898932008-10-29 08:39:34 +0000145 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
146 unsigned&, int&) const;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000147
Evan Chengd0e32c52008-10-29 05:06:14 +0000148 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000149
Evan Chengf5cd4f02008-10-23 20:43:13 +0000150 bool SplitRegLiveInterval(LiveInterval*);
151
Owen Anderson956ec272009-01-23 00:23:32 +0000152 bool SplitRegLiveIntervals(const TargetRegisterClass **,
153 SmallPtrSet<LiveInterval*, 8>&);
Owen Andersonf1f75b12008-11-04 22:22:41 +0000154
155 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
156 MachineBasicBlock* BarrierMBB);
Owen Anderson75fa96b2008-11-19 04:28:29 +0000157 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
158 MachineInstr* DefMI,
159 MachineBasicBlock::iterator RestorePt,
160 unsigned RestoreIdx,
161 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000162 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
163 MachineInstr* DefMI,
164 MachineInstr* Barrier,
165 MachineBasicBlock* MBB,
166 int& SS,
167 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
Owen Andersonc93023a2009-03-04 08:52:31 +0000168 MachineInstr* FoldRestore(unsigned vreg,
169 const TargetRegisterClass* RC,
170 MachineInstr* Barrier,
171 MachineBasicBlock* MBB,
172 int SS,
173 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000174 void RenumberValno(VNInfo* VN);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000175 void ReconstructLiveInterval(LiveInterval* LI);
Owen Anderson956ec272009-01-23 00:23:32 +0000176 bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
Owen Anderson45e68552009-01-29 05:28:55 +0000177 unsigned getNumberOfNonSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
178 unsigned Reg, int FrameIndex, bool& TwoAddr);
Evan Cheng19a72582009-02-02 18:33:18 +0000179 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator Use,
180 MachineBasicBlock* MBB, LiveInterval* LI,
Owen Anderson200ee7f2009-01-06 07:53:32 +0000181 SmallPtrSet<MachineInstr*, 4>& Visited,
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000182 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
183 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
184 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
Owen Anderson7d211e22008-12-31 02:00:25 +0000185 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
186 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
Evan Cheng19a72582009-02-02 18:33:18 +0000187 bool IsTopLevel, bool IsIntraBlock);
188 VNInfo* PerformPHIConstructionFallBack(MachineBasicBlock::iterator Use,
189 MachineBasicBlock* MBB, LiveInterval* LI,
190 SmallPtrSet<MachineInstr*, 4>& Visited,
191 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
192 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
193 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
194 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
195 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
196 bool IsTopLevel, bool IsIntraBlock);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000197};
Evan Cheng09e8ca82008-10-20 21:44:59 +0000198} // end anonymous namespace
199
200char PreAllocSplitting::ID = 0;
201
202static RegisterPass<PreAllocSplitting>
203X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
204
205const PassInfo *const llvm::PreAllocSplittingID = &X;
206
Evan Chengf5cd4f02008-10-23 20:43:13 +0000207
208/// findNextEmptySlot - Find a gap after the given machine instruction in the
209/// instruction index map. If there isn't one, return end().
210MachineBasicBlock::iterator
211PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
212 unsigned &SpotIndex) {
213 MachineBasicBlock::iterator MII = MI;
214 if (++MII != MBB->end()) {
215 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
216 if (Index) {
217 SpotIndex = Index;
218 return MII;
219 }
220 }
221 return MBB->end();
222}
223
224/// findSpillPoint - Find a gap as far away from the given MI that's suitable
225/// for spilling the current live interval. The index must be before any
226/// defs and uses of the live interval register in the mbb. Return begin() if
227/// none is found.
228MachineBasicBlock::iterator
229PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
Evan Cheng1f08cc22008-10-28 05:28:21 +0000230 MachineInstr *DefMI,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000231 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
232 unsigned &SpillIndex) {
233 MachineBasicBlock::iterator Pt = MBB->begin();
234
Owen Anderson696a1302009-03-31 08:27:09 +0000235 MachineBasicBlock::iterator MII = MI;
236 MachineBasicBlock::iterator EndPt = DefMI
237 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
Owen Anderson4cafbb52009-02-20 10:02:23 +0000238
Owen Anderson696a1302009-03-31 08:27:09 +0000239 while (MII != EndPt && !RefsInMBB.count(MII) &&
240 MII->getOpcode() != TRI->getCallFrameSetupOpcode())
241 --MII;
242 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
Owen Anderson4cafbb52009-02-20 10:02:23 +0000243
Owen Anderson696a1302009-03-31 08:27:09 +0000244 while (MII != EndPt && !RefsInMBB.count(MII)) {
245 unsigned Index = LIs->getInstructionIndex(MII);
Owen Anderson3ef45492009-01-29 22:13:06 +0000246
Owen Anderson696a1302009-03-31 08:27:09 +0000247 // We can't insert the spill between the barrier (a call), and its
248 // corresponding call frame setup.
249 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
250 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
Owen Anderson5734c942009-02-05 05:58:41 +0000251 --MII;
Owen Anderson696a1302009-03-31 08:27:09 +0000252 if (MII == EndPt) {
253 return Pt;
Owen Anderson5734c942009-02-05 05:58:41 +0000254 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000255 }
Owen Anderson696a1302009-03-31 08:27:09 +0000256 continue;
257 } else if (LIs->hasGapBeforeInstr(Index)) {
258 Pt = MII;
259 SpillIndex = LIs->findGapBeforeInstr(Index, true);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000260 }
Owen Anderson696a1302009-03-31 08:27:09 +0000261
262 if (RefsInMBB.count(MII))
263 return Pt;
264
265
266 --MII;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000267 }
268
269 return Pt;
270}
271
272/// findRestorePoint - Find a gap in the instruction index map that's suitable
273/// for restoring the current live interval value. The index must be before any
274/// uses of the live interval register in the mbb. Return end() if none is
275/// found.
276MachineBasicBlock::iterator
277PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
Evan Chengf62ce372008-10-28 00:47:49 +0000278 unsigned LastIdx,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000279 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
280 unsigned &RestoreIndex) {
Evan Cheng54898932008-10-29 08:39:34 +0000281 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
282 // begin index accordingly.
Owen Anderson5a92d4e2008-11-18 20:53:59 +0000283 MachineBasicBlock::iterator Pt = MBB->end();
Owen Anderson696a1302009-03-31 08:27:09 +0000284 MachineBasicBlock::iterator EndPt = MBB->getFirstTerminator();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000285
Owen Anderson696a1302009-03-31 08:27:09 +0000286 // We start at the call, so walk forward until we find the call frame teardown
287 // since we can't insert restores before that. Bail if we encounter a use
288 // during this time.
289 MachineBasicBlock::iterator MII = MI;
290 if (MII == EndPt) return Pt;
291
292 while (MII != EndPt && !RefsInMBB.count(MII) &&
293 MII->getOpcode() != TRI->getCallFrameDestroyOpcode())
294 ++MII;
295 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
296 ++MII;
297
298 // FIXME: Limit the number of instructions to examine to reduce
299 // compile time?
300 while (MII != EndPt) {
301 unsigned Index = LIs->getInstructionIndex(MII);
302 if (Index > LastIdx)
303 break;
304 unsigned Gap = LIs->findGapBeforeInstr(Index);
Owen Anderson3ef45492009-01-29 22:13:06 +0000305
Owen Anderson696a1302009-03-31 08:27:09 +0000306 // We can't insert a restore between the barrier (a call) and its
307 // corresponding call frame teardown.
308 if (MII->getOpcode() == TRI->getCallFrameSetupOpcode()) {
309 do {
310 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
Owen Anderson5734c942009-02-05 05:58:41 +0000311 ++MII;
Owen Anderson696a1302009-03-31 08:27:09 +0000312 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
313 } else if (Gap) {
314 Pt = MII;
315 RestoreIndex = Gap;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000316 }
Owen Anderson696a1302009-03-31 08:27:09 +0000317
318 if (RefsInMBB.count(MII))
319 return Pt;
320
321 ++MII;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000322 }
323
324 return Pt;
325}
326
Evan Chengd0e32c52008-10-29 05:06:14 +0000327/// CreateSpillStackSlot - Create a stack slot for the live interval being
328/// split. If the live interval was previously split, just reuse the same
329/// slot.
330int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
331 const TargetRegisterClass *RC) {
332 int SS;
333 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
334 if (I != IntervalSSMap.end()) {
335 SS = I->second;
336 } else {
337 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
338 IntervalSSMap[Reg] = SS;
Evan Cheng06587492008-10-24 02:05:00 +0000339 }
Evan Chengd0e32c52008-10-29 05:06:14 +0000340
341 // Create live interval for stack slot.
Evan Chengc781a242009-05-03 18:32:42 +0000342 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
Evan Cheng54898932008-10-29 08:39:34 +0000343 if (CurrSLI->hasAtLeastOneValue())
Evan Chengd0e32c52008-10-29 05:06:14 +0000344 CurrSValNo = CurrSLI->getValNumInfo(0);
345 else
346 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
347 return SS;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000348}
349
Evan Chengd0e32c52008-10-29 05:06:14 +0000350/// IsAvailableInStack - Return true if register is available in a split stack
351/// slot at the specified index.
352bool
Evan Cheng54898932008-10-29 08:39:34 +0000353PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
354 unsigned Reg, unsigned DefIndex,
355 unsigned RestoreIndex, unsigned &SpillIndex,
356 int& SS) const {
357 if (!DefMBB)
358 return false;
359
Evan Chengd0e32c52008-10-29 05:06:14 +0000360 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
361 if (I == IntervalSSMap.end())
Evan Chengf5cd4f02008-10-23 20:43:13 +0000362 return false;
Evan Cheng54898932008-10-29 08:39:34 +0000363 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
364 if (II == Def2SpillMap.end())
365 return false;
366
367 // If last spill of def is in the same mbb as barrier mbb (where restore will
368 // be), make sure it's not below the intended restore index.
369 // FIXME: Undo the previous spill?
370 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
371 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
372 return false;
373
374 SS = I->second;
375 SpillIndex = II->second;
376 return true;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000377}
378
Evan Chengd0e32c52008-10-29 05:06:14 +0000379/// UpdateSpillSlotInterval - Given the specified val# of the register live
380/// interval being split, and the spill and restore indicies, update the live
381/// interval of the spill stack slot.
382void
383PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
384 unsigned RestoreIndex) {
Evan Cheng54898932008-10-29 08:39:34 +0000385 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
386 "Expect restore in the barrier mbb");
387
388 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
389 if (MBB == BarrierMBB) {
390 // Intra-block spill + restore. We are done.
Evan Chengd0e32c52008-10-29 05:06:14 +0000391 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
392 CurrSLI->addRange(SLR);
393 return;
394 }
395
Evan Cheng54898932008-10-29 08:39:34 +0000396 SmallPtrSet<MachineBasicBlock*, 4> Processed;
397 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
398 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000399 CurrSLI->addRange(SLR);
Evan Cheng54898932008-10-29 08:39:34 +0000400 Processed.insert(MBB);
Evan Chengd0e32c52008-10-29 05:06:14 +0000401
402 // Start from the spill mbb, figure out the extend of the spill slot's
403 // live interval.
404 SmallVector<MachineBasicBlock*, 4> WorkList;
Evan Cheng54898932008-10-29 08:39:34 +0000405 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
406 if (LR->end > EndIdx)
Evan Chengd0e32c52008-10-29 05:06:14 +0000407 // If live range extend beyond end of mbb, add successors to work list.
408 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
409 SE = MBB->succ_end(); SI != SE; ++SI)
410 WorkList.push_back(*SI);
Evan Chengd0e32c52008-10-29 05:06:14 +0000411
412 while (!WorkList.empty()) {
413 MachineBasicBlock *MBB = WorkList.back();
414 WorkList.pop_back();
Evan Cheng54898932008-10-29 08:39:34 +0000415 if (Processed.count(MBB))
416 continue;
Evan Chengd0e32c52008-10-29 05:06:14 +0000417 unsigned Idx = LIs->getMBBStartIdx(MBB);
418 LR = CurrLI->getLiveRangeContaining(Idx);
Evan Cheng54898932008-10-29 08:39:34 +0000419 if (LR && LR->valno == ValNo) {
420 EndIdx = LIs->getMBBEndIdx(MBB);
421 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
Evan Chengd0e32c52008-10-29 05:06:14 +0000422 // Spill slot live interval stops at the restore.
Evan Cheng54898932008-10-29 08:39:34 +0000423 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000424 CurrSLI->addRange(SLR);
Evan Cheng54898932008-10-29 08:39:34 +0000425 } else if (LR->end > EndIdx) {
426 // Live range extends beyond end of mbb, process successors.
427 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
428 CurrSLI->addRange(SLR);
429 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
430 SE = MBB->succ_end(); SI != SE; ++SI)
431 WorkList.push_back(*SI);
Evan Chengd0e32c52008-10-29 05:06:14 +0000432 } else {
Evan Cheng54898932008-10-29 08:39:34 +0000433 LiveRange SLR(Idx, LR->end, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000434 CurrSLI->addRange(SLR);
Evan Chengd0e32c52008-10-29 05:06:14 +0000435 }
Evan Cheng54898932008-10-29 08:39:34 +0000436 Processed.insert(MBB);
Evan Chengd0e32c52008-10-29 05:06:14 +0000437 }
438 }
439}
440
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000441/// PerformPHIConstruction - From properly set up use and def lists, use a PHI
442/// construction algorithm to compute the ranges and valnos for an interval.
Evan Cheng19a72582009-02-02 18:33:18 +0000443VNInfo*
444PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
445 MachineBasicBlock* MBB, LiveInterval* LI,
Owen Anderson200ee7f2009-01-06 07:53:32 +0000446 SmallPtrSet<MachineInstr*, 4>& Visited,
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000447 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
448 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
449 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
Owen Anderson7d211e22008-12-31 02:00:25 +0000450 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
451 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
Evan Cheng19a72582009-02-02 18:33:18 +0000452 bool IsTopLevel, bool IsIntraBlock) {
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000453 // Return memoized result if it's available.
Evan Cheng19a72582009-02-02 18:33:18 +0000454 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
455 return NewVNs[UseI];
456 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
457 return NewVNs[UseI];
458 else if (!IsIntraBlock && LiveOut.count(MBB))
Owen Anderson7d211e22008-12-31 02:00:25 +0000459 return LiveOut[MBB];
460
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000461 // Check if our block contains any uses or defs.
Owen Anderson7d211e22008-12-31 02:00:25 +0000462 bool ContainsDefs = Defs.count(MBB);
463 bool ContainsUses = Uses.count(MBB);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000464
Evan Cheng19a72582009-02-02 18:33:18 +0000465 VNInfo* RetVNI = 0;
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000466
467 // Enumerate the cases of use/def contaning blocks.
468 if (!ContainsDefs && !ContainsUses) {
Evan Cheng19a72582009-02-02 18:33:18 +0000469 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
470 NewVNs, LiveOut, Phis,
471 IsTopLevel, IsIntraBlock);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000472 } else if (ContainsDefs && !ContainsUses) {
Owen Anderson7d211e22008-12-31 02:00:25 +0000473 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000474
475 // Search for the def in this block. If we don't find it before the
476 // instruction we care about, go to the fallback case. Note that that
Owen Anderson7d211e22008-12-31 02:00:25 +0000477 // should never happen: this cannot be intrablock, so use should
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000478 // always be an end() iterator.
Evan Cheng19a72582009-02-02 18:33:18 +0000479 assert(UseI == MBB->end() && "No use marked in intrablock");
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000480
Evan Cheng19a72582009-02-02 18:33:18 +0000481 MachineBasicBlock::iterator Walker = UseI;
482 --Walker;
483 while (Walker != MBB->begin()) {
484 if (BlockDefs.count(Walker))
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000485 break;
Evan Cheng19a72582009-02-02 18:33:18 +0000486 --Walker;
487 }
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000488
489 // Once we've found it, extend its VNInfo to our instruction.
Evan Cheng19a72582009-02-02 18:33:18 +0000490 unsigned DefIndex = LIs->getInstructionIndex(Walker);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000491 DefIndex = LiveIntervals::getDefIndex(DefIndex);
Owen Anderson7d211e22008-12-31 02:00:25 +0000492 unsigned EndIndex = LIs->getMBBEndIdx(MBB);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000493
Evan Cheng19a72582009-02-02 18:33:18 +0000494 RetVNI = NewVNs[Walker];
495 LI->addRange(LiveRange(DefIndex, EndIndex+1, RetVNI));
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000496 } else if (!ContainsDefs && ContainsUses) {
Owen Anderson7d211e22008-12-31 02:00:25 +0000497 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000498
499 // Search for the use in this block that precedes the instruction we care
Evan Cheng19a72582009-02-02 18:33:18 +0000500 // about, going to the fallback case if we don't find it.
501 if (UseI == MBB->begin())
502 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
503 Uses, NewVNs, LiveOut, Phis,
504 IsTopLevel, IsIntraBlock);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000505
Evan Cheng19a72582009-02-02 18:33:18 +0000506 MachineBasicBlock::iterator Walker = UseI;
507 --Walker;
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000508 bool found = false;
Evan Cheng19a72582009-02-02 18:33:18 +0000509 while (Walker != MBB->begin()) {
510 if (BlockUses.count(Walker)) {
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000511 found = true;
512 break;
Evan Cheng19a72582009-02-02 18:33:18 +0000513 }
514 --Walker;
515 }
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000516
517 // Must check begin() too.
Duncan Sands2b7fc1e2008-12-29 08:05:02 +0000518 if (!found) {
Evan Cheng19a72582009-02-02 18:33:18 +0000519 if (BlockUses.count(Walker))
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000520 found = true;
521 else
Evan Cheng19a72582009-02-02 18:33:18 +0000522 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
523 Uses, NewVNs, LiveOut, Phis,
524 IsTopLevel, IsIntraBlock);
Duncan Sands2b7fc1e2008-12-29 08:05:02 +0000525 }
526
Evan Cheng19a72582009-02-02 18:33:18 +0000527 unsigned UseIndex = LIs->getInstructionIndex(Walker);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000528 UseIndex = LiveIntervals::getUseIndex(UseIndex);
529 unsigned EndIndex = 0;
Evan Cheng19a72582009-02-02 18:33:18 +0000530 if (IsIntraBlock) {
531 EndIndex = LIs->getInstructionIndex(UseI);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000532 EndIndex = LiveIntervals::getUseIndex(EndIndex);
533 } else
Owen Anderson7d211e22008-12-31 02:00:25 +0000534 EndIndex = LIs->getMBBEndIdx(MBB);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000535
536 // Now, recursively phi construct the VNInfo for the use we found,
537 // and then extend it to include the instruction we care about
Evan Cheng19a72582009-02-02 18:33:18 +0000538 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
539 NewVNs, LiveOut, Phis, false, true);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000540
Evan Cheng19a72582009-02-02 18:33:18 +0000541 LI->addRange(LiveRange(UseIndex, EndIndex+1, RetVNI));
Owen Andersonb4b84362009-01-26 21:57:31 +0000542
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000543 // FIXME: Need to set kills properly for inter-block stuff.
Evan Cheng19a72582009-02-02 18:33:18 +0000544 if (LI->isKill(RetVNI, UseIndex)) LI->removeKill(RetVNI, UseIndex);
545 if (IsIntraBlock)
546 LI->addKill(RetVNI, EndIndex);
547 } else if (ContainsDefs && ContainsUses) {
Owen Anderson7d211e22008-12-31 02:00:25 +0000548 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
549 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000550
551 // This case is basically a merging of the two preceding case, with the
552 // special note that checking for defs must take precedence over checking
553 // for uses, because of two-address instructions.
554
Evan Cheng19a72582009-02-02 18:33:18 +0000555 if (UseI == MBB->begin())
556 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
557 NewVNs, LiveOut, Phis,
558 IsTopLevel, IsIntraBlock);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000559
Evan Cheng19a72582009-02-02 18:33:18 +0000560 MachineBasicBlock::iterator Walker = UseI;
561 --Walker;
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000562 bool foundDef = false;
563 bool foundUse = false;
Evan Cheng19a72582009-02-02 18:33:18 +0000564 while (Walker != MBB->begin()) {
565 if (BlockDefs.count(Walker)) {
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000566 foundDef = true;
567 break;
Evan Cheng19a72582009-02-02 18:33:18 +0000568 } else if (BlockUses.count(Walker)) {
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000569 foundUse = true;
570 break;
Evan Cheng19a72582009-02-02 18:33:18 +0000571 }
572 --Walker;
573 }
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000574
575 // Must check begin() too.
Duncan Sands2b7fc1e2008-12-29 08:05:02 +0000576 if (!foundDef && !foundUse) {
Evan Cheng19a72582009-02-02 18:33:18 +0000577 if (BlockDefs.count(Walker))
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000578 foundDef = true;
Evan Cheng19a72582009-02-02 18:33:18 +0000579 else if (BlockUses.count(Walker))
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000580 foundUse = true;
581 else
Evan Cheng19a72582009-02-02 18:33:18 +0000582 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
583 Uses, NewVNs, LiveOut, Phis,
584 IsTopLevel, IsIntraBlock);
Duncan Sands2b7fc1e2008-12-29 08:05:02 +0000585 }
586
Evan Cheng19a72582009-02-02 18:33:18 +0000587 unsigned StartIndex = LIs->getInstructionIndex(Walker);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000588 StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
589 LiveIntervals::getUseIndex(StartIndex);
590 unsigned EndIndex = 0;
Evan Cheng19a72582009-02-02 18:33:18 +0000591 if (IsIntraBlock) {
592 EndIndex = LIs->getInstructionIndex(UseI);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000593 EndIndex = LiveIntervals::getUseIndex(EndIndex);
594 } else
Owen Anderson7d211e22008-12-31 02:00:25 +0000595 EndIndex = LIs->getMBBEndIdx(MBB);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000596
597 if (foundDef)
Evan Cheng19a72582009-02-02 18:33:18 +0000598 RetVNI = NewVNs[Walker];
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000599 else
Evan Cheng19a72582009-02-02 18:33:18 +0000600 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
601 NewVNs, LiveOut, Phis, false, true);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000602
Evan Cheng19a72582009-02-02 18:33:18 +0000603 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
Owen Andersonb4b84362009-01-26 21:57:31 +0000604
Evan Cheng19a72582009-02-02 18:33:18 +0000605 if (foundUse && LI->isKill(RetVNI, StartIndex))
606 LI->removeKill(RetVNI, StartIndex);
607 if (IsIntraBlock) {
608 LI->addKill(RetVNI, EndIndex);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000609 }
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000610 }
611
612 // Memoize results so we don't have to recompute them.
Evan Cheng19a72582009-02-02 18:33:18 +0000613 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
Owen Anderson200ee7f2009-01-06 07:53:32 +0000614 else {
Evan Cheng19a72582009-02-02 18:33:18 +0000615 if (!NewVNs.count(UseI))
616 NewVNs[UseI] = RetVNI;
617 Visited.insert(UseI);
Owen Anderson200ee7f2009-01-06 07:53:32 +0000618 }
619
Evan Cheng19a72582009-02-02 18:33:18 +0000620 return RetVNI;
621}
622
623/// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
624///
625VNInfo*
626PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
627 MachineBasicBlock* MBB, LiveInterval* LI,
628 SmallPtrSet<MachineInstr*, 4>& Visited,
629 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
630 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
631 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
632 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
633 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
634 bool IsTopLevel, bool IsIntraBlock) {
635 // NOTE: Because this is the fallback case from other cases, we do NOT
636 // assume that we are not intrablock here.
637 if (Phis.count(MBB)) return Phis[MBB];
638
639 unsigned StartIndex = LIs->getMBBStartIdx(MBB);
640 VNInfo *RetVNI = Phis[MBB] = LI->getNextValue(~0U, /*FIXME*/ 0,
641 LIs->getVNInfoAllocator());
642 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
643
644 // If there are no uses or defs between our starting point and the
645 // beginning of the block, then recursive perform phi construction
646 // on our predecessors.
647 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
648 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
649 PE = MBB->pred_end(); PI != PE; ++PI) {
650 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
651 Visited, Defs, Uses, NewVNs,
652 LiveOut, Phis, false, false);
653 if (Incoming != 0)
654 IncomingVNs[*PI] = Incoming;
655 }
656
657 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill) {
Owen Anderson5b93f6f2009-02-02 22:42:01 +0000658 VNInfo* OldVN = RetVNI;
659 VNInfo* NewVN = IncomingVNs.begin()->second;
660 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
661 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
662
663 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
664 LOE = LiveOut.end(); LOI != LOE; ++LOI)
665 if (LOI->second == OldVN)
666 LOI->second = MergedVN;
667 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
668 NVE = NewVNs.end(); NVI != NVE; ++NVI)
669 if (NVI->second == OldVN)
670 NVI->second = MergedVN;
671 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
672 PE = Phis.end(); PI != PE; ++PI)
673 if (PI->second == OldVN)
674 PI->second = MergedVN;
675 RetVNI = MergedVN;
Evan Cheng19a72582009-02-02 18:33:18 +0000676 } else {
677 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
678 // VNInfo to represent the joined value.
679 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
680 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
681 I->second->hasPHIKill = true;
682 unsigned KillIndex = LIs->getMBBEndIdx(I->first);
683 if (!LiveInterval::isKill(I->second, KillIndex))
684 LI->addKill(I->second, KillIndex);
685 }
686 }
687
688 unsigned EndIndex = 0;
689 if (IsIntraBlock) {
690 EndIndex = LIs->getInstructionIndex(UseI);
691 EndIndex = LiveIntervals::getUseIndex(EndIndex);
692 } else
693 EndIndex = LIs->getMBBEndIdx(MBB);
694 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
695 if (IsIntraBlock)
696 LI->addKill(RetVNI, EndIndex);
697
698 // Memoize results so we don't have to recompute them.
699 if (!IsIntraBlock)
700 LiveOut[MBB] = RetVNI;
701 else {
702 if (!NewVNs.count(UseI))
703 NewVNs[UseI] = RetVNI;
704 Visited.insert(UseI);
705 }
706
707 return RetVNI;
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000708}
709
710/// ReconstructLiveInterval - Recompute a live interval from scratch.
711void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
712 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
713
714 // Clear the old ranges and valnos;
715 LI->clear();
716
717 // Cache the uses and defs of the register
718 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
719 RegMap Defs, Uses;
720
721 // Keep track of the new VNs we're creating.
722 DenseMap<MachineInstr*, VNInfo*> NewVNs;
723 SmallPtrSet<VNInfo*, 2> PhiVNs;
724
725 // Cache defs, and create a new VNInfo for each def.
726 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
727 DE = MRI->def_end(); DI != DE; ++DI) {
728 Defs[(*DI).getParent()].insert(&*DI);
729
730 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
731 DefIdx = LiveIntervals::getDefIndex(DefIdx);
732
Owen Anderson200ee7f2009-01-06 07:53:32 +0000733 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
734
735 // If the def is a move, set the copy field.
Evan Cheng04ee5a12009-01-20 19:12:24 +0000736 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
737 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
738 if (DstReg == LI->reg)
Owen Anderson200ee7f2009-01-06 07:53:32 +0000739 NewVN->copy = &*DI;
740
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000741 NewVNs[&*DI] = NewVN;
742 }
743
744 // Cache uses as a separate pass from actually processing them.
745 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
746 UE = MRI->use_end(); UI != UE; ++UI)
747 Uses[(*UI).getParent()].insert(&*UI);
748
749 // Now, actually process every use and use a phi construction algorithm
750 // to walk from it to its reaching definitions, building VNInfos along
751 // the way.
Owen Anderson7d211e22008-12-31 02:00:25 +0000752 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
753 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
Owen Anderson200ee7f2009-01-06 07:53:32 +0000754 SmallPtrSet<MachineInstr*, 4> Visited;
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000755 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
756 UE = MRI->use_end(); UI != UE; ++UI) {
Owen Anderson200ee7f2009-01-06 07:53:32 +0000757 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
Owen Anderson7d211e22008-12-31 02:00:25 +0000758 Uses, NewVNs, LiveOut, Phis, true, true);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000759 }
Owen Andersond4f6fe52008-12-28 23:35:13 +0000760
761 // Add ranges for dead defs
762 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
763 DE = MRI->def_end(); DI != DE; ++DI) {
764 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
765 DefIdx = LiveIntervals::getDefIndex(DefIdx);
Owen Andersond4f6fe52008-12-28 23:35:13 +0000766
767 if (LI->liveAt(DefIdx)) continue;
768
769 VNInfo* DeadVN = NewVNs[&*DI];
Owen Anderson7d211e22008-12-31 02:00:25 +0000770 LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
Owen Andersond4f6fe52008-12-28 23:35:13 +0000771 LI->addKill(DeadVN, DefIdx);
772 }
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000773}
774
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000775/// RenumberValno - Split the given valno out into a new vreg, allowing it to
776/// be allocated to a different register. This function creates a new vreg,
777/// copies the valno and its live ranges over to the new vreg's interval,
778/// removes them from the old interval, and rewrites all uses and defs of
779/// the original reg to the new vreg within those ranges.
780void PreAllocSplitting::RenumberValno(VNInfo* VN) {
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000781 SmallVector<VNInfo*, 4> Stack;
782 SmallVector<VNInfo*, 4> VNsToCopy;
783 Stack.push_back(VN);
784
785 // Walk through and copy the valno we care about, and any other valnos
786 // that are two-address redefinitions of the one we care about. These
787 // will need to be rewritten as well. We also check for safety of the
788 // renumbering here, by making sure that none of the valno involved has
789 // phi kills.
790 while (!Stack.empty()) {
791 VNInfo* OldVN = Stack.back();
792 Stack.pop_back();
793
794 // Bail out if we ever encounter a valno that has a PHI kill. We can't
795 // renumber these.
796 if (OldVN->hasPHIKill) return;
797
798 VNsToCopy.push_back(OldVN);
799
800 // Locate two-address redefinitions
801 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
802 KE = OldVN->kills.end(); KI != KE; ++KI) {
803 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000804 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
805 if (DefIdx == ~0U) continue;
Bob Wilsond9df5012009-04-09 17:16:43 +0000806 if (MI->isRegTiedToUseOperand(DefIdx)) {
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000807 VNInfo* NextVN =
808 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
Owen Andersonb4b84362009-01-26 21:57:31 +0000809 if (NextVN == OldVN) continue;
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000810 Stack.push_back(NextVN);
811 }
812 }
813 }
814
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000815 // Create the new vreg
816 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
817
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000818 // Create the new live interval
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000819 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000820
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000821 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
822 VNsToCopy.end(); OI != OE; ++OI) {
823 VNInfo* OldVN = *OI;
824
825 // Copy the valno over
826 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
827 LIs->getVNInfoAllocator());
828 NewLI.copyValNumInfo(NewVN, OldVN);
829 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
830
831 // Remove the valno from the old interval
832 CurrLI->removeValNo(OldVN);
833 }
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000834
835 // Rewrite defs and uses. This is done in two stages to avoid invalidating
836 // the reg_iterator.
837 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
838
839 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
840 E = MRI->reg_end(); I != E; ++I) {
841 MachineOperand& MO = I.getOperand();
842 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
843
844 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
845 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
846 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
847 }
848
849 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
850 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
851 MachineInstr* Inst = I->first;
852 unsigned OpIdx = I->second;
853 MachineOperand& MO = Inst->getOperand(OpIdx);
854 MO.setReg(NewVReg);
855 }
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000856
Owen Anderson420dd372009-03-14 21:40:05 +0000857 // Grow the VirtRegMap, since we've created a new vreg.
858 VRM->grow();
859
Owen Anderson45e68552009-01-29 05:28:55 +0000860 // The renumbered vreg shares a stack slot with the old register.
861 if (IntervalSSMap.count(CurrLI->reg))
862 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
863
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000864 NumRenumbers++;
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000865}
866
Owen Anderson6002e992008-12-04 21:20:30 +0000867bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
868 MachineInstr* DefMI,
869 MachineBasicBlock::iterator RestorePt,
870 unsigned RestoreIdx,
871 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
872 MachineBasicBlock& MBB = *RestorePt->getParent();
873
874 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
875 unsigned KillIdx = 0;
876 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
877 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
878 else
879 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
880
881 if (KillPt == DefMI->getParent()->end())
882 return false;
883
884 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
885 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
886
Owen Andersonb4b84362009-01-26 21:57:31 +0000887 ReconstructLiveInterval(CurrLI);
888 unsigned RematIdx = LIs->getInstructionIndex(prior(RestorePt));
889 RematIdx = LiveIntervals::getDefIndex(RematIdx);
890 RenumberValno(CurrLI->findDefinedVNInfo(RematIdx));
Owen Andersone1762c92009-01-12 03:10:40 +0000891
Owen Anderson75fa96b2008-11-19 04:28:29 +0000892 ++NumSplits;
893 ++NumRemats;
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000894 return true;
895}
896
897MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
898 const TargetRegisterClass* RC,
899 MachineInstr* DefMI,
900 MachineInstr* Barrier,
901 MachineBasicBlock* MBB,
902 int& SS,
903 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
904 MachineBasicBlock::iterator Pt = MBB->begin();
905
906 // Go top down if RefsInMBB is empty.
907 if (RefsInMBB.empty())
908 return 0;
Owen Anderson75fa96b2008-11-19 04:28:29 +0000909
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000910 MachineBasicBlock::iterator FoldPt = Barrier;
911 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
912 !RefsInMBB.count(FoldPt))
913 --FoldPt;
914
915 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
916 if (OpIdx == -1)
917 return 0;
918
919 SmallVector<unsigned, 1> Ops;
920 Ops.push_back(OpIdx);
921
922 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
923 return 0;
924
925 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
926 if (I != IntervalSSMap.end()) {
927 SS = I->second;
928 } else {
Evan Chengc781a242009-05-03 18:32:42 +0000929 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000930 }
931
932 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
933 FoldPt, Ops, SS);
934
935 if (FMI) {
936 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
937 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
938 ++NumFolds;
939
940 IntervalSSMap[vreg] = SS;
Evan Chengc781a242009-05-03 18:32:42 +0000941 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000942 if (CurrSLI->hasAtLeastOneValue())
943 CurrSValNo = CurrSLI->getValNumInfo(0);
944 else
945 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
946 }
947
948 return FMI;
Owen Anderson75fa96b2008-11-19 04:28:29 +0000949}
950
Owen Andersonc93023a2009-03-04 08:52:31 +0000951MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg,
952 const TargetRegisterClass* RC,
953 MachineInstr* Barrier,
954 MachineBasicBlock* MBB,
955 int SS,
956 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
Owen Andersona2bfb542009-03-05 08:23:20 +0000957 if ((int)RestoreFoldLimit != -1 && RestoreFoldLimit == (int)NumRestoreFolds)
Owen Anderson323c58d2009-03-05 07:19:18 +0000958 return 0;
959
Owen Andersonc93023a2009-03-04 08:52:31 +0000960 // Go top down if RefsInMBB is empty.
961 if (RefsInMBB.empty())
962 return 0;
963
964 // Can't fold a restore between a call stack setup and teardown.
965 MachineBasicBlock::iterator FoldPt = Barrier;
Owen Anderson323c58d2009-03-05 07:19:18 +0000966
967 // Advance from barrier to call frame teardown.
968 while (FoldPt != MBB->getFirstTerminator() &&
969 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
970 if (RefsInMBB.count(FoldPt))
971 return 0;
Owen Andersonc93023a2009-03-04 08:52:31 +0000972
Owen Anderson323c58d2009-03-05 07:19:18 +0000973 ++FoldPt;
974 }
975
976 if (FoldPt == MBB->getFirstTerminator())
977 return 0;
978 else
979 ++FoldPt;
980
981 // Now find the restore point.
982 while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
Owen Andersonc93023a2009-03-04 08:52:31 +0000983 if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
984 while (FoldPt != MBB->getFirstTerminator() &&
985 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
986 if (RefsInMBB.count(FoldPt))
987 return 0;
988
989 ++FoldPt;
990 }
991
Owen Anderson323c58d2009-03-05 07:19:18 +0000992 if (FoldPt == MBB->getFirstTerminator())
993 return 0;
994 }
995
996 ++FoldPt;
Owen Andersonc93023a2009-03-04 08:52:31 +0000997 }
998
999 if (FoldPt == MBB->getFirstTerminator())
1000 return 0;
1001
1002 int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
1003 if (OpIdx == -1)
1004 return 0;
1005
1006 SmallVector<unsigned, 1> Ops;
1007 Ops.push_back(OpIdx);
1008
1009 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1010 return 0;
1011
1012 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1013 FoldPt, Ops, SS);
1014
1015 if (FMI) {
1016 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1017 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
Owen Anderson323c58d2009-03-05 07:19:18 +00001018 ++NumRestoreFolds;
Owen Andersonc93023a2009-03-04 08:52:31 +00001019 }
1020
1021 return FMI;
1022}
1023
Evan Chengf5cd4f02008-10-23 20:43:13 +00001024/// SplitRegLiveInterval - Split (spill and restore) the given live interval
1025/// so it would not cross the barrier that's being processed. Shrink wrap
1026/// (minimize) the live interval to the last uses.
1027bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1028 CurrLI = LI;
1029
1030 // Find live range where current interval cross the barrier.
1031 LiveInterval::iterator LR =
1032 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
1033 VNInfo *ValNo = LR->valno;
1034
1035 if (ValNo->def == ~1U) {
1036 // Defined by a dead def? How can this be?
1037 assert(0 && "Val# is defined by a dead def?");
1038 abort();
1039 }
1040
Evan Cheng06587492008-10-24 02:05:00 +00001041 MachineInstr *DefMI = (ValNo->def != ~0U)
1042 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
Evan Cheng06587492008-10-24 02:05:00 +00001043
Owen Andersond3be4622009-01-21 08:18:03 +00001044 // If this would create a new join point, do not split.
1045 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
1046 return false;
1047
Evan Chengf5cd4f02008-10-23 20:43:13 +00001048 // Find all references in the barrier mbb.
1049 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1050 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1051 E = MRI->reg_end(); I != E; ++I) {
1052 MachineInstr *RefMI = &*I;
1053 if (RefMI->getParent() == BarrierMBB)
1054 RefsInMBB.insert(RefMI);
1055 }
1056
1057 // Find a point to restore the value after the barrier.
Evan Chengb964f332009-01-26 18:33:51 +00001058 unsigned RestoreIndex = 0;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001059 MachineBasicBlock::iterator RestorePt =
Evan Chengf62ce372008-10-28 00:47:49 +00001060 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
Evan Chengf5cd4f02008-10-23 20:43:13 +00001061 if (RestorePt == BarrierMBB->end())
1062 return false;
1063
Owen Anderson75fa96b2008-11-19 04:28:29 +00001064 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1065 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1066 RestoreIndex, RefsInMBB))
1067 return true;
1068
Evan Chengf5cd4f02008-10-23 20:43:13 +00001069 // Add a spill either before the barrier or after the definition.
Evan Cheng06587492008-10-24 02:05:00 +00001070 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001071 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
Evan Chengf5cd4f02008-10-23 20:43:13 +00001072 unsigned SpillIndex = 0;
Evan Cheng06587492008-10-24 02:05:00 +00001073 MachineInstr *SpillMI = NULL;
Evan Cheng985921e2008-10-27 23:29:28 +00001074 int SS = -1;
Evan Cheng78dfef72008-10-25 00:52:41 +00001075 if (ValNo->def == ~0U) {
Evan Chengf5cd4f02008-10-23 20:43:13 +00001076 // If it's defined by a phi, we must split just before the barrier.
Owen Anderson7b9d67c2008-12-02 18:53:47 +00001077 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1078 BarrierMBB, SS, RefsInMBB))) {
1079 SpillIndex = LIs->getInstructionIndex(SpillMI);
1080 } else {
1081 MachineBasicBlock::iterator SpillPt =
1082 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1083 if (SpillPt == BarrierMBB->begin())
1084 return false; // No gap to insert spill.
1085 // Add spill.
1086
1087 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1088 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1089 SpillMI = prior(SpillPt);
1090 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1091 }
Evan Cheng54898932008-10-29 08:39:34 +00001092 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1093 RestoreIndex, SpillIndex, SS)) {
Evan Cheng78dfef72008-10-25 00:52:41 +00001094 // If it's already split, just restore the value. There is no need to spill
1095 // the def again.
Evan Chengd0e32c52008-10-29 05:06:14 +00001096 if (!DefMI)
1097 return false; // Def is dead. Do nothing.
Owen Anderson7b9d67c2008-12-02 18:53:47 +00001098
1099 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1100 BarrierMBB, SS, RefsInMBB))) {
1101 SpillIndex = LIs->getInstructionIndex(SpillMI);
Evan Cheng1f08cc22008-10-28 05:28:21 +00001102 } else {
Owen Anderson7b9d67c2008-12-02 18:53:47 +00001103 // Check if it's possible to insert a spill after the def MI.
1104 MachineBasicBlock::iterator SpillPt;
1105 if (DefMBB == BarrierMBB) {
1106 // Add spill after the def and the last use before the barrier.
1107 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1108 RefsInMBB, SpillIndex);
1109 if (SpillPt == DefMBB->begin())
1110 return false; // No gap to insert spill.
1111 } else {
1112 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1113 if (SpillPt == DefMBB->end())
1114 return false; // No gap to insert spill.
1115 }
1116 // Add spill. The store instruction kills the register if def is before
1117 // the barrier in the barrier block.
1118 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1119 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
1120 DefMBB == BarrierMBB, SS, RC);
1121 SpillMI = prior(SpillPt);
1122 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
Evan Cheng1f08cc22008-10-28 05:28:21 +00001123 }
Evan Chengf5cd4f02008-10-23 20:43:13 +00001124 }
1125
Evan Cheng54898932008-10-29 08:39:34 +00001126 // Remember def instruction index to spill index mapping.
1127 if (DefMI && SpillMI)
1128 Def2SpillMap[ValNo->def] = SpillIndex;
1129
Evan Chengf5cd4f02008-10-23 20:43:13 +00001130 // Add restore.
Owen Andersonc93023a2009-03-04 08:52:31 +00001131 bool FoldedRestore = false;
1132 if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1133 BarrierMBB, SS, RefsInMBB)) {
1134 RestorePt = LMI;
Owen Anderson323c58d2009-03-05 07:19:18 +00001135 RestoreIndex = LIs->getInstructionIndex(RestorePt);
Owen Andersonc93023a2009-03-04 08:52:31 +00001136 FoldedRestore = true;
1137 } else {
1138 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1139 MachineInstr *LoadMI = prior(RestorePt);
1140 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1141 }
Evan Chengf5cd4f02008-10-23 20:43:13 +00001142
Evan Chengd0e32c52008-10-29 05:06:14 +00001143 // Update spill stack slot live interval.
Evan Cheng54898932008-10-29 08:39:34 +00001144 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1145 LIs->getDefIndex(RestoreIndex));
Evan Chengd0e32c52008-10-29 05:06:14 +00001146
Owen Andersonb4b84362009-01-26 21:57:31 +00001147 ReconstructLiveInterval(CurrLI);
Owen Andersonc93023a2009-03-04 08:52:31 +00001148
1149 if (!FoldedRestore) {
1150 unsigned RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1151 RestoreIdx = LiveIntervals::getDefIndex(RestoreIdx);
1152 RenumberValno(CurrLI->findDefinedVNInfo(RestoreIdx));
1153 }
Owen Anderson7d211e22008-12-31 02:00:25 +00001154
Evan Chengae7fa5b2008-10-28 01:48:24 +00001155 ++NumSplits;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001156 return true;
1157}
1158
1159/// SplitRegLiveIntervals - Split all register live intervals that cross the
1160/// barrier that's being processed.
1161bool
Owen Anderson956ec272009-01-23 00:23:32 +00001162PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1163 SmallPtrSet<LiveInterval*, 8>& Split) {
Evan Chengf5cd4f02008-10-23 20:43:13 +00001164 // First find all the virtual registers whose live intervals are intercepted
1165 // by the current barrier.
1166 SmallVector<LiveInterval*, 8> Intervals;
1167 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
Evan Cheng4350eb82009-02-06 17:17:30 +00001168 // FIXME: If it's not safe to move any instruction that defines the barrier
1169 // register class, then it means there are some special dependencies which
1170 // codegen is not modelling. Ignore these barriers for now.
1171 if (!TII->isSafeToMoveRegClassDefs(*RC))
Evan Cheng23066282008-10-27 07:14:50 +00001172 continue;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001173 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1174 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1175 unsigned Reg = VRs[i];
1176 if (!LIs->hasInterval(Reg))
1177 continue;
1178 LiveInterval *LI = &LIs->getInterval(Reg);
1179 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1180 // Virtual register live interval is intercepted by the barrier. We
1181 // should split and shrink wrap its interval if possible.
1182 Intervals.push_back(LI);
1183 }
1184 }
1185
1186 // Process the affected live intervals.
1187 bool Change = false;
1188 while (!Intervals.empty()) {
Evan Chengae7fa5b2008-10-28 01:48:24 +00001189 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1190 break;
Owen Andersone1762c92009-01-12 03:10:40 +00001191 else if (NumSplits == 4)
1192 Change |= Change;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001193 LiveInterval *LI = Intervals.back();
1194 Intervals.pop_back();
Owen Anderson956ec272009-01-23 00:23:32 +00001195 bool result = SplitRegLiveInterval(LI);
1196 if (result) Split.insert(LI);
1197 Change |= result;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001198 }
1199
1200 return Change;
1201}
1202
Owen Anderson45e68552009-01-29 05:28:55 +00001203unsigned PreAllocSplitting::getNumberOfNonSpills(
Owen Anderson32ca8652009-01-24 10:07:43 +00001204 SmallPtrSet<MachineInstr*, 4>& MIs,
Owen Anderson45e68552009-01-29 05:28:55 +00001205 unsigned Reg, int FrameIndex,
1206 bool& FeedsTwoAddr) {
1207 unsigned NonSpills = 0;
Owen Anderson32ca8652009-01-24 10:07:43 +00001208 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
Owen Anderson45e68552009-01-29 05:28:55 +00001209 UI != UE; ++UI) {
Owen Anderson32ca8652009-01-24 10:07:43 +00001210 int StoreFrameIndex;
1211 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
Owen Anderson45e68552009-01-29 05:28:55 +00001212 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1213 NonSpills++;
1214
1215 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
Bob Wilsond9df5012009-04-09 17:16:43 +00001216 if (DefIdx != -1 && (*UI)->isRegTiedToUseOperand(DefIdx))
Owen Anderson45e68552009-01-29 05:28:55 +00001217 FeedsTwoAddr = true;
Owen Anderson32ca8652009-01-24 10:07:43 +00001218 }
1219
Owen Anderson45e68552009-01-29 05:28:55 +00001220 return NonSpills;
Owen Anderson32ca8652009-01-24 10:07:43 +00001221}
1222
Owen Anderson956ec272009-01-23 00:23:32 +00001223/// removeDeadSpills - After doing splitting, filter through all intervals we've
1224/// split, and see if any of the spills are unnecessary. If so, remove them.
1225bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1226 bool changed = false;
1227
Owen Anderson4bfc2092009-01-29 05:41:02 +00001228 // Walk over all of the live intervals that were touched by the splitter,
1229 // and see if we can do any DCE and/or folding.
Owen Anderson956ec272009-01-23 00:23:32 +00001230 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1231 LE = split.end(); LI != LE; ++LI) {
Owen Anderson9ce499a2009-01-23 03:28:53 +00001232 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
Owen Anderson956ec272009-01-23 00:23:32 +00001233
Owen Anderson4bfc2092009-01-29 05:41:02 +00001234 // First, collect all the uses of the vreg, and sort them by their
1235 // reaching definition (VNInfo).
Owen Anderson956ec272009-01-23 00:23:32 +00001236 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1237 UE = MRI->use_end(); UI != UE; ++UI) {
1238 unsigned index = LIs->getInstructionIndex(&*UI);
1239 index = LiveIntervals::getUseIndex(index);
1240
1241 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
Owen Anderson9ce499a2009-01-23 03:28:53 +00001242 VNUseCount[LR->valno].insert(&*UI);
Owen Anderson956ec272009-01-23 00:23:32 +00001243 }
1244
Owen Anderson4bfc2092009-01-29 05:41:02 +00001245 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1246 // and/or fold them away.
Owen Anderson956ec272009-01-23 00:23:32 +00001247 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1248 VE = (*LI)->vni_end(); VI != VE; ++VI) {
Owen Anderson45e68552009-01-29 05:28:55 +00001249
1250 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1251 return changed;
1252
Owen Anderson956ec272009-01-23 00:23:32 +00001253 VNInfo* CurrVN = *VI;
Owen Anderson4bfc2092009-01-29 05:41:02 +00001254
1255 // We don't currently try to handle definitions with PHI kills, because
1256 // it would involve processing more than one VNInfo at once.
Owen Anderson956ec272009-01-23 00:23:32 +00001257 if (CurrVN->hasPHIKill) continue;
Owen Anderson956ec272009-01-23 00:23:32 +00001258
Owen Anderson4bfc2092009-01-29 05:41:02 +00001259 // We also don't try to handle the results of PHI joins, since there's
1260 // no defining instruction to analyze.
Owen Anderson956ec272009-01-23 00:23:32 +00001261 unsigned DefIdx = CurrVN->def;
1262 if (DefIdx == ~0U || DefIdx == ~1U) continue;
Owen Anderson9ce499a2009-01-23 03:28:53 +00001263
Owen Anderson4bfc2092009-01-29 05:41:02 +00001264 // We're only interested in eliminating cruft introduced by the splitter,
1265 // is of the form load-use or load-use-store. First, check that the
1266 // definition is a load, and remember what stack slot we loaded it from.
Owen Anderson956ec272009-01-23 00:23:32 +00001267 MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
1268 int FrameIndex;
1269 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1270
Owen Anderson4bfc2092009-01-29 05:41:02 +00001271 // If the definition has no uses at all, just DCE it.
Owen Anderson9ce499a2009-01-23 03:28:53 +00001272 if (VNUseCount[CurrVN].size() == 0) {
1273 LIs->RemoveMachineInstrFromMaps(DefMI);
1274 (*LI)->removeValNo(CurrVN);
1275 DefMI->eraseFromParent();
Owen Andersonc0f3a032009-01-29 08:22:06 +00001276 VNUseCount.erase(CurrVN);
Owen Anderson9ce499a2009-01-23 03:28:53 +00001277 NumDeadSpills++;
1278 changed = true;
Owen Anderson32ca8652009-01-24 10:07:43 +00001279 continue;
Owen Anderson9ce499a2009-01-23 03:28:53 +00001280 }
Owen Anderson32ca8652009-01-24 10:07:43 +00001281
Owen Anderson4bfc2092009-01-29 05:41:02 +00001282 // Second, get the number of non-store uses of the definition, as well as
1283 // a flag indicating whether it feeds into a later two-address definition.
Owen Anderson45e68552009-01-29 05:28:55 +00001284 bool FeedsTwoAddr = false;
1285 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1286 (*LI)->reg, FrameIndex,
1287 FeedsTwoAddr);
1288
Owen Anderson4bfc2092009-01-29 05:41:02 +00001289 // If there's one non-store use and it doesn't feed a two-addr, then
1290 // this is a load-use-store case that we can try to fold.
Owen Anderson45e68552009-01-29 05:28:55 +00001291 if (NonSpillCount == 1 && !FeedsTwoAddr) {
Owen Anderson4bfc2092009-01-29 05:41:02 +00001292 // Start by finding the non-store use MachineInstr.
Owen Anderson45e68552009-01-29 05:28:55 +00001293 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1294 int StoreFrameIndex;
1295 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1296 while (UI != VNUseCount[CurrVN].end() &&
1297 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1298 ++UI;
1299 if (UI != VNUseCount[CurrVN].end())
1300 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1301 }
Owen Anderson45e68552009-01-29 05:28:55 +00001302 if (UI == VNUseCount[CurrVN].end()) continue;
1303
1304 MachineInstr* use = *UI;
1305
Owen Anderson4bfc2092009-01-29 05:41:02 +00001306 // Attempt to fold it away!
Owen Anderson45e68552009-01-29 05:28:55 +00001307 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1308 if (OpIdx == -1) continue;
Owen Anderson45e68552009-01-29 05:28:55 +00001309 SmallVector<unsigned, 1> Ops;
1310 Ops.push_back(OpIdx);
Owen Anderson45e68552009-01-29 05:28:55 +00001311 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1312
1313 MachineInstr* NewMI =
1314 TII->foldMemoryOperand(*use->getParent()->getParent(),
1315 use, Ops, FrameIndex);
1316
1317 if (!NewMI) continue;
1318
Owen Anderson4bfc2092009-01-29 05:41:02 +00001319 // Update relevant analyses.
Owen Anderson45e68552009-01-29 05:28:55 +00001320 LIs->RemoveMachineInstrFromMaps(DefMI);
1321 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1322 (*LI)->removeValNo(CurrVN);
1323
1324 DefMI->eraseFromParent();
1325 MachineBasicBlock* MBB = use->getParent();
1326 NewMI = MBB->insert(MBB->erase(use), NewMI);
1327 VNUseCount[CurrVN].erase(use);
1328
Owen Anderson4bfc2092009-01-29 05:41:02 +00001329 // Remove deleted instructions. Note that we need to remove them from
1330 // the VNInfo->use map as well, just to be safe.
Owen Anderson45e68552009-01-29 05:28:55 +00001331 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1332 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1333 II != IE; ++II) {
Owen Anderson4bfc2092009-01-29 05:41:02 +00001334 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
Owen Andersonc0f3a032009-01-29 08:22:06 +00001335 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1336 ++VNI)
1337 if (VNI->first != CurrVN)
1338 VNI->second.erase(*II);
Owen Anderson45e68552009-01-29 05:28:55 +00001339 LIs->RemoveMachineInstrFromMaps(*II);
1340 (*II)->eraseFromParent();
1341 }
Owen Andersonc0f3a032009-01-29 08:22:06 +00001342
1343 VNUseCount.erase(CurrVN);
Owen Anderson45e68552009-01-29 05:28:55 +00001344
1345 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1346 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1347 if (VI->second.erase(use))
1348 VI->second.insert(NewMI);
1349
1350 NumDeadSpills++;
1351 changed = true;
1352 continue;
1353 }
1354
Owen Anderson4bfc2092009-01-29 05:41:02 +00001355 // If there's more than one non-store instruction, we can't profitably
1356 // fold it, so bail.
Owen Anderson45e68552009-01-29 05:28:55 +00001357 if (NonSpillCount) continue;
Owen Anderson32ca8652009-01-24 10:07:43 +00001358
Owen Anderson4bfc2092009-01-29 05:41:02 +00001359 // Otherwise, this is a load-store case, so DCE them.
Owen Anderson32ca8652009-01-24 10:07:43 +00001360 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1361 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1362 UI != UI; ++UI) {
1363 LIs->RemoveMachineInstrFromMaps(*UI);
1364 (*UI)->eraseFromParent();
1365 }
1366
Owen Andersonc0f3a032009-01-29 08:22:06 +00001367 VNUseCount.erase(CurrVN);
1368
Owen Anderson32ca8652009-01-24 10:07:43 +00001369 LIs->RemoveMachineInstrFromMaps(DefMI);
1370 (*LI)->removeValNo(CurrVN);
1371 DefMI->eraseFromParent();
1372 NumDeadSpills++;
1373 changed = true;
Owen Anderson956ec272009-01-23 00:23:32 +00001374 }
1375 }
1376
1377 return changed;
1378}
1379
Owen Andersonf1f75b12008-11-04 22:22:41 +00001380bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1381 MachineBasicBlock* DefMBB,
1382 MachineBasicBlock* BarrierMBB) {
1383 if (DefMBB == BarrierMBB)
1384 return false;
1385
1386 if (LR->valno->hasPHIKill)
1387 return false;
1388
1389 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1390 if (LR->end < MBBEnd)
1391 return false;
1392
1393 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1394 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1395 return true;
1396
1397 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1398 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1399 typedef std::pair<MachineBasicBlock*,
1400 MachineBasicBlock::succ_iterator> ItPair;
1401 SmallVector<ItPair, 4> Stack;
1402 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1403
1404 while (!Stack.empty()) {
1405 ItPair P = Stack.back();
1406 Stack.pop_back();
1407
1408 MachineBasicBlock* PredMBB = P.first;
1409 MachineBasicBlock::succ_iterator S = P.second;
1410
1411 if (S == PredMBB->succ_end())
1412 continue;
1413 else if (Visited.count(*S)) {
1414 Stack.push_back(std::make_pair(PredMBB, ++S));
1415 continue;
1416 } else
Owen Andersonb214c692008-11-05 00:32:13 +00001417 Stack.push_back(std::make_pair(PredMBB, S+1));
Owen Andersonf1f75b12008-11-04 22:22:41 +00001418
1419 MachineBasicBlock* MBB = *S;
1420 Visited.insert(MBB);
1421
1422 if (MBB == BarrierMBB)
1423 return true;
1424
1425 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1426 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1427 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1428 while (MDTN) {
1429 if (MDTN == DefMDTN)
1430 return true;
1431 else if (MDTN == BarrierMDTN)
1432 break;
1433 MDTN = MDTN->getIDom();
1434 }
1435
1436 MBBEnd = LIs->getMBBEndIdx(MBB);
1437 if (LR->end > MBBEnd)
1438 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1439 }
1440
1441 return false;
1442}
1443
1444
Evan Cheng09e8ca82008-10-20 21:44:59 +00001445bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd0e32c52008-10-29 05:06:14 +00001446 CurrMF = &MF;
1447 TM = &MF.getTarget();
Owen Anderson3ef45492009-01-29 22:13:06 +00001448 TRI = TM->getRegisterInfo();
Evan Chengd0e32c52008-10-29 05:06:14 +00001449 TII = TM->getInstrInfo();
1450 MFI = MF.getFrameInfo();
1451 MRI = &MF.getRegInfo();
1452 LIs = &getAnalysis<LiveIntervals>();
1453 LSs = &getAnalysis<LiveStacks>();
Owen Anderson420dd372009-03-14 21:40:05 +00001454 VRM = &getAnalysis<VirtRegMap>();
Evan Chengf5cd4f02008-10-23 20:43:13 +00001455
1456 bool MadeChange = false;
1457
1458 // Make sure blocks are numbered in order.
1459 MF.RenumberBlocks();
1460
Evan Cheng54898932008-10-29 08:39:34 +00001461 MachineBasicBlock *Entry = MF.begin();
1462 SmallPtrSet<MachineBasicBlock*,16> Visited;
1463
Owen Anderson956ec272009-01-23 00:23:32 +00001464 SmallPtrSet<LiveInterval*, 8> Split;
1465
Evan Cheng54898932008-10-29 08:39:34 +00001466 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1467 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1468 DFI != E; ++DFI) {
1469 BarrierMBB = *DFI;
1470 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1471 E = BarrierMBB->end(); I != E; ++I) {
1472 Barrier = &*I;
1473 const TargetRegisterClass **BarrierRCs =
1474 Barrier->getDesc().getRegClassBarriers();
1475 if (!BarrierRCs)
1476 continue;
1477 BarrierIdx = LIs->getInstructionIndex(Barrier);
Owen Anderson956ec272009-01-23 00:23:32 +00001478 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
Evan Cheng54898932008-10-29 08:39:34 +00001479 }
1480 }
Evan Chengf5cd4f02008-10-23 20:43:13 +00001481
Owen Anderson956ec272009-01-23 00:23:32 +00001482 MadeChange |= removeDeadSpills(Split);
1483
Evan Chengf5cd4f02008-10-23 20:43:13 +00001484 return MadeChange;
Evan Cheng09e8ca82008-10-20 21:44:59 +00001485}