blob: b6efe0624de6f75272ea2d4f67cbe9e4ce6929c7 [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 Chengf5cd4f02008-10-23 20:43:13 +000019#include "llvm/CodeGen/MachineFrameInfo.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineLoopInfo.h"
22#include "llvm/CodeGen/MachineRegisterInfo.h"
23#include "llvm/CodeGen/Passes.h"
24#include "llvm/CodeGen/RegisterCoalescer.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000025#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000026#include "llvm/Target/TargetMachine.h"
27#include "llvm/Target/TargetOptions.h"
28#include "llvm/Target/TargetRegisterInfo.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000031#include "llvm/ADT/SmallPtrSet.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000032#include "llvm/ADT/Statistic.h"
33#include <map>
Evan Cheng09e8ca82008-10-20 21:44:59 +000034using namespace llvm;
35
Evan Chengae7fa5b2008-10-28 01:48:24 +000036static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
37
38STATISTIC(NumSplits, "Number of intervals split");
Evan Chengf5cd4f02008-10-23 20:43:13 +000039
Evan Cheng09e8ca82008-10-20 21:44:59 +000040namespace {
41 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
Evan Chengf5cd4f02008-10-23 20:43:13 +000042 MachineFunction *CurMF;
43 const TargetMachine *TM;
44 const TargetInstrInfo *TII;
45 MachineFrameInfo *MFI;
46 MachineRegisterInfo *MRI;
47 LiveIntervals *LIs;
Evan Cheng09e8ca82008-10-20 21:44:59 +000048
Evan Chengf5cd4f02008-10-23 20:43:13 +000049 // Barrier - Current barrier being processed.
50 MachineInstr *Barrier;
51
52 // BarrierMBB - Basic block where the barrier resides in.
53 MachineBasicBlock *BarrierMBB;
54
55 // Barrier - Current barrier index.
56 unsigned BarrierIdx;
57
58 // CurrLI - Current live interval being split.
59 LiveInterval *CurrLI;
60
61 // LIValNoSSMap - A map from live interval and val# pairs to spill slots.
62 // This records what live interval's val# has been split and what spill
63 // slot was used.
64 std::map<std::pair<unsigned, unsigned>, int> LIValNoSSMap;
65
Evan Cheng06587492008-10-24 02:05:00 +000066 // RestoreMIs - All the restores inserted due to live interval splitting.
67 SmallPtrSet<MachineInstr*, 8> RestoreMIs;
68
Evan Cheng09e8ca82008-10-20 21:44:59 +000069 public:
70 static char ID;
71 PreAllocSplitting() : MachineFunctionPass(&ID) {}
72
73 virtual bool runOnMachineFunction(MachineFunction &MF);
74
75 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequired<LiveIntervals>();
77 AU.addPreserved<LiveIntervals>();
Evan Cheng09e8ca82008-10-20 21:44:59 +000078 AU.addPreserved<RegisterCoalescer>();
79 if (StrongPHIElim)
80 AU.addPreservedID(StrongPHIEliminationID);
81 else
82 AU.addPreservedID(PHIEliminationID);
Evan Cheng09e8ca82008-10-20 21:44:59 +000083 MachineFunctionPass::getAnalysisUsage(AU);
84 }
85
86 virtual void releaseMemory() {
Evan Chengf5cd4f02008-10-23 20:43:13 +000087 LIValNoSSMap.clear();
Evan Cheng06587492008-10-24 02:05:00 +000088 RestoreMIs.clear();
Evan Cheng09e8ca82008-10-20 21:44:59 +000089 }
90
91 virtual const char *getPassName() const {
92 return "Pre-Register Allocaton Live Interval Splitting";
93 }
Evan Chengf5cd4f02008-10-23 20:43:13 +000094
95 /// print - Implement the dump method.
96 virtual void print(std::ostream &O, const Module* M = 0) const {
97 LIs->print(O, M);
98 }
99
100 void print(std::ostream *O, const Module* M = 0) const {
101 if (O) print(*O, M);
102 }
103
104 private:
105 MachineBasicBlock::iterator
106 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
107 unsigned&);
108
109 MachineBasicBlock::iterator
110 findSpillPoint(MachineBasicBlock*, MachineInstr*,
111 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
112
113 MachineBasicBlock::iterator
Evan Chengf62ce372008-10-28 00:47:49 +0000114 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000115 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
116
117 void RecordSplit(unsigned, unsigned, unsigned, int);
118
119 bool isAlreadySplit(unsigned, unsigned, int&);
120
121 void UpdateIntervalForSplit(VNInfo*, unsigned, unsigned);
122
123 bool ShrinkWrapToLastUse(MachineBasicBlock*,
Evan Cheng06587492008-10-24 02:05:00 +0000124 SmallVector<MachineOperand*, 4>&,
125 SmallPtrSet<MachineInstr*, 4>&);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000126
Evan Chengaaf510c2008-10-26 07:49:03 +0000127 void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000128 MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
Evan Cheng06587492008-10-24 02:05:00 +0000129 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
130 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
131 SmallVector<MachineBasicBlock*, 4>&);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000132
133 bool SplitRegLiveInterval(LiveInterval*);
134
135 bool SplitRegLiveIntervals(const TargetRegisterClass **);
Evan Cheng09e8ca82008-10-20 21:44:59 +0000136 };
137} // end anonymous namespace
138
139char PreAllocSplitting::ID = 0;
140
141static RegisterPass<PreAllocSplitting>
142X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
143
144const PassInfo *const llvm::PreAllocSplittingID = &X;
145
Evan Chengf5cd4f02008-10-23 20:43:13 +0000146
147/// findNextEmptySlot - Find a gap after the given machine instruction in the
148/// instruction index map. If there isn't one, return end().
149MachineBasicBlock::iterator
150PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
151 unsigned &SpotIndex) {
152 MachineBasicBlock::iterator MII = MI;
153 if (++MII != MBB->end()) {
154 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
155 if (Index) {
156 SpotIndex = Index;
157 return MII;
158 }
159 }
160 return MBB->end();
161}
162
163/// findSpillPoint - Find a gap as far away from the given MI that's suitable
164/// for spilling the current live interval. The index must be before any
165/// defs and uses of the live interval register in the mbb. Return begin() if
166/// none is found.
167MachineBasicBlock::iterator
168PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
169 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
170 unsigned &SpillIndex) {
171 MachineBasicBlock::iterator Pt = MBB->begin();
172
173 // Go top down if RefsInMBB is empty.
174 if (RefsInMBB.empty()) {
175 MachineBasicBlock::iterator MII = MBB->begin();
176 MachineBasicBlock::iterator EndPt = MI;
177 do {
178 ++MII;
179 unsigned Index = LIs->getInstructionIndex(MII);
180 unsigned Gap = LIs->findGapBeforeInstr(Index);
181 if (Gap) {
182 Pt = MII;
183 SpillIndex = Gap;
184 break;
185 }
186 } while (MII != EndPt);
187 } else {
188 MachineBasicBlock::iterator MII = MI;
189 while (MII != MBB->begin() && !RefsInMBB.count(MII)) {
190 unsigned Index = LIs->getInstructionIndex(MII);
191 if (LIs->hasGapBeforeInstr(Index)) {
192 Pt = MII;
193 SpillIndex = LIs->findGapBeforeInstr(Index, true);
194 }
195 --MII;
196 }
197 }
198
199 return Pt;
200}
201
202/// findRestorePoint - Find a gap in the instruction index map that's suitable
203/// for restoring the current live interval value. The index must be before any
204/// uses of the live interval register in the mbb. Return end() if none is
205/// found.
206MachineBasicBlock::iterator
207PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
Evan Chengf62ce372008-10-28 00:47:49 +0000208 unsigned LastIdx,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000209 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
210 unsigned &RestoreIndex) {
211 MachineBasicBlock::iterator Pt = MBB->end();
Evan Chengf62ce372008-10-28 00:47:49 +0000212 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000213
Evan Chengf62ce372008-10-28 00:47:49 +0000214 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
215 // the last index in the live range.
216 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000217 MachineBasicBlock::iterator MII = MBB->end();
218 MachineBasicBlock::iterator EndPt = MI;
219 do {
220 --MII;
221 unsigned Index = LIs->getInstructionIndex(MII);
Evan Cheng56ab0de2008-10-24 18:46:44 +0000222 unsigned Gap = LIs->findGapBeforeInstr(Index);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000223 if (Gap) {
224 Pt = MII;
225 RestoreIndex = Gap;
226 break;
227 }
228 } while (MII != EndPt);
229 } else {
230 MachineBasicBlock::iterator MII = MI;
231 MII = ++MII;
Evan Chengf62ce372008-10-28 00:47:49 +0000232 // FIXME: Limit the number of instructions to examine to reduce
233 // compile time?
Evan Chengf5cd4f02008-10-23 20:43:13 +0000234 while (MII != MBB->end()) {
235 unsigned Index = LIs->getInstructionIndex(MII);
Evan Chengf62ce372008-10-28 00:47:49 +0000236 if (Index > LastIdx)
237 break;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000238 unsigned Gap = LIs->findGapBeforeInstr(Index);
239 if (Gap) {
240 Pt = MII;
241 RestoreIndex = Gap;
242 }
243 if (RefsInMBB.count(MII))
244 break;
245 ++MII;
246 }
247 }
248
249 return Pt;
250}
251
252/// RecordSplit - Given a register live interval is split, remember the spill
253/// slot where the val#s are in.
254void PreAllocSplitting::RecordSplit(unsigned Reg, unsigned SpillIndex,
255 unsigned RestoreIndex, int SS) {
Evan Cheng06587492008-10-24 02:05:00 +0000256 const LiveRange *LR = NULL;
257 if (SpillIndex) {
258 LR = CurrLI->getLiveRangeContaining(LIs->getUseIndex(SpillIndex));
259 LIValNoSSMap.insert(std::make_pair(std::make_pair(CurrLI->reg,
260 LR->valno->id), SS));
261 }
262 LR = CurrLI->getLiveRangeContaining(LIs->getDefIndex(RestoreIndex));
263 LIValNoSSMap.insert(std::make_pair(std::make_pair(CurrLI->reg,
264 LR->valno->id), SS));
Evan Chengf5cd4f02008-10-23 20:43:13 +0000265}
266
267/// isAlreadySplit - Return if a given val# of a register live interval is already
268/// split. Also return by reference the spill stock where the value is.
269bool PreAllocSplitting::isAlreadySplit(unsigned Reg, unsigned ValNoId, int &SS){
270 std::map<std::pair<unsigned, unsigned>, int>::iterator I =
271 LIValNoSSMap.find(std::make_pair(Reg, ValNoId));
272 if (I == LIValNoSSMap.end())
273 return false;
274 SS = I->second;
275 return true;
276}
277
278/// UpdateIntervalForSplit - Given the specified val# of the current live
279/// interval is being split, and the split and rejoin indices, update the live
280/// interval accordingly.
281void
282PreAllocSplitting::UpdateIntervalForSplit(VNInfo *ValNo, unsigned SplitIndex,
283 unsigned JoinIndex) {
284 SmallVector<std::pair<unsigned,unsigned>, 4> Before;
285 SmallVector<std::pair<unsigned,unsigned>, 4> After;
286 SmallVector<unsigned, 4> BeforeKills;
287 SmallVector<unsigned, 4> AfterKills;
288 SmallPtrSet<const LiveRange*, 4> Processed;
289
290 // First, let's figure out which parts of the live interval is now defined
291 // by the restore, which are defined by the original definition.
292 const LiveRange *LR = CurrLI->getLiveRangeContaining(JoinIndex);
293 After.push_back(std::make_pair(JoinIndex, LR->end));
Evan Cheng06587492008-10-24 02:05:00 +0000294 if (CurrLI->isKill(ValNo, LR->end))
295 AfterKills.push_back(LR->end);
296
Evan Chengf5cd4f02008-10-23 20:43:13 +0000297 assert(LR->contains(SplitIndex));
Evan Cheng06587492008-10-24 02:05:00 +0000298 if (SplitIndex > LR->start) {
299 Before.push_back(std::make_pair(LR->start, SplitIndex));
300 BeforeKills.push_back(SplitIndex);
301 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000302 Processed.insert(LR);
303
304 SmallVector<MachineBasicBlock*, 4> WorkList;
305 MachineBasicBlock *MBB = LIs->getMBBFromIndex(LR->end-1);
306 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
307 SE = MBB->succ_end(); SI != SE; ++SI)
308 WorkList.push_back(*SI);
309
310 while (!WorkList.empty()) {
311 MBB = WorkList.back();
312 WorkList.pop_back();
313 unsigned Idx = LIs->getMBBStartIdx(MBB);
314 LR = CurrLI->getLiveRangeContaining(Idx);
315 if (LR && LR->valno == ValNo && !Processed.count(LR)) {
316 After.push_back(std::make_pair(LR->start, LR->end));
317 if (CurrLI->isKill(ValNo, LR->end))
318 AfterKills.push_back(LR->end);
319 Idx = LIs->getMBBEndIdx(MBB);
320 if (LR->end > Idx) {
321 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
322 SE = MBB->succ_end(); SI != SE; ++SI)
323 WorkList.push_back(*SI);
324 if (LR->end > Idx+1) {
325 MBB = LIs->getMBBFromIndex(LR->end-1);
326 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
327 SE = MBB->succ_end(); SI != SE; ++SI)
328 WorkList.push_back(*SI);
329 }
330 }
331 Processed.insert(LR);
332 }
333 }
334
335 for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
336 I != E; ++I) {
337 LiveRange *LR = I;
338 if (LR->valno == ValNo && !Processed.count(LR)) {
339 Before.push_back(std::make_pair(LR->start, LR->end));
340 if (CurrLI->isKill(ValNo, LR->end))
341 BeforeKills.push_back(LR->end);
342 }
343 }
344
345 // Now create new val#s to represent the live ranges defined by the old def
346 // those defined by the restore.
347 unsigned AfterDef = ValNo->def;
348 MachineInstr *AfterCopy = ValNo->copy;
349 bool HasPHIKill = ValNo->hasPHIKill;
350 CurrLI->removeValNo(ValNo);
Evan Cheng06587492008-10-24 02:05:00 +0000351 VNInfo *BValNo = (Before.empty())
352 ? NULL
353 : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
354 if (BValNo)
355 CurrLI->addKills(BValNo, BeforeKills);
356
357 VNInfo *AValNo = (After.empty())
358 ? NULL
359 : CurrLI->getNextValue(JoinIndex,0, LIs->getVNInfoAllocator());
360 if (AValNo) {
361 AValNo->hasPHIKill = HasPHIKill;
362 CurrLI->addKills(AValNo, AfterKills);
363 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000364
365 for (unsigned i = 0, e = Before.size(); i != e; ++i) {
366 unsigned Start = Before[i].first;
367 unsigned End = Before[i].second;
368 CurrLI->addRange(LiveRange(Start, End, BValNo));
369 }
370 for (unsigned i = 0, e = After.size(); i != e; ++i) {
371 unsigned Start = After[i].first;
372 unsigned End = After[i].second;
373 CurrLI->addRange(LiveRange(Start, End, AValNo));
374 }
375}
376
377/// ShrinkWrapToLastUse - There are uses of the current live interval in the
378/// given block, shrink wrap the live interval to the last use (i.e. remove
379/// from last use to the end of the mbb). In case mbb is the where the barrier
380/// is, remove from the last use to the barrier.
381bool
382PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB,
Evan Cheng06587492008-10-24 02:05:00 +0000383 SmallVector<MachineOperand*, 4> &Uses,
384 SmallPtrSet<MachineInstr*, 4> &UseMIs) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000385 MachineOperand *LastMO = 0;
386 MachineInstr *LastMI = 0;
387 if (MBB != BarrierMBB && Uses.size() == 1) {
388 // Single use, no need to traverse the block. We can't assume this for the
389 // barrier bb though since the use is probably below the barrier.
390 LastMO = Uses[0];
391 LastMI = LastMO->getParent();
392 } else {
Evan Cheng2efe3fd2008-10-24 05:53:44 +0000393 MachineBasicBlock::iterator MEE = MBB->begin();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000394 MachineBasicBlock::iterator MII;
Evan Cheng2efe3fd2008-10-24 05:53:44 +0000395 if (MBB == BarrierMBB)
Evan Chengf5cd4f02008-10-23 20:43:13 +0000396 MII = Barrier;
Evan Cheng2efe3fd2008-10-24 05:53:44 +0000397 else
Evan Chengf5cd4f02008-10-23 20:43:13 +0000398 MII = MBB->end();
Evan Cheng2efe3fd2008-10-24 05:53:44 +0000399 while (--MII != MEE) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000400 MachineInstr *UseMI = &*MII;
401 if (!UseMIs.count(UseMI))
402 continue;
403 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
404 MachineOperand &MO = UseMI->getOperand(i);
405 if (MO.isReg() && MO.getReg() == CurrLI->reg) {
406 LastMO = &MO;
407 break;
408 }
409 }
410 LastMI = UseMI;
411 break;
412 }
413 }
414
415 // Cut off live range from last use (or beginning of the mbb if there
416 // are no uses in it) to the end of the mbb.
417 unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
418 if (LastMI) {
419 RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
420 assert(!LastMO->isKill() && "Last use already terminates the interval?");
421 LastMO->setIsKill();
422 } else {
423 assert(MBB == BarrierMBB);
424 RangeStart = LIs->getMBBStartIdx(MBB);
425 }
426 if (MBB == BarrierMBB)
Evan Cheng06587492008-10-24 02:05:00 +0000427 RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000428 CurrLI->removeRange(RangeStart, RangeEnd);
429
430 // Return true if the last use becomes a new kill.
431 return LastMI;
432}
433
434/// ShrinkWrapLiveInterval - Recursively traverse the predecessor
435/// chain to find the new 'kills' and shrink wrap the live interval to the
436/// new kill indices.
437void
Evan Chengaaf510c2008-10-26 07:49:03 +0000438PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
439 MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
Evan Cheng06587492008-10-24 02:05:00 +0000440 SmallPtrSet<MachineBasicBlock*, 8> &Visited,
441 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
442 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
443 SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
Evan Chengaaf510c2008-10-26 07:49:03 +0000444 if (Visited.count(MBB))
Evan Chengf5cd4f02008-10-23 20:43:13 +0000445 return;
446
Evan Chengaaf510c2008-10-26 07:49:03 +0000447 // If live interval is live in another successor path, then we can't process
448 // this block. But we may able to do so after all the successors have been
449 // processed.
Evan Chengf62ce372008-10-28 00:47:49 +0000450 if (MBB != BarrierMBB) {
451 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
452 SE = MBB->succ_end(); SI != SE; ++SI) {
453 MachineBasicBlock *SMBB = *SI;
454 if (SMBB == SuccMBB)
455 continue;
456 if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
457 return;
458 }
Evan Chengaaf510c2008-10-26 07:49:03 +0000459 }
460
461 Visited.insert(MBB);
462
Evan Cheng06587492008-10-24 02:05:00 +0000463 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
464 UMII = Uses.find(MBB);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000465 if (UMII != Uses.end()) {
466 // At least one use in this mbb, lets look for the kill.
Evan Cheng06587492008-10-24 02:05:00 +0000467 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
468 UMII2 = UseMIs.find(MBB);
469 if (ShrinkWrapToLastUse(MBB, UMII->second, UMII2->second))
Evan Chengf5cd4f02008-10-23 20:43:13 +0000470 // Found a kill, shrink wrapping of this path ends here.
471 return;
Evan Cheng06587492008-10-24 02:05:00 +0000472 } else if (MBB == DefMBB) {
473 assert(LIValNoSSMap.find(std::make_pair(CurrLI->reg, ValNo->id)) !=
474 LIValNoSSMap.end() && "Why wasn't def spilled?");
475 // There are no uses after the def.
476 MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
477 assert(RestoreMIs.count(DefMI) && "Not defined by a join?");
478 if (UseMBBs.empty()) {
479 // The only use must be below barrier in the barrier block. It's safe to
480 // remove the def.
481 LIs->RemoveMachineInstrFromMaps(DefMI);
482 DefMI->eraseFromParent();
483 CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
484 }
Evan Cheng79d5b5a2008-10-25 23:49:39 +0000485 } else if (MBB == BarrierMBB) {
486 // Remove entire live range from start of mbb to barrier.
487 CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
488 LIs->getUseIndex(BarrierIdx)+1);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000489 } else {
Evan Cheng79d5b5a2008-10-25 23:49:39 +0000490 // Remove entire live range of the mbb out of the live interval.
Evan Cheng06587492008-10-24 02:05:00 +0000491 CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000492 }
493
494 if (MBB == DefMBB)
495 // Reached the def mbb, stop traversing this path further.
496 return;
497
498 // Traverse the pathes up the predecessor chains further.
499 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
500 PE = MBB->pred_end(); PI != PE; ++PI) {
501 MachineBasicBlock *Pred = *PI;
502 if (Pred == MBB)
503 continue;
504 if (Pred == DefMBB && ValNo->hasPHIKill)
505 // Pred is the def bb and the def reaches other val#s, we must
506 // allow the value to be live out of the bb.
507 continue;
Evan Chengaaf510c2008-10-26 07:49:03 +0000508 ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
509 Uses, UseMIs, UseMBBs);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000510 }
511
512 return;
513}
514
515/// SplitRegLiveInterval - Split (spill and restore) the given live interval
516/// so it would not cross the barrier that's being processed. Shrink wrap
517/// (minimize) the live interval to the last uses.
518bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
519 CurrLI = LI;
520
521 // Find live range where current interval cross the barrier.
522 LiveInterval::iterator LR =
523 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
524 VNInfo *ValNo = LR->valno;
525
526 if (ValNo->def == ~1U) {
527 // Defined by a dead def? How can this be?
528 assert(0 && "Val# is defined by a dead def?");
529 abort();
530 }
531
Evan Cheng06587492008-10-24 02:05:00 +0000532 // FIXME: For now, if definition is rematerializable, do not split.
533 MachineInstr *DefMI = (ValNo->def != ~0U)
534 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
535 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
536 return false;
537
Evan Chengf5cd4f02008-10-23 20:43:13 +0000538 // Find all references in the barrier mbb.
539 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
540 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
541 E = MRI->reg_end(); I != E; ++I) {
542 MachineInstr *RefMI = &*I;
543 if (RefMI->getParent() == BarrierMBB)
544 RefsInMBB.insert(RefMI);
545 }
546
547 // Find a point to restore the value after the barrier.
548 unsigned RestoreIndex;
549 MachineBasicBlock::iterator RestorePt =
Evan Chengf62ce372008-10-28 00:47:49 +0000550 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000551 if (RestorePt == BarrierMBB->end())
552 return false;
553
554 // Add a spill either before the barrier or after the definition.
Evan Cheng06587492008-10-24 02:05:00 +0000555 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000556 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000557 unsigned SpillIndex = 0;
Evan Cheng06587492008-10-24 02:05:00 +0000558 MachineInstr *SpillMI = NULL;
Evan Cheng985921e2008-10-27 23:29:28 +0000559 int SS = -1;
Evan Cheng78dfef72008-10-25 00:52:41 +0000560 bool PrevSpilled = isAlreadySplit(CurrLI->reg, ValNo->id, SS);
561 if (ValNo->def == ~0U) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000562 // If it's defined by a phi, we must split just before the barrier.
563 MachineBasicBlock::iterator SpillPt =
564 findSpillPoint(BarrierMBB, Barrier, RefsInMBB, SpillIndex);
565 if (SpillPt == BarrierMBB->begin())
566 return false; // No gap to insert spill.
567 // Add spill.
Evan Cheng78dfef72008-10-25 00:52:41 +0000568 if (!PrevSpilled)
569 // If previously split, reuse the spill slot.
570 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
Evan Chengf5cd4f02008-10-23 20:43:13 +0000571 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
Evan Cheng06587492008-10-24 02:05:00 +0000572 SpillMI = prior(SpillPt);
573 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
Evan Cheng78dfef72008-10-25 00:52:41 +0000574 } else if (!PrevSpilled) {
Evan Chengb3990d52008-10-27 23:21:01 +0000575 if (!DefMI)
576 // Def is dead. Do nothing.
577 return false;
Evan Cheng78dfef72008-10-25 00:52:41 +0000578 // If it's already split, just restore the value. There is no need to spill
579 // the def again.
Evan Chengf5cd4f02008-10-23 20:43:13 +0000580 // Check if it's possible to insert a spill after the def MI.
Evan Chengf5cd4f02008-10-23 20:43:13 +0000581 MachineBasicBlock::iterator SpillPt =
582 findNextEmptySlot(DefMBB, DefMI, SpillIndex);
583 if (SpillPt == DefMBB->end())
584 return false; // No gap to insert spill.
585 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
586
Evan Cheng78dfef72008-10-25 00:52:41 +0000587 // Add spill. The store instruction kills the register if def is before
588 // the barrier in the barrier block.
Evan Cheng06587492008-10-24 02:05:00 +0000589 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
590 DefMBB == BarrierMBB, SS, RC);
591 SpillMI = prior(SpillPt);
592 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000593 }
594
595 // Add restore.
596 // FIXME: Create live interval for stack slot.
597 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
598 MachineInstr *LoadMI = prior(RestorePt);
599 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
Evan Cheng06587492008-10-24 02:05:00 +0000600 RestoreMIs.insert(LoadMI);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000601
602 // If live interval is spilled in the same block as the barrier, just
603 // create a hole in the interval.
604 if (!DefMBB ||
Evan Cheng78dfef72008-10-25 00:52:41 +0000605 (SpillMI && SpillMI->getParent() == BarrierMBB)) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000606 UpdateIntervalForSplit(ValNo, LIs->getUseIndex(SpillIndex)+1,
607 LIs->getDefIndex(RestoreIndex));
608
609 // Record val# values are in the specific spill slot.
610 RecordSplit(CurrLI->reg, SpillIndex, RestoreIndex, SS);
611
Evan Chengae7fa5b2008-10-28 01:48:24 +0000612 ++NumSplits;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000613 return true;
614 }
615
616 // Shrink wrap the live interval by walking up the CFG and find the
617 // new kills.
618 // Now let's find all the uses of the val#.
Evan Cheng06587492008-10-24 02:05:00 +0000619 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
620 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
621 SmallPtrSet<MachineBasicBlock*, 4> Seen;
622 SmallVector<MachineBasicBlock*, 4> UseMBBs;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000623 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
624 UE = MRI->use_end(); UI != UE; ++UI) {
625 MachineOperand &UseMO = UI.getOperand();
626 MachineInstr *UseMI = UseMO.getParent();
627 unsigned UseIdx = LIs->getInstructionIndex(UseMI);
628 LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
629 if (ULR->valno != ValNo)
630 continue;
631 MachineBasicBlock *UseMBB = UseMI->getParent();
Evan Cheng06587492008-10-24 02:05:00 +0000632 // Remember which other mbb's use this val#.
633 if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
634 UseMBBs.push_back(UseMBB);
635 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
636 UMII = Uses.find(UseMBB);
637 if (UMII != Uses.end()) {
638 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
639 UMII2 = UseMIs.find(UseMBB);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000640 UMII->second.push_back(&UseMO);
Evan Cheng06587492008-10-24 02:05:00 +0000641 UMII2->second.insert(UseMI);
642 } else {
643 SmallVector<MachineOperand*, 4> Ops;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000644 Ops.push_back(&UseMO);
Evan Cheng06587492008-10-24 02:05:00 +0000645 Uses.insert(std::make_pair(UseMBB, Ops));
646 SmallPtrSet<MachineInstr*, 4> MIs;
647 MIs.insert(UseMI);
648 UseMIs.insert(std::make_pair(UseMBB, MIs));
Evan Chengf5cd4f02008-10-23 20:43:13 +0000649 }
650 }
651
652 // Walk up the predecessor chains.
653 SmallPtrSet<MachineBasicBlock*, 8> Visited;
Evan Chengaaf510c2008-10-26 07:49:03 +0000654 ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMBB, Visited,
Evan Cheng06587492008-10-24 02:05:00 +0000655 Uses, UseMIs, UseMBBs);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000656
657 // Remove live range from barrier to the restore. FIXME: Find a better
658 // point to re-start the live interval.
659 UpdateIntervalForSplit(ValNo, LIs->getUseIndex(BarrierIdx)+1,
660 LIs->getDefIndex(RestoreIndex));
661 // Record val# values are in the specific spill slot.
Evan Cheng06587492008-10-24 02:05:00 +0000662 RecordSplit(CurrLI->reg, SpillIndex, RestoreIndex, SS);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000663
Evan Chengae7fa5b2008-10-28 01:48:24 +0000664 ++NumSplits;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000665 return true;
666}
667
668/// SplitRegLiveIntervals - Split all register live intervals that cross the
669/// barrier that's being processed.
670bool
671PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs) {
672 // First find all the virtual registers whose live intervals are intercepted
673 // by the current barrier.
674 SmallVector<LiveInterval*, 8> Intervals;
675 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
Evan Cheng23066282008-10-27 07:14:50 +0000676 if (TII->IgnoreRegisterClassBarriers(*RC))
677 continue;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000678 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
679 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
680 unsigned Reg = VRs[i];
681 if (!LIs->hasInterval(Reg))
682 continue;
683 LiveInterval *LI = &LIs->getInterval(Reg);
684 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
685 // Virtual register live interval is intercepted by the barrier. We
686 // should split and shrink wrap its interval if possible.
687 Intervals.push_back(LI);
688 }
689 }
690
691 // Process the affected live intervals.
692 bool Change = false;
693 while (!Intervals.empty()) {
Evan Chengae7fa5b2008-10-28 01:48:24 +0000694 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
695 break;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000696 LiveInterval *LI = Intervals.back();
697 Intervals.pop_back();
698 Change |= SplitRegLiveInterval(LI);
699 }
700
701 return Change;
702}
703
Evan Cheng09e8ca82008-10-20 21:44:59 +0000704bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000705 CurMF = &MF;
706 TM = &MF.getTarget();
707 TII = TM->getInstrInfo();
708 MFI = MF.getFrameInfo();
709 MRI = &MF.getRegInfo();
710 LIs = &getAnalysis<LiveIntervals>();
711
712 bool MadeChange = false;
713
714 // Make sure blocks are numbered in order.
715 MF.RenumberBlocks();
716
717 for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();
718 I != E; ++I) {
719 BarrierMBB = &*I;
720 for (MachineBasicBlock::reverse_iterator II = BarrierMBB->rbegin(),
721 EE = BarrierMBB->rend(); II != EE; ++II) {
722 Barrier = &*II;
723 const TargetRegisterClass **BarrierRCs =
724 Barrier->getDesc().getRegClassBarriers();
725 if (!BarrierRCs)
726 continue;
727 BarrierIdx = LIs->getInstructionIndex(Barrier);
728 MadeChange |= SplitRegLiveIntervals(BarrierRCs);
729 }
730 }
731
732 return MadeChange;
Evan Cheng09e8ca82008-10-20 21:44:59 +0000733}