b6efe0624de6f75272ea2d4f67cbe9e4ce6929c7
[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/MachineFrameInfo.h"
20 #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"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #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"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include <map>
34 using namespace llvm;
35
36 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
37
38 STATISTIC(NumSplits, "Number of intervals split");
39
40 namespace {
41   class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
42     MachineFunction       *CurMF;
43     const TargetMachine   *TM;
44     const TargetInstrInfo *TII;
45     MachineFrameInfo      *MFI;
46     MachineRegisterInfo   *MRI;
47     LiveIntervals         *LIs;
48
49     // 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
66     // RestoreMIs - All the restores inserted due to live interval splitting.
67     SmallPtrSet<MachineInstr*, 8> RestoreMIs;
68
69   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>();
78       AU.addPreserved<RegisterCoalescer>();
79       if (StrongPHIElim)
80         AU.addPreservedID(StrongPHIEliminationID);
81       else
82         AU.addPreservedID(PHIEliminationID);
83       MachineFunctionPass::getAnalysisUsage(AU);
84     }
85     
86     virtual void releaseMemory() {
87       LIValNoSSMap.clear();
88       RestoreMIs.clear();
89     }
90
91     virtual const char *getPassName() const {
92       return "Pre-Register Allocaton Live Interval Splitting";
93     }
94
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
114       findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
115                      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*,
124                              SmallVector<MachineOperand*, 4>&,
125                              SmallPtrSet<MachineInstr*, 4>&);
126
127     void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
128                         MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
129                 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
130                   DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
131                                 SmallVector<MachineBasicBlock*, 4>&);
132
133     bool SplitRegLiveInterval(LiveInterval*);
134
135     bool SplitRegLiveIntervals(const TargetRegisterClass **);
136   };
137 } // end anonymous namespace
138
139 char PreAllocSplitting::ID = 0;
140
141 static RegisterPass<PreAllocSplitting>
142 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
143
144 const PassInfo *const llvm::PreAllocSplittingID = &X;
145
146
147 /// findNextEmptySlot - Find a gap after the given machine instruction in the
148 /// instruction index map. If there isn't one, return end().
149 MachineBasicBlock::iterator
150 PreAllocSplitting::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.
167 MachineBasicBlock::iterator
168 PreAllocSplitting::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.
206 MachineBasicBlock::iterator
207 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
208                                     unsigned LastIdx,
209                                     SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
210                                     unsigned &RestoreIndex) {
211   MachineBasicBlock::iterator Pt = MBB->end();
212   unsigned EndIdx = LIs->getMBBEndIdx(MBB);
213
214   // 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) {
217     MachineBasicBlock::iterator MII = MBB->end();
218     MachineBasicBlock::iterator EndPt = MI;
219     do {
220       --MII;
221       unsigned Index = LIs->getInstructionIndex(MII);
222       unsigned Gap = LIs->findGapBeforeInstr(Index);
223       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;
232     // FIXME: Limit the number of instructions to examine to reduce
233     // compile time?
234     while (MII != MBB->end()) {
235       unsigned Index = LIs->getInstructionIndex(MII);
236       if (Index > LastIdx)
237         break;
238       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.
254 void PreAllocSplitting::RecordSplit(unsigned Reg, unsigned SpillIndex,
255                                     unsigned RestoreIndex, int SS) {
256   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));
265 }
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.
269 bool 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.
281 void
282 PreAllocSplitting::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));
294   if (CurrLI->isKill(ValNo, LR->end))
295     AfterKills.push_back(LR->end);
296
297   assert(LR->contains(SplitIndex));
298   if (SplitIndex > LR->start) {
299     Before.push_back(std::make_pair(LR->start, SplitIndex));
300     BeforeKills.push_back(SplitIndex);
301   }
302   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);
351   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   }
364
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.
381 bool
382 PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB,
383                                        SmallVector<MachineOperand*, 4> &Uses,
384                                        SmallPtrSet<MachineInstr*, 4> &UseMIs) {
385   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 {
393     MachineBasicBlock::iterator MEE = MBB->begin();
394     MachineBasicBlock::iterator MII;
395     if (MBB == BarrierMBB)
396       MII = Barrier;
397     else
398       MII = MBB->end();
399     while (--MII != MEE) {
400       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)
427     RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
428   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.
437 void
438 PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
439                           MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
440                                     SmallPtrSet<MachineBasicBlock*, 8> &Visited,
441            DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
442            DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
443                                   SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
444   if (Visited.count(MBB))
445     return;
446
447   // 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.
450   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     }
459   }
460
461   Visited.insert(MBB);
462
463   DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
464     UMII = Uses.find(MBB);
465   if (UMII != Uses.end()) {
466     // At least one use in this mbb, lets look for the kill.
467     DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
468       UMII2 = UseMIs.find(MBB);
469     if (ShrinkWrapToLastUse(MBB, UMII->second, UMII2->second))
470       // Found a kill, shrink wrapping of this path ends here.
471       return;
472   } 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     }
485   } 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);
489   } else {
490     // Remove entire live range of the mbb out of the live interval.
491     CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
492   }
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;
508     ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
509                            Uses, UseMIs, UseMBBs);
510   }
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.
518 bool 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
532   // 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
538   // 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 =
550     findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
551   if (RestorePt == BarrierMBB->end())
552     return false;
553
554   // Add a spill either before the barrier or after the definition.
555   MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
556   const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
557   unsigned SpillIndex = 0;
558   MachineInstr *SpillMI = NULL;
559   int SS = -1;
560   bool PrevSpilled = isAlreadySplit(CurrLI->reg, ValNo->id, SS);
561   if (ValNo->def == ~0U) {
562     // 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.
568     if (!PrevSpilled)
569       // If previously split, reuse the spill slot.
570       SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
571     TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
572     SpillMI = prior(SpillPt);
573     LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
574   } else if (!PrevSpilled) {
575     if (!DefMI)
576       // Def is dead. Do nothing.
577       return false;
578     // If it's already split, just restore the value. There is no need to spill
579     // the def again.
580     // Check if it's possible to insert a spill after the def MI.
581     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
587     // Add spill. The store instruction kills the register if def is before
588     // the barrier in the barrier block.
589     TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
590                              DefMBB == BarrierMBB, SS, RC);
591     SpillMI = prior(SpillPt);
592     LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
593   }
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);
600   RestoreMIs.insert(LoadMI);
601
602   // If live interval is spilled in the same block as the barrier, just
603   // create a hole in the interval.
604   if (!DefMBB ||
605       (SpillMI && SpillMI->getParent() == BarrierMBB)) {
606     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
612     ++NumSplits;
613     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#.
619   DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
620   DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
621   SmallPtrSet<MachineBasicBlock*, 4> Seen;
622   SmallVector<MachineBasicBlock*, 4> UseMBBs;
623   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();
632     // 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);
640       UMII->second.push_back(&UseMO);
641       UMII2->second.insert(UseMI);
642     } else {
643       SmallVector<MachineOperand*, 4> Ops;
644       Ops.push_back(&UseMO);
645       Uses.insert(std::make_pair(UseMBB, Ops));
646       SmallPtrSet<MachineInstr*, 4> MIs;
647       MIs.insert(UseMI);
648       UseMIs.insert(std::make_pair(UseMBB, MIs));
649     }
650   }
651
652   // Walk up the predecessor chains.
653   SmallPtrSet<MachineBasicBlock*, 8> Visited;
654   ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMBB, Visited,
655                          Uses, UseMIs, UseMBBs);
656
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.
662   RecordSplit(CurrLI->reg, SpillIndex, RestoreIndex, SS);
663
664   ++NumSplits;
665   return true;
666 }
667
668 /// SplitRegLiveIntervals - Split all register live intervals that cross the
669 /// barrier that's being processed.
670 bool
671 PreAllocSplitting::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) {
676     if (TII->IgnoreRegisterClassBarriers(*RC))
677       continue;
678     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()) {
694     if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
695       break;
696     LiveInterval *LI = Intervals.back();
697     Intervals.pop_back();
698     Change |= SplitRegLiveInterval(LI);
699   }
700
701   return Change;
702 }
703
704 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
705   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;
733 }