blob: 5abe135109f2f7f3c6e7b1ae71a79e17145da584 [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"
18#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Evan Chengd0e32c52008-10-29 05:06:14 +000019#include "llvm/CodeGen/LiveStackAnalysis.h"
Owen Andersonf1f75b12008-11-04 22:22:41 +000020#include "llvm/CodeGen/MachineDominators.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000021#include "llvm/CodeGen/MachineFrameInfo.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineLoopInfo.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/Passes.h"
26#include "llvm/CodeGen/RegisterCoalescer.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000027#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000028#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetOptions.h"
30#include "llvm/Target/TargetRegisterInfo.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
Evan Chengd0e32c52008-10-29 05:06:14 +000033#include "llvm/ADT/DenseMap.h"
Evan Cheng54898932008-10-29 08:39:34 +000034#include "llvm/ADT/DepthFirstIterator.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000035#include "llvm/ADT/SmallPtrSet.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000036#include "llvm/ADT/Statistic.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000037using namespace llvm;
38
Evan Chengae7fa5b2008-10-28 01:48:24 +000039static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
40
41STATISTIC(NumSplits, "Number of intervals split");
Owen Anderson75fa96b2008-11-19 04:28:29 +000042STATISTIC(NumRemats, "Number of intervals split by rematerialization");
Owen Anderson7b9d67c2008-12-02 18:53:47 +000043STATISTIC(NumFolds, "Number of intervals split with spill folding");
Owen Anderson2ebf63f2008-12-18 01:27:19 +000044STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
Evan Chengf5cd4f02008-10-23 20:43:13 +000045
Evan Cheng09e8ca82008-10-20 21:44:59 +000046namespace {
47 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
Evan Chengd0e32c52008-10-29 05:06:14 +000048 MachineFunction *CurrMF;
Evan Chengf5cd4f02008-10-23 20:43:13 +000049 const TargetMachine *TM;
50 const TargetInstrInfo *TII;
51 MachineFrameInfo *MFI;
52 MachineRegisterInfo *MRI;
53 LiveIntervals *LIs;
Evan Chengd0e32c52008-10-29 05:06:14 +000054 LiveStacks *LSs;
Evan Cheng09e8ca82008-10-20 21:44:59 +000055
Evan Chengf5cd4f02008-10-23 20:43:13 +000056 // Barrier - Current barrier being processed.
57 MachineInstr *Barrier;
58
59 // BarrierMBB - Basic block where the barrier resides in.
60 MachineBasicBlock *BarrierMBB;
61
62 // Barrier - Current barrier index.
63 unsigned BarrierIdx;
64
65 // CurrLI - Current live interval being split.
66 LiveInterval *CurrLI;
67
Evan Chengd0e32c52008-10-29 05:06:14 +000068 // CurrSLI - Current stack slot live interval.
69 LiveInterval *CurrSLI;
70
71 // CurrSValNo - Current val# for the stack slot live interval.
72 VNInfo *CurrSValNo;
73
74 // IntervalSSMap - A map from live interval to spill slots.
75 DenseMap<unsigned, int> IntervalSSMap;
Evan Chengf5cd4f02008-10-23 20:43:13 +000076
Evan Cheng54898932008-10-29 08:39:34 +000077 // Def2SpillMap - A map from a def instruction index to spill index.
78 DenseMap<unsigned, unsigned> Def2SpillMap;
Evan Cheng06587492008-10-24 02:05:00 +000079
Evan Cheng09e8ca82008-10-20 21:44:59 +000080 public:
81 static char ID;
82 PreAllocSplitting() : MachineFunctionPass(&ID) {}
83
84 virtual bool runOnMachineFunction(MachineFunction &MF);
85
86 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87 AU.addRequired<LiveIntervals>();
88 AU.addPreserved<LiveIntervals>();
Evan Chengd0e32c52008-10-29 05:06:14 +000089 AU.addRequired<LiveStacks>();
90 AU.addPreserved<LiveStacks>();
Evan Cheng09e8ca82008-10-20 21:44:59 +000091 AU.addPreserved<RegisterCoalescer>();
92 if (StrongPHIElim)
93 AU.addPreservedID(StrongPHIEliminationID);
94 else
95 AU.addPreservedID(PHIEliminationID);
Owen Andersonf1f75b12008-11-04 22:22:41 +000096 AU.addRequired<MachineDominatorTree>();
97 AU.addRequired<MachineLoopInfo>();
98 AU.addPreserved<MachineDominatorTree>();
99 AU.addPreserved<MachineLoopInfo>();
Evan Cheng09e8ca82008-10-20 21:44:59 +0000100 MachineFunctionPass::getAnalysisUsage(AU);
101 }
102
103 virtual void releaseMemory() {
Evan Chengd0e32c52008-10-29 05:06:14 +0000104 IntervalSSMap.clear();
Evan Cheng54898932008-10-29 08:39:34 +0000105 Def2SpillMap.clear();
Evan Cheng09e8ca82008-10-20 21:44:59 +0000106 }
107
108 virtual const char *getPassName() const {
109 return "Pre-Register Allocaton Live Interval Splitting";
110 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000111
112 /// print - Implement the dump method.
113 virtual void print(std::ostream &O, const Module* M = 0) const {
114 LIs->print(O, M);
115 }
116
117 void print(std::ostream *O, const Module* M = 0) const {
118 if (O) print(*O, M);
119 }
120
121 private:
122 MachineBasicBlock::iterator
123 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
124 unsigned&);
125
126 MachineBasicBlock::iterator
Evan Cheng1f08cc22008-10-28 05:28:21 +0000127 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000128 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
129
130 MachineBasicBlock::iterator
Evan Chengf62ce372008-10-28 00:47:49 +0000131 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000132 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
133
Evan Chengd0e32c52008-10-29 05:06:14 +0000134 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000135
Evan Cheng54898932008-10-29 08:39:34 +0000136 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
137 unsigned&, int&) const;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000138
Evan Chengd0e32c52008-10-29 05:06:14 +0000139 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000140
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000141 VNInfo* UpdateRegisterInterval(VNInfo*, unsigned, unsigned);
Evan Chengd0e32c52008-10-29 05:06:14 +0000142
143 bool ShrinkWrapToLastUse(MachineBasicBlock*, VNInfo*,
Evan Cheng06587492008-10-24 02:05:00 +0000144 SmallVector<MachineOperand*, 4>&,
145 SmallPtrSet<MachineInstr*, 4>&);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000146
Evan Chengaaf510c2008-10-26 07:49:03 +0000147 void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000148 MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
Evan Cheng06587492008-10-24 02:05:00 +0000149 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
150 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
151 SmallVector<MachineBasicBlock*, 4>&);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000152
153 bool SplitRegLiveInterval(LiveInterval*);
154
155 bool SplitRegLiveIntervals(const TargetRegisterClass **);
Owen Andersonf1f75b12008-11-04 22:22:41 +0000156
Owen Anderson6002e992008-12-04 21:20:30 +0000157 void RepairLiveInterval(LiveInterval* CurrLI, VNInfo* ValNo,
158 MachineInstr* DefMI, unsigned RestoreIdx);
159
Owen Andersonf1f75b12008-11-04 22:22:41 +0000160 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
161 MachineBasicBlock* BarrierMBB);
Owen Anderson75fa96b2008-11-19 04:28:29 +0000162 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
163 MachineInstr* DefMI,
164 MachineBasicBlock::iterator RestorePt,
165 unsigned RestoreIdx,
166 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000167 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
168 MachineInstr* DefMI,
169 MachineInstr* Barrier,
170 MachineBasicBlock* MBB,
171 int& SS,
172 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000173 void RenumberValno(VNInfo* VN);
Evan Cheng09e8ca82008-10-20 21:44:59 +0000174 };
175} // end anonymous namespace
176
177char PreAllocSplitting::ID = 0;
178
179static RegisterPass<PreAllocSplitting>
180X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
181
182const PassInfo *const llvm::PreAllocSplittingID = &X;
183
Evan Chengf5cd4f02008-10-23 20:43:13 +0000184
185/// findNextEmptySlot - Find a gap after the given machine instruction in the
186/// instruction index map. If there isn't one, return end().
187MachineBasicBlock::iterator
188PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
189 unsigned &SpotIndex) {
190 MachineBasicBlock::iterator MII = MI;
191 if (++MII != MBB->end()) {
192 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
193 if (Index) {
194 SpotIndex = Index;
195 return MII;
196 }
197 }
198 return MBB->end();
199}
200
201/// findSpillPoint - Find a gap as far away from the given MI that's suitable
202/// for spilling the current live interval. The index must be before any
203/// defs and uses of the live interval register in the mbb. Return begin() if
204/// none is found.
205MachineBasicBlock::iterator
206PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
Evan Cheng1f08cc22008-10-28 05:28:21 +0000207 MachineInstr *DefMI,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000208 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
209 unsigned &SpillIndex) {
210 MachineBasicBlock::iterator Pt = MBB->begin();
211
212 // Go top down if RefsInMBB is empty.
Evan Cheng1f08cc22008-10-28 05:28:21 +0000213 if (RefsInMBB.empty() && !DefMI) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000214 MachineBasicBlock::iterator MII = MBB->begin();
215 MachineBasicBlock::iterator EndPt = MI;
216 do {
217 ++MII;
218 unsigned Index = LIs->getInstructionIndex(MII);
219 unsigned Gap = LIs->findGapBeforeInstr(Index);
220 if (Gap) {
221 Pt = MII;
222 SpillIndex = Gap;
223 break;
224 }
225 } while (MII != EndPt);
226 } else {
227 MachineBasicBlock::iterator MII = MI;
Evan Cheng1f08cc22008-10-28 05:28:21 +0000228 MachineBasicBlock::iterator EndPt = DefMI
229 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
230 while (MII != EndPt && !RefsInMBB.count(MII)) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000231 unsigned Index = LIs->getInstructionIndex(MII);
232 if (LIs->hasGapBeforeInstr(Index)) {
233 Pt = MII;
234 SpillIndex = LIs->findGapBeforeInstr(Index, true);
235 }
236 --MII;
237 }
238 }
239
240 return Pt;
241}
242
243/// findRestorePoint - Find a gap in the instruction index map that's suitable
244/// for restoring the current live interval value. The index must be before any
245/// uses of the live interval register in the mbb. Return end() if none is
246/// found.
247MachineBasicBlock::iterator
248PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
Evan Chengf62ce372008-10-28 00:47:49 +0000249 unsigned LastIdx,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000250 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
251 unsigned &RestoreIndex) {
Evan Cheng54898932008-10-29 08:39:34 +0000252 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
253 // begin index accordingly.
Owen Anderson5a92d4e2008-11-18 20:53:59 +0000254 MachineBasicBlock::iterator Pt = MBB->end();
Evan Chengf62ce372008-10-28 00:47:49 +0000255 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000256
Evan Chengf62ce372008-10-28 00:47:49 +0000257 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
258 // the last index in the live range.
259 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
Owen Anderson711fd3d2008-11-13 21:53:14 +0000260 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000261 MachineBasicBlock::iterator EndPt = MI;
Evan Cheng54898932008-10-29 08:39:34 +0000262 --MII;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000263 do {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000264 unsigned Index = LIs->getInstructionIndex(MII);
Evan Cheng56ab0de2008-10-24 18:46:44 +0000265 unsigned Gap = LIs->findGapBeforeInstr(Index);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000266 if (Gap) {
267 Pt = MII;
268 RestoreIndex = Gap;
269 break;
270 }
Evan Cheng54898932008-10-29 08:39:34 +0000271 --MII;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000272 } while (MII != EndPt);
273 } else {
274 MachineBasicBlock::iterator MII = MI;
275 MII = ++MII;
Evan Chengf62ce372008-10-28 00:47:49 +0000276 // FIXME: Limit the number of instructions to examine to reduce
277 // compile time?
Evan Chengf5cd4f02008-10-23 20:43:13 +0000278 while (MII != MBB->end()) {
279 unsigned Index = LIs->getInstructionIndex(MII);
Evan Chengf62ce372008-10-28 00:47:49 +0000280 if (Index > LastIdx)
281 break;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000282 unsigned Gap = LIs->findGapBeforeInstr(Index);
283 if (Gap) {
284 Pt = MII;
285 RestoreIndex = Gap;
286 }
287 if (RefsInMBB.count(MII))
288 break;
289 ++MII;
290 }
291 }
292
293 return Pt;
294}
295
Evan Chengd0e32c52008-10-29 05:06:14 +0000296/// CreateSpillStackSlot - Create a stack slot for the live interval being
297/// split. If the live interval was previously split, just reuse the same
298/// slot.
299int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
300 const TargetRegisterClass *RC) {
301 int SS;
302 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
303 if (I != IntervalSSMap.end()) {
304 SS = I->second;
305 } else {
306 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
307 IntervalSSMap[Reg] = SS;
Evan Cheng06587492008-10-24 02:05:00 +0000308 }
Evan Chengd0e32c52008-10-29 05:06:14 +0000309
310 // Create live interval for stack slot.
311 CurrSLI = &LSs->getOrCreateInterval(SS);
Evan Cheng54898932008-10-29 08:39:34 +0000312 if (CurrSLI->hasAtLeastOneValue())
Evan Chengd0e32c52008-10-29 05:06:14 +0000313 CurrSValNo = CurrSLI->getValNumInfo(0);
314 else
315 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
316 return SS;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000317}
318
Evan Chengd0e32c52008-10-29 05:06:14 +0000319/// IsAvailableInStack - Return true if register is available in a split stack
320/// slot at the specified index.
321bool
Evan Cheng54898932008-10-29 08:39:34 +0000322PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
323 unsigned Reg, unsigned DefIndex,
324 unsigned RestoreIndex, unsigned &SpillIndex,
325 int& SS) const {
326 if (!DefMBB)
327 return false;
328
Evan Chengd0e32c52008-10-29 05:06:14 +0000329 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
330 if (I == IntervalSSMap.end())
Evan Chengf5cd4f02008-10-23 20:43:13 +0000331 return false;
Evan Cheng54898932008-10-29 08:39:34 +0000332 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
333 if (II == Def2SpillMap.end())
334 return false;
335
336 // If last spill of def is in the same mbb as barrier mbb (where restore will
337 // be), make sure it's not below the intended restore index.
338 // FIXME: Undo the previous spill?
339 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
340 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
341 return false;
342
343 SS = I->second;
344 SpillIndex = II->second;
345 return true;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000346}
347
Evan Chengd0e32c52008-10-29 05:06:14 +0000348/// UpdateSpillSlotInterval - Given the specified val# of the register live
349/// interval being split, and the spill and restore indicies, update the live
350/// interval of the spill stack slot.
351void
352PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
353 unsigned RestoreIndex) {
Evan Cheng54898932008-10-29 08:39:34 +0000354 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
355 "Expect restore in the barrier mbb");
356
357 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
358 if (MBB == BarrierMBB) {
359 // Intra-block spill + restore. We are done.
Evan Chengd0e32c52008-10-29 05:06:14 +0000360 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
361 CurrSLI->addRange(SLR);
362 return;
363 }
364
Evan Cheng54898932008-10-29 08:39:34 +0000365 SmallPtrSet<MachineBasicBlock*, 4> Processed;
366 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
367 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000368 CurrSLI->addRange(SLR);
Evan Cheng54898932008-10-29 08:39:34 +0000369 Processed.insert(MBB);
Evan Chengd0e32c52008-10-29 05:06:14 +0000370
371 // Start from the spill mbb, figure out the extend of the spill slot's
372 // live interval.
373 SmallVector<MachineBasicBlock*, 4> WorkList;
Evan Cheng54898932008-10-29 08:39:34 +0000374 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
375 if (LR->end > EndIdx)
Evan Chengd0e32c52008-10-29 05:06:14 +0000376 // If live range extend beyond end of mbb, add successors to work list.
377 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
378 SE = MBB->succ_end(); SI != SE; ++SI)
379 WorkList.push_back(*SI);
Evan Chengd0e32c52008-10-29 05:06:14 +0000380
381 while (!WorkList.empty()) {
382 MachineBasicBlock *MBB = WorkList.back();
383 WorkList.pop_back();
Evan Cheng54898932008-10-29 08:39:34 +0000384 if (Processed.count(MBB))
385 continue;
Evan Chengd0e32c52008-10-29 05:06:14 +0000386 unsigned Idx = LIs->getMBBStartIdx(MBB);
387 LR = CurrLI->getLiveRangeContaining(Idx);
Evan Cheng54898932008-10-29 08:39:34 +0000388 if (LR && LR->valno == ValNo) {
389 EndIdx = LIs->getMBBEndIdx(MBB);
390 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
Evan Chengd0e32c52008-10-29 05:06:14 +0000391 // Spill slot live interval stops at the restore.
Evan Cheng54898932008-10-29 08:39:34 +0000392 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000393 CurrSLI->addRange(SLR);
Evan Cheng54898932008-10-29 08:39:34 +0000394 } else if (LR->end > EndIdx) {
395 // Live range extends beyond end of mbb, process successors.
396 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
397 CurrSLI->addRange(SLR);
398 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
399 SE = MBB->succ_end(); SI != SE; ++SI)
400 WorkList.push_back(*SI);
Evan Chengd0e32c52008-10-29 05:06:14 +0000401 } else {
Evan Cheng54898932008-10-29 08:39:34 +0000402 LiveRange SLR(Idx, LR->end, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000403 CurrSLI->addRange(SLR);
Evan Chengd0e32c52008-10-29 05:06:14 +0000404 }
Evan Cheng54898932008-10-29 08:39:34 +0000405 Processed.insert(MBB);
Evan Chengd0e32c52008-10-29 05:06:14 +0000406 }
407 }
408}
409
410/// UpdateRegisterInterval - Given the specified val# of the current live
411/// interval is being split, and the spill and restore indices, update the live
Evan Chengf5cd4f02008-10-23 20:43:13 +0000412/// interval accordingly.
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000413VNInfo*
Evan Chengd0e32c52008-10-29 05:06:14 +0000414PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
415 unsigned RestoreIndex) {
Evan Cheng54898932008-10-29 08:39:34 +0000416 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
417 "Expect restore in the barrier mbb");
418
Evan Chengf5cd4f02008-10-23 20:43:13 +0000419 SmallVector<std::pair<unsigned,unsigned>, 4> Before;
420 SmallVector<std::pair<unsigned,unsigned>, 4> After;
421 SmallVector<unsigned, 4> BeforeKills;
422 SmallVector<unsigned, 4> AfterKills;
423 SmallPtrSet<const LiveRange*, 4> Processed;
424
425 // First, let's figure out which parts of the live interval is now defined
426 // by the restore, which are defined by the original definition.
Evan Chengd0e32c52008-10-29 05:06:14 +0000427 const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
428 After.push_back(std::make_pair(RestoreIndex, LR->end));
Evan Cheng06587492008-10-24 02:05:00 +0000429 if (CurrLI->isKill(ValNo, LR->end))
430 AfterKills.push_back(LR->end);
431
Evan Chengd0e32c52008-10-29 05:06:14 +0000432 assert(LR->contains(SpillIndex));
433 if (SpillIndex > LR->start) {
434 Before.push_back(std::make_pair(LR->start, SpillIndex));
435 BeforeKills.push_back(SpillIndex);
Evan Cheng06587492008-10-24 02:05:00 +0000436 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000437 Processed.insert(LR);
438
Evan Chengd0e32c52008-10-29 05:06:14 +0000439 // Start from the restore mbb, figure out what part of the live interval
440 // are defined by the restore.
Evan Chengf5cd4f02008-10-23 20:43:13 +0000441 SmallVector<MachineBasicBlock*, 4> WorkList;
Evan Cheng54898932008-10-29 08:39:34 +0000442 MachineBasicBlock *MBB = BarrierMBB;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000443 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
444 SE = MBB->succ_end(); SI != SE; ++SI)
445 WorkList.push_back(*SI);
446
Owen Anderson75c99c52008-12-07 05:33:18 +0000447 SmallPtrSet<MachineBasicBlock*, 4> ProcessedBlocks;
448 ProcessedBlocks.insert(MBB);
449
Evan Chengf5cd4f02008-10-23 20:43:13 +0000450 while (!WorkList.empty()) {
451 MBB = WorkList.back();
452 WorkList.pop_back();
453 unsigned Idx = LIs->getMBBStartIdx(MBB);
454 LR = CurrLI->getLiveRangeContaining(Idx);
455 if (LR && LR->valno == ValNo && !Processed.count(LR)) {
456 After.push_back(std::make_pair(LR->start, LR->end));
457 if (CurrLI->isKill(ValNo, LR->end))
458 AfterKills.push_back(LR->end);
459 Idx = LIs->getMBBEndIdx(MBB);
460 if (LR->end > Idx) {
Evan Chengd0e32c52008-10-29 05:06:14 +0000461 // Live range extend beyond at least one mbb. Let's see what other
462 // mbbs it reaches.
463 LIs->findReachableMBBs(LR->start, LR->end, WorkList);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000464 }
465 Processed.insert(LR);
466 }
Owen Anderson75c99c52008-12-07 05:33:18 +0000467
468 ProcessedBlocks.insert(MBB);
469 if (LR)
470 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
471 SE = MBB->succ_end(); SI != SE; ++SI)
472 if (!ProcessedBlocks.count(*SI))
473 WorkList.push_back(*SI);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000474 }
475
476 for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
477 I != E; ++I) {
478 LiveRange *LR = I;
479 if (LR->valno == ValNo && !Processed.count(LR)) {
480 Before.push_back(std::make_pair(LR->start, LR->end));
481 if (CurrLI->isKill(ValNo, LR->end))
482 BeforeKills.push_back(LR->end);
483 }
484 }
485
486 // Now create new val#s to represent the live ranges defined by the old def
487 // those defined by the restore.
488 unsigned AfterDef = ValNo->def;
489 MachineInstr *AfterCopy = ValNo->copy;
490 bool HasPHIKill = ValNo->hasPHIKill;
491 CurrLI->removeValNo(ValNo);
Evan Cheng06587492008-10-24 02:05:00 +0000492 VNInfo *BValNo = (Before.empty())
493 ? NULL
494 : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
495 if (BValNo)
496 CurrLI->addKills(BValNo, BeforeKills);
497
498 VNInfo *AValNo = (After.empty())
499 ? NULL
Evan Chengd0e32c52008-10-29 05:06:14 +0000500 : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
Evan Cheng06587492008-10-24 02:05:00 +0000501 if (AValNo) {
502 AValNo->hasPHIKill = HasPHIKill;
503 CurrLI->addKills(AValNo, AfterKills);
504 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000505
506 for (unsigned i = 0, e = Before.size(); i != e; ++i) {
507 unsigned Start = Before[i].first;
508 unsigned End = Before[i].second;
509 CurrLI->addRange(LiveRange(Start, End, BValNo));
510 }
511 for (unsigned i = 0, e = After.size(); i != e; ++i) {
512 unsigned Start = After[i].first;
513 unsigned End = After[i].second;
514 CurrLI->addRange(LiveRange(Start, End, AValNo));
515 }
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000516
517 return AValNo;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000518}
519
520/// ShrinkWrapToLastUse - There are uses of the current live interval in the
521/// given block, shrink wrap the live interval to the last use (i.e. remove
522/// from last use to the end of the mbb). In case mbb is the where the barrier
523/// is, remove from the last use to the barrier.
524bool
Evan Chengd0e32c52008-10-29 05:06:14 +0000525PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
Evan Cheng06587492008-10-24 02:05:00 +0000526 SmallVector<MachineOperand*, 4> &Uses,
527 SmallPtrSet<MachineInstr*, 4> &UseMIs) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000528 MachineOperand *LastMO = 0;
529 MachineInstr *LastMI = 0;
530 if (MBB != BarrierMBB && Uses.size() == 1) {
531 // Single use, no need to traverse the block. We can't assume this for the
532 // barrier bb though since the use is probably below the barrier.
533 LastMO = Uses[0];
534 LastMI = LastMO->getParent();
535 } else {
Evan Cheng2efe3fd2008-10-24 05:53:44 +0000536 MachineBasicBlock::iterator MEE = MBB->begin();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000537 MachineBasicBlock::iterator MII;
Evan Cheng2efe3fd2008-10-24 05:53:44 +0000538 if (MBB == BarrierMBB)
Evan Chengf5cd4f02008-10-23 20:43:13 +0000539 MII = Barrier;
Evan Cheng2efe3fd2008-10-24 05:53:44 +0000540 else
Evan Chengf5cd4f02008-10-23 20:43:13 +0000541 MII = MBB->end();
Evan Chengd0e32c52008-10-29 05:06:14 +0000542 while (MII != MEE) {
543 --MII;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000544 MachineInstr *UseMI = &*MII;
545 if (!UseMIs.count(UseMI))
546 continue;
547 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
548 MachineOperand &MO = UseMI->getOperand(i);
549 if (MO.isReg() && MO.getReg() == CurrLI->reg) {
550 LastMO = &MO;
551 break;
552 }
553 }
554 LastMI = UseMI;
555 break;
556 }
557 }
558
559 // Cut off live range from last use (or beginning of the mbb if there
560 // are no uses in it) to the end of the mbb.
561 unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
562 if (LastMI) {
563 RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
564 assert(!LastMO->isKill() && "Last use already terminates the interval?");
565 LastMO->setIsKill();
566 } else {
567 assert(MBB == BarrierMBB);
568 RangeStart = LIs->getMBBStartIdx(MBB);
569 }
570 if (MBB == BarrierMBB)
Evan Cheng06587492008-10-24 02:05:00 +0000571 RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000572 CurrLI->removeRange(RangeStart, RangeEnd);
Evan Chengd0e32c52008-10-29 05:06:14 +0000573 if (LastMI)
574 CurrLI->addKill(ValNo, RangeStart);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000575
576 // Return true if the last use becomes a new kill.
577 return LastMI;
578}
579
580/// ShrinkWrapLiveInterval - Recursively traverse the predecessor
581/// chain to find the new 'kills' and shrink wrap the live interval to the
582/// new kill indices.
583void
Evan Chengaaf510c2008-10-26 07:49:03 +0000584PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
585 MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
Evan Cheng06587492008-10-24 02:05:00 +0000586 SmallPtrSet<MachineBasicBlock*, 8> &Visited,
587 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
588 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
589 SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
Evan Chengaaf510c2008-10-26 07:49:03 +0000590 if (Visited.count(MBB))
Evan Chengf5cd4f02008-10-23 20:43:13 +0000591 return;
592
Evan Chengaaf510c2008-10-26 07:49:03 +0000593 // If live interval is live in another successor path, then we can't process
594 // this block. But we may able to do so after all the successors have been
595 // processed.
Evan Chengf62ce372008-10-28 00:47:49 +0000596 if (MBB != BarrierMBB) {
597 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
598 SE = MBB->succ_end(); SI != SE; ++SI) {
599 MachineBasicBlock *SMBB = *SI;
600 if (SMBB == SuccMBB)
601 continue;
602 if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
603 return;
604 }
Evan Chengaaf510c2008-10-26 07:49:03 +0000605 }
606
607 Visited.insert(MBB);
608
Evan Cheng06587492008-10-24 02:05:00 +0000609 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
610 UMII = Uses.find(MBB);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000611 if (UMII != Uses.end()) {
612 // At least one use in this mbb, lets look for the kill.
Evan Cheng06587492008-10-24 02:05:00 +0000613 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
614 UMII2 = UseMIs.find(MBB);
Evan Chengd0e32c52008-10-29 05:06:14 +0000615 if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
Evan Chengf5cd4f02008-10-23 20:43:13 +0000616 // Found a kill, shrink wrapping of this path ends here.
617 return;
Evan Cheng06587492008-10-24 02:05:00 +0000618 } else if (MBB == DefMBB) {
Evan Cheng06587492008-10-24 02:05:00 +0000619 // There are no uses after the def.
620 MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
Evan Cheng06587492008-10-24 02:05:00 +0000621 if (UseMBBs.empty()) {
622 // The only use must be below barrier in the barrier block. It's safe to
623 // remove the def.
624 LIs->RemoveMachineInstrFromMaps(DefMI);
625 DefMI->eraseFromParent();
626 CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
627 }
Evan Cheng79d5b5a2008-10-25 23:49:39 +0000628 } else if (MBB == BarrierMBB) {
629 // Remove entire live range from start of mbb to barrier.
630 CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
631 LIs->getUseIndex(BarrierIdx)+1);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000632 } else {
Evan Cheng79d5b5a2008-10-25 23:49:39 +0000633 // Remove entire live range of the mbb out of the live interval.
Evan Cheng06587492008-10-24 02:05:00 +0000634 CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000635 }
636
637 if (MBB == DefMBB)
638 // Reached the def mbb, stop traversing this path further.
639 return;
640
641 // Traverse the pathes up the predecessor chains further.
642 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
643 PE = MBB->pred_end(); PI != PE; ++PI) {
644 MachineBasicBlock *Pred = *PI;
645 if (Pred == MBB)
646 continue;
647 if (Pred == DefMBB && ValNo->hasPHIKill)
648 // Pred is the def bb and the def reaches other val#s, we must
649 // allow the value to be live out of the bb.
650 continue;
Owen Anderson80fe8732008-11-11 22:11:27 +0000651 if (!CurrLI->liveAt(LIs->getMBBEndIdx(Pred)-1))
652 return;
Evan Chengaaf510c2008-10-26 07:49:03 +0000653 ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
654 Uses, UseMIs, UseMBBs);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000655 }
656
657 return;
658}
659
Owen Anderson75fa96b2008-11-19 04:28:29 +0000660
Owen Anderson6002e992008-12-04 21:20:30 +0000661void PreAllocSplitting::RepairLiveInterval(LiveInterval* CurrLI,
662 VNInfo* ValNo,
663 MachineInstr* DefMI,
664 unsigned RestoreIdx) {
Owen Anderson75fa96b2008-11-19 04:28:29 +0000665 // Shrink wrap the live interval by walking up the CFG and find the
666 // new kills.
667 // Now let's find all the uses of the val#.
668 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
669 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
670 SmallPtrSet<MachineBasicBlock*, 4> Seen;
671 SmallVector<MachineBasicBlock*, 4> UseMBBs;
672 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
673 UE = MRI->use_end(); UI != UE; ++UI) {
674 MachineOperand &UseMO = UI.getOperand();
675 MachineInstr *UseMI = UseMO.getParent();
676 unsigned UseIdx = LIs->getInstructionIndex(UseMI);
677 LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
678 if (ULR->valno != ValNo)
679 continue;
680 MachineBasicBlock *UseMBB = UseMI->getParent();
681 // Remember which other mbb's use this val#.
682 if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
683 UseMBBs.push_back(UseMBB);
684 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
685 UMII = Uses.find(UseMBB);
686 if (UMII != Uses.end()) {
687 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
688 UMII2 = UseMIs.find(UseMBB);
689 UMII->second.push_back(&UseMO);
690 UMII2->second.insert(UseMI);
691 } else {
692 SmallVector<MachineOperand*, 4> Ops;
693 Ops.push_back(&UseMO);
694 Uses.insert(std::make_pair(UseMBB, Ops));
695 SmallPtrSet<MachineInstr*, 4> MIs;
696 MIs.insert(UseMI);
697 UseMIs.insert(std::make_pair(UseMBB, MIs));
698 }
699 }
700
701 // Walk up the predecessor chains.
702 SmallPtrSet<MachineBasicBlock*, 8> Visited;
703 ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMI->getParent(), Visited,
704 Uses, UseMIs, UseMBBs);
705
Owen Anderson75fa96b2008-11-19 04:28:29 +0000706 // Remove live range from barrier to the restore. FIXME: Find a better
707 // point to re-start the live interval.
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000708 VNInfo* AfterValNo = UpdateRegisterInterval(ValNo,
709 LIs->getUseIndex(BarrierIdx)+1,
710 LIs->getDefIndex(RestoreIdx));
711
712 // Attempt to renumber the new valno into a new vreg.
713 RenumberValno(AfterValNo);
Owen Anderson6002e992008-12-04 21:20:30 +0000714}
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000715
716/// RenumberValno - Split the given valno out into a new vreg, allowing it to
717/// be allocated to a different register. This function creates a new vreg,
718/// copies the valno and its live ranges over to the new vreg's interval,
719/// removes them from the old interval, and rewrites all uses and defs of
720/// the original reg to the new vreg within those ranges.
721void PreAllocSplitting::RenumberValno(VNInfo* VN) {
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000722 SmallVector<VNInfo*, 4> Stack;
723 SmallVector<VNInfo*, 4> VNsToCopy;
724 Stack.push_back(VN);
725
726 // Walk through and copy the valno we care about, and any other valnos
727 // that are two-address redefinitions of the one we care about. These
728 // will need to be rewritten as well. We also check for safety of the
729 // renumbering here, by making sure that none of the valno involved has
730 // phi kills.
731 while (!Stack.empty()) {
732 VNInfo* OldVN = Stack.back();
733 Stack.pop_back();
734
735 // Bail out if we ever encounter a valno that has a PHI kill. We can't
736 // renumber these.
737 if (OldVN->hasPHIKill) return;
738
739 VNsToCopy.push_back(OldVN);
740
741 // Locate two-address redefinitions
742 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
743 KE = OldVN->kills.end(); KI != KE; ++KI) {
744 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
745 //if (!MI) continue;
746 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
747 if (DefIdx == ~0U) continue;
748 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
749 VNInfo* NextVN =
750 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
751 Stack.push_back(NextVN);
752 }
753 }
754 }
755
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000756 // Create the new vreg
757 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
758
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000759 // Create the new live interval
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000760 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000761
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000762 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
763 VNsToCopy.end(); OI != OE; ++OI) {
764 VNInfo* OldVN = *OI;
765
766 // Copy the valno over
767 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
768 LIs->getVNInfoAllocator());
769 NewLI.copyValNumInfo(NewVN, OldVN);
770 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
771
772 // Remove the valno from the old interval
773 CurrLI->removeValNo(OldVN);
774 }
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000775
776 // Rewrite defs and uses. This is done in two stages to avoid invalidating
777 // the reg_iterator.
778 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
779
780 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
781 E = MRI->reg_end(); I != E; ++I) {
782 MachineOperand& MO = I.getOperand();
783 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
784
785 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
786 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
787 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
788 }
789
790 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
791 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
792 MachineInstr* Inst = I->first;
793 unsigned OpIdx = I->second;
794 MachineOperand& MO = Inst->getOperand(OpIdx);
795 MO.setReg(NewVReg);
796 }
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000797
798 NumRenumbers++;
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000799}
800
Owen Anderson6002e992008-12-04 21:20:30 +0000801bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
802 MachineInstr* DefMI,
803 MachineBasicBlock::iterator RestorePt,
804 unsigned RestoreIdx,
805 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
806 MachineBasicBlock& MBB = *RestorePt->getParent();
807
808 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
809 unsigned KillIdx = 0;
810 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
811 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
812 else
813 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
814
815 if (KillPt == DefMI->getParent()->end())
816 return false;
817
818 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
819 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
820
821 if (KillPt->getParent() == BarrierMBB) {
822 UpdateRegisterInterval(ValNo, LIs->getUseIndex(KillIdx)+1,
823 LIs->getDefIndex(RestoreIdx));
824
825 ++NumSplits;
826 ++NumRemats;
827 return true;
828 }
829
830 RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIdx);
Owen Anderson75fa96b2008-11-19 04:28:29 +0000831
832 ++NumSplits;
833 ++NumRemats;
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000834 return true;
835}
836
837MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
838 const TargetRegisterClass* RC,
839 MachineInstr* DefMI,
840 MachineInstr* Barrier,
841 MachineBasicBlock* MBB,
842 int& SS,
843 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
844 MachineBasicBlock::iterator Pt = MBB->begin();
845
846 // Go top down if RefsInMBB is empty.
847 if (RefsInMBB.empty())
848 return 0;
Owen Anderson75fa96b2008-11-19 04:28:29 +0000849
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000850 MachineBasicBlock::iterator FoldPt = Barrier;
851 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
852 !RefsInMBB.count(FoldPt))
853 --FoldPt;
854
855 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
856 if (OpIdx == -1)
857 return 0;
858
859 SmallVector<unsigned, 1> Ops;
860 Ops.push_back(OpIdx);
861
862 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
863 return 0;
864
865 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
866 if (I != IntervalSSMap.end()) {
867 SS = I->second;
868 } else {
869 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
870
871 }
872
873 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
874 FoldPt, Ops, SS);
875
876 if (FMI) {
877 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
878 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
879 ++NumFolds;
880
881 IntervalSSMap[vreg] = SS;
882 CurrSLI = &LSs->getOrCreateInterval(SS);
883 if (CurrSLI->hasAtLeastOneValue())
884 CurrSValNo = CurrSLI->getValNumInfo(0);
885 else
886 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
887 }
888
889 return FMI;
Owen Anderson75fa96b2008-11-19 04:28:29 +0000890}
891
Evan Chengf5cd4f02008-10-23 20:43:13 +0000892/// SplitRegLiveInterval - Split (spill and restore) the given live interval
893/// so it would not cross the barrier that's being processed. Shrink wrap
894/// (minimize) the live interval to the last uses.
895bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
896 CurrLI = LI;
897
898 // Find live range where current interval cross the barrier.
899 LiveInterval::iterator LR =
900 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
901 VNInfo *ValNo = LR->valno;
902
903 if (ValNo->def == ~1U) {
904 // Defined by a dead def? How can this be?
905 assert(0 && "Val# is defined by a dead def?");
906 abort();
907 }
908
Evan Cheng06587492008-10-24 02:05:00 +0000909 MachineInstr *DefMI = (ValNo->def != ~0U)
910 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
Evan Cheng06587492008-10-24 02:05:00 +0000911
Owen Andersonb214c692008-11-05 00:32:13 +0000912 // If this would create a new join point, do not split.
913 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
914 return false;
915
Evan Chengf5cd4f02008-10-23 20:43:13 +0000916 // Find all references in the barrier mbb.
917 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
918 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
919 E = MRI->reg_end(); I != E; ++I) {
920 MachineInstr *RefMI = &*I;
921 if (RefMI->getParent() == BarrierMBB)
922 RefsInMBB.insert(RefMI);
923 }
924
925 // Find a point to restore the value after the barrier.
926 unsigned RestoreIndex;
927 MachineBasicBlock::iterator RestorePt =
Evan Chengf62ce372008-10-28 00:47:49 +0000928 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000929 if (RestorePt == BarrierMBB->end())
930 return false;
931
Owen Anderson75fa96b2008-11-19 04:28:29 +0000932 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
933 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
934 RestoreIndex, RefsInMBB))
935 return true;
936
Evan Chengf5cd4f02008-10-23 20:43:13 +0000937 // Add a spill either before the barrier or after the definition.
Evan Cheng06587492008-10-24 02:05:00 +0000938 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000939 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000940 unsigned SpillIndex = 0;
Evan Cheng06587492008-10-24 02:05:00 +0000941 MachineInstr *SpillMI = NULL;
Evan Cheng985921e2008-10-27 23:29:28 +0000942 int SS = -1;
Evan Cheng78dfef72008-10-25 00:52:41 +0000943 if (ValNo->def == ~0U) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000944 // If it's defined by a phi, we must split just before the barrier.
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000945 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
946 BarrierMBB, SS, RefsInMBB))) {
947 SpillIndex = LIs->getInstructionIndex(SpillMI);
948 } else {
949 MachineBasicBlock::iterator SpillPt =
950 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
951 if (SpillPt == BarrierMBB->begin())
952 return false; // No gap to insert spill.
953 // Add spill.
954
955 SS = CreateSpillStackSlot(CurrLI->reg, RC);
956 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
957 SpillMI = prior(SpillPt);
958 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
959 }
Evan Cheng54898932008-10-29 08:39:34 +0000960 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
961 RestoreIndex, SpillIndex, SS)) {
Evan Cheng78dfef72008-10-25 00:52:41 +0000962 // If it's already split, just restore the value. There is no need to spill
963 // the def again.
Evan Chengd0e32c52008-10-29 05:06:14 +0000964 if (!DefMI)
965 return false; // Def is dead. Do nothing.
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000966
967 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
968 BarrierMBB, SS, RefsInMBB))) {
969 SpillIndex = LIs->getInstructionIndex(SpillMI);
Evan Cheng1f08cc22008-10-28 05:28:21 +0000970 } else {
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000971 // Check if it's possible to insert a spill after the def MI.
972 MachineBasicBlock::iterator SpillPt;
973 if (DefMBB == BarrierMBB) {
974 // Add spill after the def and the last use before the barrier.
975 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
976 RefsInMBB, SpillIndex);
977 if (SpillPt == DefMBB->begin())
978 return false; // No gap to insert spill.
979 } else {
980 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
981 if (SpillPt == DefMBB->end())
982 return false; // No gap to insert spill.
983 }
984 // Add spill. The store instruction kills the register if def is before
985 // the barrier in the barrier block.
986 SS = CreateSpillStackSlot(CurrLI->reg, RC);
987 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
988 DefMBB == BarrierMBB, SS, RC);
989 SpillMI = prior(SpillPt);
990 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
Evan Cheng1f08cc22008-10-28 05:28:21 +0000991 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000992 }
993
Evan Cheng54898932008-10-29 08:39:34 +0000994 // Remember def instruction index to spill index mapping.
995 if (DefMI && SpillMI)
996 Def2SpillMap[ValNo->def] = SpillIndex;
997
Evan Chengf5cd4f02008-10-23 20:43:13 +0000998 // Add restore.
Evan Chengf5cd4f02008-10-23 20:43:13 +0000999 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1000 MachineInstr *LoadMI = prior(RestorePt);
1001 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1002
1003 // If live interval is spilled in the same block as the barrier, just
1004 // create a hole in the interval.
1005 if (!DefMBB ||
Evan Cheng78dfef72008-10-25 00:52:41 +00001006 (SpillMI && SpillMI->getParent() == BarrierMBB)) {
Evan Chengd0e32c52008-10-29 05:06:14 +00001007 // Update spill stack slot live interval.
1008 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1009 LIs->getDefIndex(RestoreIndex));
Evan Chengf5cd4f02008-10-23 20:43:13 +00001010
Evan Chengd0e32c52008-10-29 05:06:14 +00001011 UpdateRegisterInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1012 LIs->getDefIndex(RestoreIndex));
Evan Chengf5cd4f02008-10-23 20:43:13 +00001013
Evan Chengae7fa5b2008-10-28 01:48:24 +00001014 ++NumSplits;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001015 return true;
1016 }
1017
Evan Chengd0e32c52008-10-29 05:06:14 +00001018 // Update spill stack slot live interval.
Evan Cheng54898932008-10-29 08:39:34 +00001019 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1020 LIs->getDefIndex(RestoreIndex));
Evan Chengd0e32c52008-10-29 05:06:14 +00001021
Owen Anderson6002e992008-12-04 21:20:30 +00001022 RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIndex);
Evan Chengf5cd4f02008-10-23 20:43:13 +00001023
Evan Chengae7fa5b2008-10-28 01:48:24 +00001024 ++NumSplits;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001025 return true;
1026}
1027
1028/// SplitRegLiveIntervals - Split all register live intervals that cross the
1029/// barrier that's being processed.
1030bool
1031PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs) {
1032 // First find all the virtual registers whose live intervals are intercepted
1033 // by the current barrier.
1034 SmallVector<LiveInterval*, 8> Intervals;
1035 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
Evan Cheng23066282008-10-27 07:14:50 +00001036 if (TII->IgnoreRegisterClassBarriers(*RC))
1037 continue;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001038 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1039 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1040 unsigned Reg = VRs[i];
1041 if (!LIs->hasInterval(Reg))
1042 continue;
1043 LiveInterval *LI = &LIs->getInterval(Reg);
1044 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1045 // Virtual register live interval is intercepted by the barrier. We
1046 // should split and shrink wrap its interval if possible.
1047 Intervals.push_back(LI);
1048 }
1049 }
1050
1051 // Process the affected live intervals.
1052 bool Change = false;
1053 while (!Intervals.empty()) {
Evan Chengae7fa5b2008-10-28 01:48:24 +00001054 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1055 break;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001056 LiveInterval *LI = Intervals.back();
1057 Intervals.pop_back();
1058 Change |= SplitRegLiveInterval(LI);
1059 }
1060
1061 return Change;
1062}
1063
Owen Andersonf1f75b12008-11-04 22:22:41 +00001064bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1065 MachineBasicBlock* DefMBB,
1066 MachineBasicBlock* BarrierMBB) {
1067 if (DefMBB == BarrierMBB)
1068 return false;
1069
1070 if (LR->valno->hasPHIKill)
1071 return false;
1072
1073 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1074 if (LR->end < MBBEnd)
1075 return false;
1076
1077 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1078 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1079 return true;
1080
1081 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1082 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1083 typedef std::pair<MachineBasicBlock*,
1084 MachineBasicBlock::succ_iterator> ItPair;
1085 SmallVector<ItPair, 4> Stack;
1086 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1087
1088 while (!Stack.empty()) {
1089 ItPair P = Stack.back();
1090 Stack.pop_back();
1091
1092 MachineBasicBlock* PredMBB = P.first;
1093 MachineBasicBlock::succ_iterator S = P.second;
1094
1095 if (S == PredMBB->succ_end())
1096 continue;
1097 else if (Visited.count(*S)) {
1098 Stack.push_back(std::make_pair(PredMBB, ++S));
1099 continue;
1100 } else
Owen Andersonb214c692008-11-05 00:32:13 +00001101 Stack.push_back(std::make_pair(PredMBB, S+1));
Owen Andersonf1f75b12008-11-04 22:22:41 +00001102
1103 MachineBasicBlock* MBB = *S;
1104 Visited.insert(MBB);
1105
1106 if (MBB == BarrierMBB)
1107 return true;
1108
1109 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1110 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1111 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1112 while (MDTN) {
1113 if (MDTN == DefMDTN)
1114 return true;
1115 else if (MDTN == BarrierMDTN)
1116 break;
1117 MDTN = MDTN->getIDom();
1118 }
1119
1120 MBBEnd = LIs->getMBBEndIdx(MBB);
1121 if (LR->end > MBBEnd)
1122 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1123 }
1124
1125 return false;
1126}
1127
1128
Evan Cheng09e8ca82008-10-20 21:44:59 +00001129bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd0e32c52008-10-29 05:06:14 +00001130 CurrMF = &MF;
1131 TM = &MF.getTarget();
1132 TII = TM->getInstrInfo();
1133 MFI = MF.getFrameInfo();
1134 MRI = &MF.getRegInfo();
1135 LIs = &getAnalysis<LiveIntervals>();
1136 LSs = &getAnalysis<LiveStacks>();
Evan Chengf5cd4f02008-10-23 20:43:13 +00001137
1138 bool MadeChange = false;
1139
1140 // Make sure blocks are numbered in order.
1141 MF.RenumberBlocks();
1142
Evan Cheng54898932008-10-29 08:39:34 +00001143 MachineBasicBlock *Entry = MF.begin();
1144 SmallPtrSet<MachineBasicBlock*,16> Visited;
1145
1146 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1147 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1148 DFI != E; ++DFI) {
1149 BarrierMBB = *DFI;
1150 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1151 E = BarrierMBB->end(); I != E; ++I) {
1152 Barrier = &*I;
1153 const TargetRegisterClass **BarrierRCs =
1154 Barrier->getDesc().getRegClassBarriers();
1155 if (!BarrierRCs)
1156 continue;
1157 BarrierIdx = LIs->getInstructionIndex(Barrier);
1158 MadeChange |= SplitRegLiveIntervals(BarrierRCs);
1159 }
1160 }
Evan Chengf5cd4f02008-10-23 20:43:13 +00001161
1162 return MadeChange;
Evan Cheng09e8ca82008-10-20 21:44:59 +00001163}