- Rewrite code that update register live interval that's split.
[oota-llvm.git] / lib / CodeGen / PreAllocSplitting.cpp
1 //===-- 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"
19 #include "llvm/CodeGen/LiveStackAnalysis.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/Statistic.h"
35 using namespace llvm;
36
37 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
38
39 STATISTIC(NumSplits, "Number of intervals split");
40
41 namespace {
42   class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
43     MachineFunction       *CurrMF;
44     const TargetMachine   *TM;
45     const TargetInstrInfo *TII;
46     MachineFrameInfo      *MFI;
47     MachineRegisterInfo   *MRI;
48     LiveIntervals         *LIs;
49     LiveStacks            *LSs;
50
51     // Barrier - Current barrier being processed.
52     MachineInstr          *Barrier;
53
54     // BarrierMBB - Basic block where the barrier resides in.
55     MachineBasicBlock     *BarrierMBB;
56
57     // Barrier - Current barrier index.
58     unsigned              BarrierIdx;
59
60     // CurrLI - Current live interval being split.
61     LiveInterval          *CurrLI;
62
63     // CurrSLI - Current stack slot live interval.
64     LiveInterval          *CurrSLI;
65
66     // CurrSValNo - Current val# for the stack slot live interval.
67     VNInfo                *CurrSValNo;
68
69     // IntervalSSMap - A map from live interval to spill slots.
70     DenseMap<unsigned, int> IntervalSSMap;
71
72     // RestoreMIs - All the restores inserted due to live interval splitting.
73     SmallPtrSet<MachineInstr*, 8> RestoreMIs;
74
75   public:
76     static char ID;
77     PreAllocSplitting() : MachineFunctionPass(&ID) {}
78
79     virtual bool runOnMachineFunction(MachineFunction &MF);
80
81     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82       AU.addRequired<LiveIntervals>();
83       AU.addPreserved<LiveIntervals>();
84       AU.addRequired<LiveStacks>();
85       AU.addPreserved<LiveStacks>();
86       AU.addPreserved<RegisterCoalescer>();
87       if (StrongPHIElim)
88         AU.addPreservedID(StrongPHIEliminationID);
89       else
90         AU.addPreservedID(PHIEliminationID);
91       MachineFunctionPass::getAnalysisUsage(AU);
92     }
93     
94     virtual void releaseMemory() {
95       IntervalSSMap.clear();
96       RestoreMIs.clear();
97     }
98
99     virtual const char *getPassName() const {
100       return "Pre-Register Allocaton Live Interval Splitting";
101     }
102
103     /// print - Implement the dump method.
104     virtual void print(std::ostream &O, const Module* M = 0) const {
105       LIs->print(O, M);
106     }
107
108     void print(std::ostream *O, const Module* M = 0) const {
109       if (O) print(*O, M);
110     }
111
112   private:
113     MachineBasicBlock::iterator
114       findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
115                         unsigned&);
116
117     MachineBasicBlock::iterator
118       findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
119                      SmallPtrSet<MachineInstr*, 4>&, unsigned&);
120
121     MachineBasicBlock::iterator
122       findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
123                      SmallPtrSet<MachineInstr*, 4>&, unsigned&);
124
125     int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
126
127     bool IsAvailableInStack(unsigned, unsigned, int&) const;
128
129     void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
130
131     void UpdateRegisterInterval(VNInfo*, unsigned, unsigned);
132
133     bool ShrinkWrapToLastUse(MachineBasicBlock*, VNInfo*,
134                              SmallVector<MachineOperand*, 4>&,
135                              SmallPtrSet<MachineInstr*, 4>&);
136
137     void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
138                         MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
139                 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
140                   DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
141                                 SmallVector<MachineBasicBlock*, 4>&);
142
143     bool SplitRegLiveInterval(LiveInterval*);
144
145     bool SplitRegLiveIntervals(const TargetRegisterClass **);
146   };
147 } // end anonymous namespace
148
149 char PreAllocSplitting::ID = 0;
150
151 static RegisterPass<PreAllocSplitting>
152 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
153
154 const PassInfo *const llvm::PreAllocSplittingID = &X;
155
156
157 /// findNextEmptySlot - Find a gap after the given machine instruction in the
158 /// instruction index map. If there isn't one, return end().
159 MachineBasicBlock::iterator
160 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
161                                      unsigned &SpotIndex) {
162   MachineBasicBlock::iterator MII = MI;
163   if (++MII != MBB->end()) {
164     unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
165     if (Index) {
166       SpotIndex = Index;
167       return MII;
168     }
169   }
170   return MBB->end();
171 }
172
173 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
174 /// for spilling the current live interval. The index must be before any
175 /// defs and uses of the live interval register in the mbb. Return begin() if
176 /// none is found.
177 MachineBasicBlock::iterator
178 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
179                                   MachineInstr *DefMI,
180                                   SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
181                                   unsigned &SpillIndex) {
182   MachineBasicBlock::iterator Pt = MBB->begin();
183
184   // Go top down if RefsInMBB is empty.
185   if (RefsInMBB.empty() && !DefMI) {
186     MachineBasicBlock::iterator MII = MBB->begin();
187     MachineBasicBlock::iterator EndPt = MI;
188     do {
189       ++MII;
190       unsigned Index = LIs->getInstructionIndex(MII);
191       unsigned Gap = LIs->findGapBeforeInstr(Index);
192       if (Gap) {
193         Pt = MII;
194         SpillIndex = Gap;
195         break;
196       }
197     } while (MII != EndPt);
198   } else {
199     MachineBasicBlock::iterator MII = MI;
200     MachineBasicBlock::iterator EndPt = DefMI
201       ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
202     while (MII != EndPt && !RefsInMBB.count(MII)) {
203       unsigned Index = LIs->getInstructionIndex(MII);
204       if (LIs->hasGapBeforeInstr(Index)) {
205         Pt = MII;
206         SpillIndex = LIs->findGapBeforeInstr(Index, true);
207       }
208       --MII;
209     }
210   }
211
212   return Pt;
213 }
214
215 /// findRestorePoint - Find a gap in the instruction index map that's suitable
216 /// for restoring the current live interval value. The index must be before any
217 /// uses of the live interval register in the mbb. Return end() if none is
218 /// found.
219 MachineBasicBlock::iterator
220 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
221                                     unsigned LastIdx,
222                                     SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
223                                     unsigned &RestoreIndex) {
224   MachineBasicBlock::iterator Pt = MBB->end();
225   unsigned EndIdx = LIs->getMBBEndIdx(MBB);
226
227   // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
228   // the last index in the live range.
229   if (RefsInMBB.empty() && LastIdx >= EndIdx) {
230     MachineBasicBlock::iterator MII = MBB->end();
231     MachineBasicBlock::iterator EndPt = MI;
232     do {
233       --MII;
234       unsigned Index = LIs->getInstructionIndex(MII);
235       unsigned Gap = LIs->findGapBeforeInstr(Index);
236       if (Gap) {
237         Pt = MII;
238         RestoreIndex = Gap;
239         break;
240       }
241     } while (MII != EndPt);
242   } else {
243     MachineBasicBlock::iterator MII = MI;
244     MII = ++MII;
245     // FIXME: Limit the number of instructions to examine to reduce
246     // compile time?
247     while (MII != MBB->end()) {
248       unsigned Index = LIs->getInstructionIndex(MII);
249       if (Index > LastIdx)
250         break;
251       unsigned Gap = LIs->findGapBeforeInstr(Index);
252       if (Gap) {
253         Pt = MII;
254         RestoreIndex = Gap;
255       }
256       if (RefsInMBB.count(MII))
257         break;
258       ++MII;
259     }
260   }
261
262   return Pt;
263 }
264
265 /// CreateSpillStackSlot - Create a stack slot for the live interval being
266 /// split. If the live interval was previously split, just reuse the same
267 /// slot.
268 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
269                                             const TargetRegisterClass *RC) {
270   int SS;
271   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
272   if (I != IntervalSSMap.end()) {
273     SS = I->second;
274   } else {
275     SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
276     IntervalSSMap[Reg] = SS;
277   }
278
279   // Create live interval for stack slot.
280   CurrSLI = &LSs->getOrCreateInterval(SS);
281   if (CurrSLI->getNumValNums())
282     CurrSValNo = CurrSLI->getValNumInfo(0);
283   else
284     CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
285   return SS;
286 }
287
288 /// IsAvailableInStack - Return true if register is available in a split stack
289 /// slot at the specified index.
290 bool
291 PreAllocSplitting::IsAvailableInStack(unsigned Reg, unsigned Index, int &SS) const {
292   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
293   if (I == IntervalSSMap.end())
294     return false;
295   if (LSs->getInterval(I->second).liveAt(Index)) {
296     SS = I->second;
297     return true;
298   }
299   return false;
300 }
301
302 /// UpdateSpillSlotInterval - Given the specified val# of the register live
303 /// interval being split, and the spill and restore indicies, update the live
304 /// interval of the spill stack slot.
305 void
306 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
307                                            unsigned RestoreIndex) {
308   const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
309   if (LR->contains(RestoreIndex)) {
310     LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
311     CurrSLI->addRange(SLR);
312     return;
313   }
314
315   SmallPtrSet<const LiveRange*, 4> Processed;
316   LiveRange SLR(SpillIndex, LR->end, CurrSValNo);
317   CurrSLI->addRange(SLR);
318   Processed.insert(LR);
319
320   // Start from the spill mbb, figure out the extend of the spill slot's
321   // live interval.
322   SmallVector<MachineBasicBlock*, 4> WorkList;
323   MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
324   if (LR->end > LIs->getMBBEndIdx(MBB))
325     // If live range extend beyond end of mbb, add successors to work list.
326     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
327            SE = MBB->succ_end(); SI != SE; ++SI)
328       WorkList.push_back(*SI);
329   // Live range may cross multiple basic blocks, add all reachable mbbs to
330   // the work list.
331   LIs->findReachableMBBs(LR->start, LR->end, WorkList);
332
333   while (!WorkList.empty()) {
334     MachineBasicBlock *MBB = WorkList.back();
335     WorkList.pop_back();
336     unsigned Idx = LIs->getMBBStartIdx(MBB);
337     LR = CurrLI->getLiveRangeContaining(Idx);
338     if (LR && LR->valno == ValNo && !Processed.count(LR)) {
339       if (LR->contains(RestoreIndex)) {
340         // Spill slot live interval stops at the restore.
341         LiveRange SLR(LR->start, RestoreIndex, CurrSValNo);
342         CurrSLI->addRange(SLR);
343         LIs->findReachableMBBs(LR->start, RestoreIndex, WorkList);
344       } else {
345         LiveRange SLR(LR->start, LR->end, CurrSValNo);
346         CurrSLI->addRange(SLR);
347         LIs->findReachableMBBs(LR->start, LR->end, WorkList);
348       }
349       Processed.insert(LR);
350     }
351   }
352 }
353
354 /// UpdateRegisterInterval - Given the specified val# of the current live
355 /// interval is being split, and the spill and restore indices, update the live
356 /// interval accordingly.
357 void
358 PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
359                                           unsigned RestoreIndex) {
360   SmallVector<std::pair<unsigned,unsigned>, 4> Before;
361   SmallVector<std::pair<unsigned,unsigned>, 4> After;
362   SmallVector<unsigned, 4> BeforeKills;
363   SmallVector<unsigned, 4> AfterKills;
364   SmallPtrSet<const LiveRange*, 4> Processed;
365
366   // First, let's figure out which parts of the live interval is now defined
367   // by the restore, which are defined by the original definition.
368   const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
369   After.push_back(std::make_pair(RestoreIndex, LR->end));
370   if (CurrLI->isKill(ValNo, LR->end))
371     AfterKills.push_back(LR->end);
372
373   assert(LR->contains(SpillIndex));
374   if (SpillIndex > LR->start) {
375     Before.push_back(std::make_pair(LR->start, SpillIndex));
376     BeforeKills.push_back(SpillIndex);
377   }
378   Processed.insert(LR);
379
380   // Start from the restore mbb, figure out what part of the live interval
381   // are defined by the restore.
382   SmallVector<MachineBasicBlock*, 4> WorkList;
383   MachineBasicBlock *MBB = LIs->getMBBFromIndex(RestoreIndex);
384   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
385          SE = MBB->succ_end(); SI != SE; ++SI)
386     WorkList.push_back(*SI);
387
388   while (!WorkList.empty()) {
389     MBB = WorkList.back();
390     WorkList.pop_back();
391     unsigned Idx = LIs->getMBBStartIdx(MBB);
392     LR = CurrLI->getLiveRangeContaining(Idx);
393     if (LR && LR->valno == ValNo && !Processed.count(LR)) {
394       After.push_back(std::make_pair(LR->start, LR->end));
395       if (CurrLI->isKill(ValNo, LR->end))
396         AfterKills.push_back(LR->end);
397       Idx = LIs->getMBBEndIdx(MBB);
398       if (LR->end > Idx) {
399         // Live range extend beyond at least one mbb. Let's see what other
400         // mbbs it reaches.
401         LIs->findReachableMBBs(LR->start, LR->end, WorkList);
402       }
403       Processed.insert(LR);
404     }
405   }
406
407   for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
408        I != E; ++I) {
409     LiveRange *LR = I;
410     if (LR->valno == ValNo && !Processed.count(LR)) {
411       Before.push_back(std::make_pair(LR->start, LR->end));
412       if (CurrLI->isKill(ValNo, LR->end))
413         BeforeKills.push_back(LR->end);
414     }
415   }
416
417   // Now create new val#s to represent the live ranges defined by the old def
418   // those defined by the restore.
419   unsigned AfterDef = ValNo->def;
420   MachineInstr *AfterCopy = ValNo->copy;
421   bool HasPHIKill = ValNo->hasPHIKill;
422   CurrLI->removeValNo(ValNo);
423   VNInfo *BValNo = (Before.empty())
424     ? NULL
425     : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
426   if (BValNo)
427     CurrLI->addKills(BValNo, BeforeKills);
428
429   VNInfo *AValNo = (After.empty())
430     ? NULL
431     : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
432   if (AValNo) {
433     AValNo->hasPHIKill = HasPHIKill;
434     CurrLI->addKills(AValNo, AfterKills);
435   }
436
437   for (unsigned i = 0, e = Before.size(); i != e; ++i) {
438     unsigned Start = Before[i].first;
439     unsigned End   = Before[i].second;
440     CurrLI->addRange(LiveRange(Start, End, BValNo));
441   }
442   for (unsigned i = 0, e = After.size(); i != e; ++i) {
443     unsigned Start = After[i].first;
444     unsigned End   = After[i].second;
445     CurrLI->addRange(LiveRange(Start, End, AValNo));
446   }
447 }
448
449 /// ShrinkWrapToLastUse - There are uses of the current live interval in the
450 /// given block, shrink wrap the live interval to the last use (i.e. remove
451 /// from last use to the end of the mbb). In case mbb is the where the barrier
452 /// is, remove from the last use to the barrier.
453 bool
454 PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
455                                        SmallVector<MachineOperand*, 4> &Uses,
456                                        SmallPtrSet<MachineInstr*, 4> &UseMIs) {
457   MachineOperand *LastMO = 0;
458   MachineInstr *LastMI = 0;
459   if (MBB != BarrierMBB && Uses.size() == 1) {
460     // Single use, no need to traverse the block. We can't assume this for the
461     // barrier bb though since the use is probably below the barrier.
462     LastMO = Uses[0];
463     LastMI = LastMO->getParent();
464   } else {
465     MachineBasicBlock::iterator MEE = MBB->begin();
466     MachineBasicBlock::iterator MII;
467     if (MBB == BarrierMBB)
468       MII = Barrier;
469     else
470       MII = MBB->end();
471     while (MII != MEE) {
472       --MII;
473       MachineInstr *UseMI = &*MII;
474       if (!UseMIs.count(UseMI))
475         continue;
476       for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
477         MachineOperand &MO = UseMI->getOperand(i);
478         if (MO.isReg() && MO.getReg() == CurrLI->reg) {
479           LastMO = &MO;
480           break;
481         }
482       }
483       LastMI = UseMI;
484       break;
485     }
486   }
487
488   // Cut off live range from last use (or beginning of the mbb if there
489   // are no uses in it) to the end of the mbb.
490   unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
491   if (LastMI) {
492     RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
493     assert(!LastMO->isKill() && "Last use already terminates the interval?");
494     LastMO->setIsKill();
495   } else {
496     assert(MBB == BarrierMBB);
497     RangeStart = LIs->getMBBStartIdx(MBB);
498   }
499   if (MBB == BarrierMBB)
500     RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
501   CurrLI->removeRange(RangeStart, RangeEnd);
502   if (LastMI)
503     CurrLI->addKill(ValNo, RangeStart);
504
505   // Return true if the last use becomes a new kill.
506   return LastMI;
507 }
508
509 /// ShrinkWrapLiveInterval - Recursively traverse the predecessor
510 /// chain to find the new 'kills' and shrink wrap the live interval to the
511 /// new kill indices.
512 void
513 PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
514                           MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
515                                     SmallPtrSet<MachineBasicBlock*, 8> &Visited,
516            DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
517            DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
518                                   SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
519   if (Visited.count(MBB))
520     return;
521
522   // If live interval is live in another successor path, then we can't process
523   // this block. But we may able to do so after all the successors have been
524   // processed.
525   if (MBB != BarrierMBB) {
526     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
527            SE = MBB->succ_end(); SI != SE; ++SI) {
528       MachineBasicBlock *SMBB = *SI;
529       if (SMBB == SuccMBB)
530         continue;
531       if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
532         return;
533     }
534   }
535
536   Visited.insert(MBB);
537
538   DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
539     UMII = Uses.find(MBB);
540   if (UMII != Uses.end()) {
541     // At least one use in this mbb, lets look for the kill.
542     DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
543       UMII2 = UseMIs.find(MBB);
544     if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
545       // Found a kill, shrink wrapping of this path ends here.
546       return;
547   } else if (MBB == DefMBB) {
548     // There are no uses after the def.
549     MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
550     assert(RestoreMIs.count(DefMI) && "Not defined by a join?");
551     if (UseMBBs.empty()) {
552       // The only use must be below barrier in the barrier block. It's safe to
553       // remove the def.
554       LIs->RemoveMachineInstrFromMaps(DefMI);
555       DefMI->eraseFromParent();
556       CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
557     }
558   } else if (MBB == BarrierMBB) {
559     // Remove entire live range from start of mbb to barrier.
560     CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
561                         LIs->getUseIndex(BarrierIdx)+1);
562   } else {
563     // Remove entire live range of the mbb out of the live interval.
564     CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
565   }
566
567   if (MBB == DefMBB)
568     // Reached the def mbb, stop traversing this path further.
569     return;
570
571   // Traverse the pathes up the predecessor chains further.
572   for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
573          PE = MBB->pred_end(); PI != PE; ++PI) {
574     MachineBasicBlock *Pred = *PI;
575     if (Pred == MBB)
576       continue;
577     if (Pred == DefMBB && ValNo->hasPHIKill)
578       // Pred is the def bb and the def reaches other val#s, we must
579       // allow the value to be live out of the bb.
580       continue;
581     ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
582                            Uses, UseMIs, UseMBBs);
583   }
584
585   return;
586 }
587
588 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
589 /// so it would not cross the barrier that's being processed. Shrink wrap
590 /// (minimize) the live interval to the last uses.
591 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
592   CurrLI = LI;
593
594   // Find live range where current interval cross the barrier.
595   LiveInterval::iterator LR =
596     CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
597   VNInfo *ValNo = LR->valno;
598
599   if (ValNo->def == ~1U) {
600     // Defined by a dead def? How can this be?
601     assert(0 && "Val# is defined by a dead def?");
602     abort();
603   }
604
605   // FIXME: For now, if definition is rematerializable, do not split.
606   MachineInstr *DefMI = (ValNo->def != ~0U)
607     ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
608   if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
609     return false;
610
611   // Find all references in the barrier mbb.
612   SmallPtrSet<MachineInstr*, 4> RefsInMBB;
613   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
614          E = MRI->reg_end(); I != E; ++I) {
615     MachineInstr *RefMI = &*I;
616     if (RefMI->getParent() == BarrierMBB)
617       RefsInMBB.insert(RefMI);
618   }
619
620   // Find a point to restore the value after the barrier.
621   unsigned RestoreIndex;
622   MachineBasicBlock::iterator RestorePt =
623     findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
624   if (RestorePt == BarrierMBB->end())
625     return false;
626
627   // Add a spill either before the barrier or after the definition.
628   MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
629   const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
630   unsigned SpillIndex = 0;
631   MachineInstr *SpillMI = NULL;
632   int SS = -1;
633   if (ValNo->def == ~0U) {
634     // If it's defined by a phi, we must split just before the barrier.
635     MachineBasicBlock::iterator SpillPt = 
636       findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
637     if (SpillPt == BarrierMBB->begin())
638       return false; // No gap to insert spill.
639     // Add spill.
640     SS = CreateSpillStackSlot(CurrLI->reg, RC);
641     TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
642     SpillMI = prior(SpillPt);
643     LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
644   } else if (!IsAvailableInStack(CurrLI->reg, RestoreIndex, SS)) {
645     // If it's already split, just restore the value. There is no need to spill
646     // the def again.
647     if (!DefMI)
648       return false; // Def is dead. Do nothing.
649     // Check if it's possible to insert a spill after the def MI.
650     MachineBasicBlock::iterator SpillPt;
651     if (DefMBB == BarrierMBB) {
652       // Add spill after the def and the last use before the barrier.
653       SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI, RefsInMBB, SpillIndex);
654       if (SpillPt == DefMBB->begin())
655         return false; // No gap to insert spill.
656     } else {
657       SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
658       if (SpillPt == DefMBB->end())
659         return false; // No gap to insert spill.
660     }
661     // Add spill. The store instruction kills the register if def is before
662     // the barrier in the barrier block.
663     SS = CreateSpillStackSlot(CurrLI->reg, RC);
664     TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
665                              DefMBB == BarrierMBB, SS, RC);
666     SpillMI = prior(SpillPt);
667     LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
668   }
669
670   // Add restore.
671   TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
672   MachineInstr *LoadMI = prior(RestorePt);
673   LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
674   RestoreMIs.insert(LoadMI);
675
676   // If live interval is spilled in the same block as the barrier, just
677   // create a hole in the interval.
678   if (!DefMBB ||
679       (SpillMI && SpillMI->getParent() == BarrierMBB)) {
680     // Update spill stack slot live interval.
681     UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
682                             LIs->getDefIndex(RestoreIndex));
683
684     UpdateRegisterInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
685                            LIs->getDefIndex(RestoreIndex));
686
687     ++NumSplits;
688     return true;
689   }
690
691   // Update spill stack slot live interval.
692   if (SpillIndex)
693     // If value is already in stack at the restore point, there is
694     // no need to update the live interval.
695     UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
696                             LIs->getDefIndex(RestoreIndex));
697
698   // Shrink wrap the live interval by walking up the CFG and find the
699   // new kills.
700   // Now let's find all the uses of the val#.
701   DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
702   DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
703   SmallPtrSet<MachineBasicBlock*, 4> Seen;
704   SmallVector<MachineBasicBlock*, 4> UseMBBs;
705   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
706          UE = MRI->use_end(); UI != UE; ++UI) {
707     MachineOperand &UseMO = UI.getOperand();
708     MachineInstr *UseMI = UseMO.getParent();
709     unsigned UseIdx = LIs->getInstructionIndex(UseMI);
710     LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
711     if (ULR->valno != ValNo)
712       continue;
713     MachineBasicBlock *UseMBB = UseMI->getParent();
714     // Remember which other mbb's use this val#.
715     if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
716       UseMBBs.push_back(UseMBB);
717     DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
718       UMII = Uses.find(UseMBB);
719     if (UMII != Uses.end()) {
720       DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
721         UMII2 = UseMIs.find(UseMBB);
722       UMII->second.push_back(&UseMO);
723       UMII2->second.insert(UseMI);
724     } else {
725       SmallVector<MachineOperand*, 4> Ops;
726       Ops.push_back(&UseMO);
727       Uses.insert(std::make_pair(UseMBB, Ops));
728       SmallPtrSet<MachineInstr*, 4> MIs;
729       MIs.insert(UseMI);
730       UseMIs.insert(std::make_pair(UseMBB, MIs));
731     }
732   }
733
734   // Walk up the predecessor chains.
735   SmallPtrSet<MachineBasicBlock*, 8> Visited;
736   ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMBB, Visited,
737                          Uses, UseMIs, UseMBBs);
738
739   // Remove live range from barrier to the restore. FIXME: Find a better
740   // point to re-start the live interval.
741   UpdateRegisterInterval(ValNo, LIs->getUseIndex(BarrierIdx)+1,
742                          LIs->getDefIndex(RestoreIndex));
743
744   ++NumSplits;
745   return true;
746 }
747
748 /// SplitRegLiveIntervals - Split all register live intervals that cross the
749 /// barrier that's being processed.
750 bool
751 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs) {
752   // First find all the virtual registers whose live intervals are intercepted
753   // by the current barrier.
754   SmallVector<LiveInterval*, 8> Intervals;
755   for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
756     if (TII->IgnoreRegisterClassBarriers(*RC))
757       continue;
758     std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
759     for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
760       unsigned Reg = VRs[i];
761       if (!LIs->hasInterval(Reg))
762         continue;
763       LiveInterval *LI = &LIs->getInterval(Reg);
764       if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
765         // Virtual register live interval is intercepted by the barrier. We
766         // should split and shrink wrap its interval if possible.
767         Intervals.push_back(LI);
768     }
769   }
770
771   // Process the affected live intervals.
772   bool Change = false;
773   while (!Intervals.empty()) {
774     if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
775       break;
776     LiveInterval *LI = Intervals.back();
777     Intervals.pop_back();
778     Change |= SplitRegLiveInterval(LI);
779   }
780
781   return Change;
782 }
783
784 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
785   CurrMF = &MF;
786   TM     = &MF.getTarget();
787   TII    = TM->getInstrInfo();
788   MFI    = MF.getFrameInfo();
789   MRI    = &MF.getRegInfo();
790   LIs    = &getAnalysis<LiveIntervals>();
791   LSs    = &getAnalysis<LiveStacks>();
792
793   bool MadeChange = false;
794
795   // Make sure blocks are numbered in order.
796   MF.RenumberBlocks();
797
798   for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();
799        I != E; ++I) {
800     BarrierMBB = &*I;
801     for (MachineBasicBlock::reverse_iterator II = BarrierMBB->rbegin(),
802            EE = BarrierMBB->rend(); II != EE; ++II) {
803       Barrier = &*II;
804       const TargetRegisterClass **BarrierRCs =
805         Barrier->getDesc().getRegClassBarriers();
806       if (!BarrierRCs)
807         continue;
808       BarrierIdx = LIs->getInstructionIndex(Barrier);
809       MadeChange |= SplitRegLiveIntervals(BarrierRCs);
810     }
811   }
812
813   return MadeChange;
814 }