Also revert r63206
[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/MachineDominators.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/DepthFirstIterator.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/Statistic.h"
37 using namespace llvm;
38
39 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
40
41 STATISTIC(NumSplits, "Number of intervals split");
42 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
43 STATISTIC(NumFolds, "Number of intervals split with spill folding");
44 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
45 STATISTIC(NumDeadSpills, "Number of dead spills removed");
46
47 namespace {
48   class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
49     MachineFunction       *CurrMF;
50     const TargetMachine   *TM;
51     const TargetInstrInfo *TII;
52     MachineFrameInfo      *MFI;
53     MachineRegisterInfo   *MRI;
54     LiveIntervals         *LIs;
55     LiveStacks            *LSs;
56
57     // Barrier - Current barrier being processed.
58     MachineInstr          *Barrier;
59
60     // BarrierMBB - Basic block where the barrier resides in.
61     MachineBasicBlock     *BarrierMBB;
62
63     // Barrier - Current barrier index.
64     unsigned              BarrierIdx;
65
66     // CurrLI - Current live interval being split.
67     LiveInterval          *CurrLI;
68
69     // CurrSLI - Current stack slot live interval.
70     LiveInterval          *CurrSLI;
71
72     // CurrSValNo - Current val# for the stack slot live interval.
73     VNInfo                *CurrSValNo;
74
75     // IntervalSSMap - A map from live interval to spill slots.
76     DenseMap<unsigned, int> IntervalSSMap;
77
78     // Def2SpillMap - A map from a def instruction index to spill index.
79     DenseMap<unsigned, unsigned> Def2SpillMap;
80
81   public:
82     static char ID;
83     PreAllocSplitting() : MachineFunctionPass(&ID) {}
84
85     virtual bool runOnMachineFunction(MachineFunction &MF);
86
87     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88       AU.addRequired<LiveIntervals>();
89       AU.addPreserved<LiveIntervals>();
90       AU.addRequired<LiveStacks>();
91       AU.addPreserved<LiveStacks>();
92       AU.addPreserved<RegisterCoalescer>();
93       if (StrongPHIElim)
94         AU.addPreservedID(StrongPHIEliminationID);
95       else
96         AU.addPreservedID(PHIEliminationID);
97       AU.addRequired<MachineDominatorTree>();
98       AU.addRequired<MachineLoopInfo>();
99       AU.addPreserved<MachineDominatorTree>();
100       AU.addPreserved<MachineLoopInfo>();
101       MachineFunctionPass::getAnalysisUsage(AU);
102     }
103     
104     virtual void releaseMemory() {
105       IntervalSSMap.clear();
106       Def2SpillMap.clear();
107     }
108
109     virtual const char *getPassName() const {
110       return "Pre-Register Allocaton Live Interval Splitting";
111     }
112
113     /// print - Implement the dump method.
114     virtual void print(std::ostream &O, const Module* M = 0) const {
115       LIs->print(O, M);
116     }
117
118     void print(std::ostream *O, const Module* M = 0) const {
119       if (O) print(*O, M);
120     }
121
122   private:
123     MachineBasicBlock::iterator
124       findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
125                         unsigned&);
126
127     MachineBasicBlock::iterator
128       findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
129                      SmallPtrSet<MachineInstr*, 4>&, unsigned&);
130
131     MachineBasicBlock::iterator
132       findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
133                      SmallPtrSet<MachineInstr*, 4>&, unsigned&);
134
135     int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
136
137     bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
138                             unsigned&, int&) const;
139
140     void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
141
142     VNInfo* UpdateRegisterInterval(VNInfo*, unsigned, unsigned);
143
144     bool ShrinkWrapToLastUse(MachineBasicBlock*, VNInfo*,
145                              SmallVector<MachineOperand*, 4>&,
146                              SmallPtrSet<MachineInstr*, 4>&);
147
148     void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
149                         MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
150                 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
151                   DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
152                                 SmallVector<MachineBasicBlock*, 4>&);
153
154     bool SplitRegLiveInterval(LiveInterval*);
155
156     bool SplitRegLiveIntervals(const TargetRegisterClass **,
157                                SmallPtrSet<LiveInterval*, 8>&);
158     
159     void RepairLiveInterval(LiveInterval* CurrLI, VNInfo* ValNo,
160                             MachineInstr* DefMI, unsigned RestoreIdx);
161     
162     bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
163                         MachineBasicBlock* BarrierMBB);
164     bool Rematerialize(unsigned vreg, VNInfo* ValNo,
165                        MachineInstr* DefMI,
166                        MachineBasicBlock::iterator RestorePt,
167                        unsigned RestoreIdx,
168                        SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
169     MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
170                             MachineInstr* DefMI,
171                             MachineInstr* Barrier,
172                             MachineBasicBlock* MBB,
173                             int& SS,
174                             SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
175     void RenumberValno(VNInfo* VN);
176     void ReconstructLiveInterval(LiveInterval* LI);
177     bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
178     unsigned getNumberOfSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
179                                unsigned Reg, int FrameIndex);
180     VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator use,
181                                    MachineBasicBlock* MBB,
182                                    LiveInterval* LI,
183                                    SmallPtrSet<MachineInstr*, 4>& Visited,
184             DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
185             DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
186                                       DenseMap<MachineInstr*, VNInfo*>& NewVNs,
187                                 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
188                                 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
189                                         bool toplevel, bool intrablock);
190 };
191 } // end anonymous namespace
192
193 char PreAllocSplitting::ID = 0;
194
195 static RegisterPass<PreAllocSplitting>
196 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
197
198 const PassInfo *const llvm::PreAllocSplittingID = &X;
199
200
201 /// findNextEmptySlot - Find a gap after the given machine instruction in the
202 /// instruction index map. If there isn't one, return end().
203 MachineBasicBlock::iterator
204 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
205                                      unsigned &SpotIndex) {
206   MachineBasicBlock::iterator MII = MI;
207   if (++MII != MBB->end()) {
208     unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
209     if (Index) {
210       SpotIndex = Index;
211       return MII;
212     }
213   }
214   return MBB->end();
215 }
216
217 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
218 /// for spilling the current live interval. The index must be before any
219 /// defs and uses of the live interval register in the mbb. Return begin() if
220 /// none is found.
221 MachineBasicBlock::iterator
222 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
223                                   MachineInstr *DefMI,
224                                   SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
225                                   unsigned &SpillIndex) {
226   MachineBasicBlock::iterator Pt = MBB->begin();
227
228   // Go top down if RefsInMBB is empty.
229   if (RefsInMBB.empty() && !DefMI) {
230     MachineBasicBlock::iterator MII = MBB->begin();
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         SpillIndex = Gap;
239         break;
240       }
241     } while (MII != EndPt);
242   } else {
243     MachineBasicBlock::iterator MII = MI;
244     MachineBasicBlock::iterator EndPt = DefMI
245       ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
246     while (MII != EndPt && !RefsInMBB.count(MII)) {
247       unsigned Index = LIs->getInstructionIndex(MII);
248       if (LIs->hasGapBeforeInstr(Index)) {
249         Pt = MII;
250         SpillIndex = LIs->findGapBeforeInstr(Index, true);
251       }
252       --MII;
253     }
254   }
255
256   return Pt;
257 }
258
259 /// findRestorePoint - Find a gap in the instruction index map that's suitable
260 /// for restoring the current live interval value. The index must be before any
261 /// uses of the live interval register in the mbb. Return end() if none is
262 /// found.
263 MachineBasicBlock::iterator
264 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
265                                     unsigned LastIdx,
266                                     SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
267                                     unsigned &RestoreIndex) {
268   // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
269   // begin index accordingly.
270   MachineBasicBlock::iterator Pt = MBB->end();
271   unsigned EndIdx = LIs->getMBBEndIdx(MBB);
272
273   // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
274   // the last index in the live range.
275   if (RefsInMBB.empty() && LastIdx >= EndIdx) {
276     MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
277     MachineBasicBlock::iterator EndPt = MI;
278     --MII;
279     do {
280       unsigned Index = LIs->getInstructionIndex(MII);
281       unsigned Gap = LIs->findGapBeforeInstr(Index);
282       if (Gap) {
283         Pt = MII;
284         RestoreIndex = Gap;
285         break;
286       }
287       --MII;
288     } while (MII != EndPt);
289   } else {
290     MachineBasicBlock::iterator MII = MI;
291     MII = ++MII;
292     // FIXME: Limit the number of instructions to examine to reduce
293     // compile time?
294     while (MII != MBB->end()) {
295       unsigned Index = LIs->getInstructionIndex(MII);
296       if (Index > LastIdx)
297         break;
298       unsigned Gap = LIs->findGapBeforeInstr(Index);
299       if (Gap) {
300         Pt = MII;
301         RestoreIndex = Gap;
302       }
303       if (RefsInMBB.count(MII))
304         break;
305       ++MII;
306     }
307   }
308
309   return Pt;
310 }
311
312 /// CreateSpillStackSlot - Create a stack slot for the live interval being
313 /// split. If the live interval was previously split, just reuse the same
314 /// slot.
315 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
316                                             const TargetRegisterClass *RC) {
317   int SS;
318   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
319   if (I != IntervalSSMap.end()) {
320     SS = I->second;
321   } else {
322     SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
323     IntervalSSMap[Reg] = SS;
324   }
325
326   // Create live interval for stack slot.
327   CurrSLI = &LSs->getOrCreateInterval(SS);
328   if (CurrSLI->hasAtLeastOneValue())
329     CurrSValNo = CurrSLI->getValNumInfo(0);
330   else
331     CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
332   return SS;
333 }
334
335 /// IsAvailableInStack - Return true if register is available in a split stack
336 /// slot at the specified index.
337 bool
338 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
339                                     unsigned Reg, unsigned DefIndex,
340                                     unsigned RestoreIndex, unsigned &SpillIndex,
341                                     int& SS) const {
342   if (!DefMBB)
343     return false;
344
345   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
346   if (I == IntervalSSMap.end())
347     return false;
348   DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
349   if (II == Def2SpillMap.end())
350     return false;
351
352   // If last spill of def is in the same mbb as barrier mbb (where restore will
353   // be), make sure it's not below the intended restore index.
354   // FIXME: Undo the previous spill?
355   assert(LIs->getMBBFromIndex(II->second) == DefMBB);
356   if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
357     return false;
358
359   SS = I->second;
360   SpillIndex = II->second;
361   return true;
362 }
363
364 /// UpdateSpillSlotInterval - Given the specified val# of the register live
365 /// interval being split, and the spill and restore indicies, update the live
366 /// interval of the spill stack slot.
367 void
368 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
369                                            unsigned RestoreIndex) {
370   assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
371          "Expect restore in the barrier mbb");
372
373   MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
374   if (MBB == BarrierMBB) {
375     // Intra-block spill + restore. We are done.
376     LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
377     CurrSLI->addRange(SLR);
378     return;
379   }
380
381   SmallPtrSet<MachineBasicBlock*, 4> Processed;
382   unsigned EndIdx = LIs->getMBBEndIdx(MBB);
383   LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
384   CurrSLI->addRange(SLR);
385   Processed.insert(MBB);
386
387   // Start from the spill mbb, figure out the extend of the spill slot's
388   // live interval.
389   SmallVector<MachineBasicBlock*, 4> WorkList;
390   const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
391   if (LR->end > EndIdx)
392     // If live range extend beyond end of mbb, add successors to work list.
393     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
394            SE = MBB->succ_end(); SI != SE; ++SI)
395       WorkList.push_back(*SI);
396
397   while (!WorkList.empty()) {
398     MachineBasicBlock *MBB = WorkList.back();
399     WorkList.pop_back();
400     if (Processed.count(MBB))
401       continue;
402     unsigned Idx = LIs->getMBBStartIdx(MBB);
403     LR = CurrLI->getLiveRangeContaining(Idx);
404     if (LR && LR->valno == ValNo) {
405       EndIdx = LIs->getMBBEndIdx(MBB);
406       if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
407         // Spill slot live interval stops at the restore.
408         LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
409         CurrSLI->addRange(SLR);
410       } else if (LR->end > EndIdx) {
411         // Live range extends beyond end of mbb, process successors.
412         LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
413         CurrSLI->addRange(SLR);
414         for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
415                SE = MBB->succ_end(); SI != SE; ++SI)
416           WorkList.push_back(*SI);
417       } else {
418         LiveRange SLR(Idx, LR->end, CurrSValNo);
419         CurrSLI->addRange(SLR);
420       }
421       Processed.insert(MBB);
422     }
423   }
424 }
425
426 /// UpdateRegisterInterval - Given the specified val# of the current live
427 /// interval is being split, and the spill and restore indices, update the live
428 /// interval accordingly.
429 VNInfo*
430 PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
431                                           unsigned RestoreIndex) {
432   assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
433          "Expect restore in the barrier mbb");
434
435   SmallVector<std::pair<unsigned,unsigned>, 4> Before;
436   SmallVector<std::pair<unsigned,unsigned>, 4> After;
437   SmallVector<unsigned, 4> BeforeKills;
438   SmallVector<unsigned, 4> AfterKills;
439   SmallPtrSet<const LiveRange*, 4> Processed;
440
441   // First, let's figure out which parts of the live interval is now defined
442   // by the restore, which are defined by the original definition.
443   const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
444   After.push_back(std::make_pair(RestoreIndex, LR->end));
445   if (CurrLI->isKill(ValNo, LR->end))
446     AfterKills.push_back(LR->end);
447
448   assert(LR->contains(SpillIndex));
449   if (SpillIndex > LR->start) {
450     Before.push_back(std::make_pair(LR->start, SpillIndex));
451     BeforeKills.push_back(SpillIndex);
452   }
453   Processed.insert(LR);
454
455   // Start from the restore mbb, figure out what part of the live interval
456   // are defined by the restore.
457   SmallVector<MachineBasicBlock*, 4> WorkList;
458   MachineBasicBlock *MBB = BarrierMBB;
459   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
460          SE = MBB->succ_end(); SI != SE; ++SI)
461     WorkList.push_back(*SI);
462
463   SmallPtrSet<MachineBasicBlock*, 4> ProcessedBlocks;
464   ProcessedBlocks.insert(MBB);
465
466   while (!WorkList.empty()) {
467     MBB = WorkList.back();
468     WorkList.pop_back();
469     unsigned Idx = LIs->getMBBStartIdx(MBB);
470     LR = CurrLI->getLiveRangeContaining(Idx);
471     if (LR && LR->valno == ValNo && !Processed.count(LR)) {
472       After.push_back(std::make_pair(LR->start, LR->end));
473       if (CurrLI->isKill(ValNo, LR->end))
474         AfterKills.push_back(LR->end);
475       Idx = LIs->getMBBEndIdx(MBB);
476       if (LR->end > Idx) {
477         // Live range extend beyond at least one mbb. Let's see what other
478         // mbbs it reaches.
479         LIs->findReachableMBBs(LR->start, LR->end, WorkList);
480       }
481       Processed.insert(LR);
482     }
483     
484     ProcessedBlocks.insert(MBB);
485     if (LR)
486       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
487             SE = MBB->succ_end(); SI != SE; ++SI)
488         if (!ProcessedBlocks.count(*SI))
489           WorkList.push_back(*SI);
490   }
491
492   for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
493        I != E; ++I) {
494     LiveRange *LR = I;
495     if (LR->valno == ValNo && !Processed.count(LR)) {
496       Before.push_back(std::make_pair(LR->start, LR->end));
497       if (CurrLI->isKill(ValNo, LR->end))
498         BeforeKills.push_back(LR->end);
499     }
500   }
501
502   // Now create new val#s to represent the live ranges defined by the old def
503   // those defined by the restore.
504   unsigned AfterDef = ValNo->def;
505   MachineInstr *AfterCopy = ValNo->copy;
506   bool HasPHIKill = ValNo->hasPHIKill;
507   CurrLI->removeValNo(ValNo);
508   VNInfo *BValNo = (Before.empty())
509     ? NULL
510     : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
511   if (BValNo)
512     CurrLI->addKills(BValNo, BeforeKills);
513
514   VNInfo *AValNo = (After.empty())
515     ? NULL
516     : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
517   if (AValNo) {
518     AValNo->hasPHIKill = HasPHIKill;
519     CurrLI->addKills(AValNo, AfterKills);
520   }
521
522   for (unsigned i = 0, e = Before.size(); i != e; ++i) {
523     unsigned Start = Before[i].first;
524     unsigned End   = Before[i].second;
525     CurrLI->addRange(LiveRange(Start, End, BValNo));
526   }
527   for (unsigned i = 0, e = After.size(); i != e; ++i) {
528     unsigned Start = After[i].first;
529     unsigned End   = After[i].second;
530     CurrLI->addRange(LiveRange(Start, End, AValNo));
531   }
532   
533   return AValNo;
534 }
535
536 /// ShrinkWrapToLastUse - There are uses of the current live interval in the
537 /// given block, shrink wrap the live interval to the last use (i.e. remove
538 /// from last use to the end of the mbb). In case mbb is the where the barrier
539 /// is, remove from the last use to the barrier.
540 bool
541 PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
542                                        SmallVector<MachineOperand*, 4> &Uses,
543                                        SmallPtrSet<MachineInstr*, 4> &UseMIs) {
544   MachineOperand *LastMO = 0;
545   MachineInstr *LastMI = 0;
546   if (MBB != BarrierMBB && Uses.size() == 1) {
547     // Single use, no need to traverse the block. We can't assume this for the
548     // barrier bb though since the use is probably below the barrier.
549     LastMO = Uses[0];
550     LastMI = LastMO->getParent();
551   } else {
552     MachineBasicBlock::iterator MEE = MBB->begin();
553     MachineBasicBlock::iterator MII;
554     if (MBB == BarrierMBB)
555       MII = Barrier;
556     else
557       MII = MBB->end();
558     while (MII != MEE) {
559       --MII;
560       MachineInstr *UseMI = &*MII;
561       if (!UseMIs.count(UseMI))
562         continue;
563       for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
564         MachineOperand &MO = UseMI->getOperand(i);
565         if (MO.isReg() && MO.getReg() == CurrLI->reg) {
566           LastMO = &MO;
567           break;
568         }
569       }
570       LastMI = UseMI;
571       break;
572     }
573   }
574
575   // Cut off live range from last use (or beginning of the mbb if there
576   // are no uses in it) to the end of the mbb.
577   unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
578   if (LastMI) {
579     RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
580     assert(!LastMO->isKill() && "Last use already terminates the interval?");
581     LastMO->setIsKill();
582   } else {
583     assert(MBB == BarrierMBB);
584     RangeStart = LIs->getMBBStartIdx(MBB);
585   }
586   if (MBB == BarrierMBB)
587     RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
588   CurrLI->removeRange(RangeStart, RangeEnd);
589   if (LastMI)
590     CurrLI->addKill(ValNo, RangeStart);
591
592   // Return true if the last use becomes a new kill.
593   return LastMI;
594 }
595
596 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
597 /// construction algorithm to compute the ranges and valnos for an interval.
598 VNInfo* PreAllocSplitting::PerformPHIConstruction(
599                                                 MachineBasicBlock::iterator use,
600                                                          MachineBasicBlock* MBB,
601                                                                LiveInterval* LI,
602                                        SmallPtrSet<MachineInstr*, 4>& Visited,
603              DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
604              DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
605                                        DenseMap<MachineInstr*, VNInfo*>& NewVNs,
606                                  DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
607                                  DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
608                                               bool toplevel, bool intrablock) {
609   // Return memoized result if it's available.
610   if (toplevel && Visited.count(use) && NewVNs.count(use))
611     return NewVNs[use];
612   else if (!toplevel && intrablock && NewVNs.count(use))
613     return NewVNs[use];
614   else if (!intrablock && LiveOut.count(MBB))
615     return LiveOut[MBB];
616   
617   typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
618   
619   // Check if our block contains any uses or defs.
620   bool ContainsDefs = Defs.count(MBB);
621   bool ContainsUses = Uses.count(MBB);
622   
623   VNInfo* ret = 0;
624   
625   // Enumerate the cases of use/def contaning blocks.
626   if (!ContainsDefs && !ContainsUses) {
627   Fallback:
628     // NOTE: Because this is the fallback case from other cases, we do NOT
629     // assume that we are not intrablock here.
630     if (Phis.count(MBB)) return Phis[MBB];
631     
632     unsigned StartIndex = LIs->getMBBStartIdx(MBB);
633     
634     if (MBB->pred_size() == 1) {
635       Phis[MBB] = ret = PerformPHIConstruction((*MBB->pred_begin())->end(),
636                                           *(MBB->pred_begin()), LI, Visited,
637                                           Defs, Uses, NewVNs, LiveOut, Phis,
638                                           false, false);
639       unsigned EndIndex = 0;
640       if (intrablock) {
641         EndIndex = LIs->getInstructionIndex(use);
642         EndIndex = LiveIntervals::getUseIndex(EndIndex);
643       } else
644         EndIndex = LIs->getMBBEndIdx(MBB);
645       
646       LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
647       if (intrablock)
648         LI->addKill(ret, EndIndex);
649     } else {
650       Phis[MBB] = ret = LI->getNextValue(~0U, /*FIXME*/ 0,
651                                           LIs->getVNInfoAllocator());
652       if (!intrablock) LiveOut[MBB] = ret;
653     
654       // If there are no uses or defs between our starting point and the
655       // beginning of the block, then recursive perform phi construction
656       // on our predecessors.
657       DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
658       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
659            PE = MBB->pred_end(); PI != PE; ++PI) {
660         VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI, 
661                                             Visited, Defs, Uses, NewVNs,
662                                             LiveOut, Phis, false, false);
663         if (Incoming != 0)
664           IncomingVNs[*PI] = Incoming;
665       }
666     
667       // Otherwise, merge the incoming VNInfos with a phi join.  Create a new
668       // VNInfo to represent the joined value.
669       for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
670            IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
671         I->second->hasPHIKill = true;
672         unsigned KillIndex = LIs->getMBBEndIdx(I->first);
673         LI->addKill(I->second, KillIndex);
674       }
675       
676       unsigned EndIndex = 0;
677       if (intrablock) {
678         EndIndex = LIs->getInstructionIndex(use);
679         EndIndex = LiveIntervals::getUseIndex(EndIndex);
680       } else
681         EndIndex = LIs->getMBBEndIdx(MBB);
682       LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
683       if (intrablock)
684         LI->addKill(ret, EndIndex);
685     }
686   } else if (ContainsDefs && !ContainsUses) {
687     SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
688
689     // Search for the def in this block.  If we don't find it before the
690     // instruction we care about, go to the fallback case.  Note that that
691     // should never happen: this cannot be intrablock, so use should
692     // always be an end() iterator.
693     assert(use == MBB->end() && "No use marked in intrablock");
694     
695     MachineBasicBlock::iterator walker = use;
696     --walker;
697     while (walker != MBB->begin())
698       if (BlockDefs.count(walker)) {
699         break;
700       } else
701         --walker;
702     
703     // Once we've found it, extend its VNInfo to our instruction.
704     unsigned DefIndex = LIs->getInstructionIndex(walker);
705     DefIndex = LiveIntervals::getDefIndex(DefIndex);
706     unsigned EndIndex = LIs->getMBBEndIdx(MBB);
707     
708     ret = NewVNs[walker];
709     LI->addRange(LiveRange(DefIndex, EndIndex+1, ret));
710   } else if (!ContainsDefs && ContainsUses) {
711     SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
712     
713     // Search for the use in this block that precedes the instruction we care 
714     // about, going to the fallback case if we don't find it.
715     
716     if (use == MBB->begin())
717       goto Fallback;
718     
719     MachineBasicBlock::iterator walker = use;
720     --walker;
721     bool found = false;
722     while (walker != MBB->begin())
723       if (BlockUses.count(walker)) {
724         found = true;
725         break;
726       } else
727         --walker;
728         
729     // Must check begin() too.
730     if (!found) {
731       if (BlockUses.count(walker))
732         found = true;
733       else
734         goto Fallback;
735     }
736
737     unsigned UseIndex = LIs->getInstructionIndex(walker);
738     UseIndex = LiveIntervals::getUseIndex(UseIndex);
739     unsigned EndIndex = 0;
740     if (intrablock) {
741       EndIndex = LIs->getInstructionIndex(use);
742       EndIndex = LiveIntervals::getUseIndex(EndIndex);
743     } else
744       EndIndex = LIs->getMBBEndIdx(MBB);
745
746     // Now, recursively phi construct the VNInfo for the use we found,
747     // and then extend it to include the instruction we care about
748     ret = PerformPHIConstruction(walker, MBB, LI, Visited, Defs, Uses,
749                                  NewVNs, LiveOut, Phis, false, true);
750     
751     // FIXME: Need to set kills properly for inter-block stuff.
752     if (LI->isKill(ret, UseIndex)) LI->removeKill(ret, UseIndex);
753     if (intrablock)
754       LI->addKill(ret, EndIndex);
755     
756     LI->addRange(LiveRange(UseIndex, EndIndex+1, ret));
757   } else if (ContainsDefs && ContainsUses){
758     SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
759     SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
760     
761     // This case is basically a merging of the two preceding case, with the
762     // special note that checking for defs must take precedence over checking
763     // for uses, because of two-address instructions.
764     
765     if (use == MBB->begin())
766       goto Fallback;
767     
768     MachineBasicBlock::iterator walker = use;
769     --walker;
770     bool foundDef = false;
771     bool foundUse = false;
772     while (walker != MBB->begin())
773       if (BlockDefs.count(walker)) {
774         foundDef = true;
775         break;
776       } else if (BlockUses.count(walker)) {
777         foundUse = true;
778         break;
779       } else
780         --walker;
781         
782     // Must check begin() too.
783     if (!foundDef && !foundUse) {
784       if (BlockDefs.count(walker))
785         foundDef = true;
786       else if (BlockUses.count(walker))
787         foundUse = true;
788       else
789         goto Fallback;
790     }
791
792     unsigned StartIndex = LIs->getInstructionIndex(walker);
793     StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
794                             LiveIntervals::getUseIndex(StartIndex);
795     unsigned EndIndex = 0;
796     if (intrablock) {
797       EndIndex = LIs->getInstructionIndex(use);
798       EndIndex = LiveIntervals::getUseIndex(EndIndex);
799     } else
800       EndIndex = LIs->getMBBEndIdx(MBB);
801
802     if (foundDef)
803       ret = NewVNs[walker];
804     else
805       ret = PerformPHIConstruction(walker, MBB, LI, Visited, Defs, Uses,
806                                    NewVNs, LiveOut, Phis, false, true);
807
808     if (foundUse && LI->isKill(ret, StartIndex))
809       LI->removeKill(ret, StartIndex);
810     if (intrablock) {
811       LI->addKill(ret, EndIndex);
812     }
813
814     LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
815   }
816   
817   // Memoize results so we don't have to recompute them.
818   if (!intrablock) LiveOut[MBB] = ret;
819   else {
820     if (!NewVNs.count(use))
821       NewVNs[use] = ret;
822     Visited.insert(use);
823   }
824
825   return ret;
826 }
827
828 /// ReconstructLiveInterval - Recompute a live interval from scratch.
829 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
830   BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
831   
832   // Clear the old ranges and valnos;
833   LI->clear();
834   
835   // Cache the uses and defs of the register
836   typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
837   RegMap Defs, Uses;
838   
839   // Keep track of the new VNs we're creating.
840   DenseMap<MachineInstr*, VNInfo*> NewVNs;
841   SmallPtrSet<VNInfo*, 2> PhiVNs;
842   
843   // Cache defs, and create a new VNInfo for each def.
844   for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
845        DE = MRI->def_end(); DI != DE; ++DI) {
846     Defs[(*DI).getParent()].insert(&*DI);
847     
848     unsigned DefIdx = LIs->getInstructionIndex(&*DI);
849     DefIdx = LiveIntervals::getDefIndex(DefIdx);
850     
851     VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
852     
853     // If the def is a move, set the copy field.
854     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
855     if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
856       if (DstReg == LI->reg)
857         NewVN->copy = &*DI;
858     
859     NewVNs[&*DI] = NewVN;
860   }
861   
862   // Cache uses as a separate pass from actually processing them.
863   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
864        UE = MRI->use_end(); UI != UE; ++UI)
865     Uses[(*UI).getParent()].insert(&*UI);
866     
867   // Now, actually process every use and use a phi construction algorithm
868   // to walk from it to its reaching definitions, building VNInfos along
869   // the way.
870   DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
871   DenseMap<MachineBasicBlock*, VNInfo*> Phis;
872   SmallPtrSet<MachineInstr*, 4> Visited;
873   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
874        UE = MRI->use_end(); UI != UE; ++UI) {
875     PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
876                            Uses, NewVNs, LiveOut, Phis, true, true); 
877   }
878   
879   // Add ranges for dead defs
880   for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
881        DE = MRI->def_end(); DI != DE; ++DI) {
882     unsigned DefIdx = LIs->getInstructionIndex(&*DI);
883     DefIdx = LiveIntervals::getDefIndex(DefIdx);
884     
885     if (LI->liveAt(DefIdx)) continue;
886     
887     VNInfo* DeadVN = NewVNs[&*DI];
888     LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
889     LI->addKill(DeadVN, DefIdx);
890   }
891 }
892
893 /// ShrinkWrapLiveInterval - Recursively traverse the predecessor
894 /// chain to find the new 'kills' and shrink wrap the live interval to the
895 /// new kill indices.
896 void
897 PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
898                           MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
899                                     SmallPtrSet<MachineBasicBlock*, 8> &Visited,
900            DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
901            DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
902                                   SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
903   if (Visited.count(MBB))
904     return;
905
906   // If live interval is live in another successor path, then we can't process
907   // this block. But we may able to do so after all the successors have been
908   // processed.
909   if (MBB != BarrierMBB) {
910     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
911            SE = MBB->succ_end(); SI != SE; ++SI) {
912       MachineBasicBlock *SMBB = *SI;
913       if (SMBB == SuccMBB)
914         continue;
915       if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
916         return;
917     }
918   }
919
920   Visited.insert(MBB);
921
922   DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
923     UMII = Uses.find(MBB);
924   if (UMII != Uses.end()) {
925     // At least one use in this mbb, lets look for the kill.
926     DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
927       UMII2 = UseMIs.find(MBB);
928     if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
929       // Found a kill, shrink wrapping of this path ends here.
930       return;
931   } else if (MBB == DefMBB) {
932     // There are no uses after the def.
933     MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
934     if (UseMBBs.empty()) {
935       // The only use must be below barrier in the barrier block. It's safe to
936       // remove the def.
937       LIs->RemoveMachineInstrFromMaps(DefMI);
938       DefMI->eraseFromParent();
939       CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
940     }
941   } else if (MBB == BarrierMBB) {
942     // Remove entire live range from start of mbb to barrier.
943     CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
944                         LIs->getUseIndex(BarrierIdx)+1);
945   } else {
946     // Remove entire live range of the mbb out of the live interval.
947     CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
948   }
949
950   if (MBB == DefMBB)
951     // Reached the def mbb, stop traversing this path further.
952     return;
953
954   // Traverse the pathes up the predecessor chains further.
955   for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
956          PE = MBB->pred_end(); PI != PE; ++PI) {
957     MachineBasicBlock *Pred = *PI;
958     if (Pred == MBB)
959       continue;
960     if (Pred == DefMBB && ValNo->hasPHIKill)
961       // Pred is the def bb and the def reaches other val#s, we must
962       // allow the value to be live out of the bb.
963       continue;
964     if (!CurrLI->liveAt(LIs->getMBBEndIdx(Pred)-1))
965       return;
966     ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
967                            Uses, UseMIs, UseMBBs);
968   }
969
970   return;
971 }
972
973
974 void PreAllocSplitting::RepairLiveInterval(LiveInterval* CurrLI,
975                                            VNInfo* ValNo,
976                                            MachineInstr* DefMI,
977                                            unsigned RestoreIdx) {
978   // Shrink wrap the live interval by walking up the CFG and find the
979   // new kills.
980   // Now let's find all the uses of the val#.
981   DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
982   DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
983   SmallPtrSet<MachineBasicBlock*, 4> Seen;
984   SmallVector<MachineBasicBlock*, 4> UseMBBs;
985   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
986          UE = MRI->use_end(); UI != UE; ++UI) {
987     MachineOperand &UseMO = UI.getOperand();
988     MachineInstr *UseMI = UseMO.getParent();
989     unsigned UseIdx = LIs->getInstructionIndex(UseMI);
990     LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
991     if (ULR->valno != ValNo)
992       continue;
993     MachineBasicBlock *UseMBB = UseMI->getParent();
994     // Remember which other mbb's use this val#.
995     if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
996       UseMBBs.push_back(UseMBB);
997     DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
998       UMII = Uses.find(UseMBB);
999     if (UMII != Uses.end()) {
1000       DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
1001         UMII2 = UseMIs.find(UseMBB);
1002       UMII->second.push_back(&UseMO);
1003       UMII2->second.insert(UseMI);
1004     } else {
1005       SmallVector<MachineOperand*, 4> Ops;
1006       Ops.push_back(&UseMO);
1007       Uses.insert(std::make_pair(UseMBB, Ops));
1008       SmallPtrSet<MachineInstr*, 4> MIs;
1009       MIs.insert(UseMI);
1010       UseMIs.insert(std::make_pair(UseMBB, MIs));
1011     }
1012   }
1013
1014   // Walk up the predecessor chains.
1015   SmallPtrSet<MachineBasicBlock*, 8> Visited;
1016   ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMI->getParent(), Visited,
1017                          Uses, UseMIs, UseMBBs);
1018
1019   // Remove live range from barrier to the restore. FIXME: Find a better
1020   // point to re-start the live interval.
1021   VNInfo* AfterValNo = UpdateRegisterInterval(ValNo,
1022                                               LIs->getUseIndex(BarrierIdx)+1,
1023                                               LIs->getDefIndex(RestoreIdx));
1024   
1025   // Attempt to renumber the new valno into a new vreg.
1026   RenumberValno(AfterValNo);
1027 }
1028
1029 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
1030 /// be allocated to a different register.  This function creates a new vreg,
1031 /// copies the valno and its live ranges over to the new vreg's interval,
1032 /// removes them from the old interval, and rewrites all uses and defs of
1033 /// the original reg to the new vreg within those ranges.
1034 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
1035   SmallVector<VNInfo*, 4> Stack;
1036   SmallVector<VNInfo*, 4> VNsToCopy;
1037   Stack.push_back(VN);
1038
1039   // Walk through and copy the valno we care about, and any other valnos
1040   // that are two-address redefinitions of the one we care about.  These
1041   // will need to be rewritten as well.  We also check for safety of the 
1042   // renumbering here, by making sure that none of the valno involved has
1043   // phi kills.
1044   while (!Stack.empty()) {
1045     VNInfo* OldVN = Stack.back();
1046     Stack.pop_back();
1047     
1048     // Bail out if we ever encounter a valno that has a PHI kill.  We can't
1049     // renumber these.
1050     if (OldVN->hasPHIKill) return;
1051     
1052     VNsToCopy.push_back(OldVN);
1053     
1054     // Locate two-address redefinitions
1055     for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
1056          KE = OldVN->kills.end(); KI != KE; ++KI) {
1057       MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
1058       //if (!MI) continue;
1059       unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
1060       if (DefIdx == ~0U) continue;
1061       if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
1062         VNInfo* NextVN =
1063                      CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
1064         Stack.push_back(NextVN);
1065       }
1066     }
1067   }
1068   
1069   // Create the new vreg
1070   unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
1071   
1072   // Create the new live interval
1073   LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
1074   
1075   for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE = 
1076        VNsToCopy.end(); OI != OE; ++OI) {
1077     VNInfo* OldVN = *OI;
1078     
1079     // Copy the valno over
1080     VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy, 
1081                                        LIs->getVNInfoAllocator());
1082     NewLI.copyValNumInfo(NewVN, OldVN);
1083     NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
1084
1085     // Remove the valno from the old interval
1086     CurrLI->removeValNo(OldVN);
1087   }
1088   
1089   // Rewrite defs and uses.  This is done in two stages to avoid invalidating
1090   // the reg_iterator.
1091   SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
1092   
1093   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1094          E = MRI->reg_end(); I != E; ++I) {
1095     MachineOperand& MO = I.getOperand();
1096     unsigned InstrIdx = LIs->getInstructionIndex(&*I);
1097     
1098     if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
1099         (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
1100       OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
1101   }
1102   
1103   for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
1104        OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
1105     MachineInstr* Inst = I->first;
1106     unsigned OpIdx = I->second;
1107     MachineOperand& MO = Inst->getOperand(OpIdx);
1108     MO.setReg(NewVReg);
1109   }
1110   
1111   NumRenumbers++;
1112 }
1113
1114 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
1115                                       MachineInstr* DefMI,
1116                                       MachineBasicBlock::iterator RestorePt,
1117                                       unsigned RestoreIdx,
1118                                     SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
1119   MachineBasicBlock& MBB = *RestorePt->getParent();
1120   
1121   MachineBasicBlock::iterator KillPt = BarrierMBB->end();
1122   unsigned KillIdx = 0;
1123   if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
1124     KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
1125   else
1126     KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
1127   
1128   if (KillPt == DefMI->getParent()->end())
1129     return false;
1130   
1131   TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
1132   LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
1133   
1134   if (KillPt->getParent() == BarrierMBB) {
1135     VNInfo* After = UpdateRegisterInterval(ValNo, LIs->getUseIndex(KillIdx)+1,
1136                            LIs->getDefIndex(RestoreIdx));
1137     
1138     RenumberValno(After);
1139
1140     ++NumSplits;
1141     ++NumRemats;
1142     return true;
1143   }
1144
1145   RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIdx);
1146   
1147   ++NumSplits;
1148   ++NumRemats;
1149   return true;  
1150 }
1151
1152 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg, 
1153                                            const TargetRegisterClass* RC,
1154                                            MachineInstr* DefMI,
1155                                            MachineInstr* Barrier,
1156                                            MachineBasicBlock* MBB,
1157                                            int& SS,
1158                                     SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
1159   MachineBasicBlock::iterator Pt = MBB->begin();
1160
1161   // Go top down if RefsInMBB is empty.
1162   if (RefsInMBB.empty())
1163     return 0;
1164   
1165   MachineBasicBlock::iterator FoldPt = Barrier;
1166   while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
1167          !RefsInMBB.count(FoldPt))
1168     --FoldPt;
1169   
1170   int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
1171   if (OpIdx == -1)
1172     return 0;
1173   
1174   SmallVector<unsigned, 1> Ops;
1175   Ops.push_back(OpIdx);
1176   
1177   if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1178     return 0;
1179   
1180   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
1181   if (I != IntervalSSMap.end()) {
1182     SS = I->second;
1183   } else {
1184     SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
1185     
1186   }
1187   
1188   MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1189                                              FoldPt, Ops, SS);
1190   
1191   if (FMI) {
1192     LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1193     FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1194     ++NumFolds;
1195     
1196     IntervalSSMap[vreg] = SS;
1197     CurrSLI = &LSs->getOrCreateInterval(SS);
1198     if (CurrSLI->hasAtLeastOneValue())
1199       CurrSValNo = CurrSLI->getValNumInfo(0);
1200     else
1201       CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
1202   }
1203   
1204   return FMI;
1205 }
1206
1207 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1208 /// so it would not cross the barrier that's being processed. Shrink wrap
1209 /// (minimize) the live interval to the last uses.
1210 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1211   CurrLI = LI;
1212
1213   // Find live range where current interval cross the barrier.
1214   LiveInterval::iterator LR =
1215     CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
1216   VNInfo *ValNo = LR->valno;
1217
1218   if (ValNo->def == ~1U) {
1219     // Defined by a dead def? How can this be?
1220     assert(0 && "Val# is defined by a dead def?");
1221     abort();
1222   }
1223
1224   MachineInstr *DefMI = (ValNo->def != ~0U)
1225     ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
1226
1227   // If this would create a new join point, do not split.
1228   if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
1229     return false;
1230
1231   // Find all references in the barrier mbb.
1232   SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1233   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1234          E = MRI->reg_end(); I != E; ++I) {
1235     MachineInstr *RefMI = &*I;
1236     if (RefMI->getParent() == BarrierMBB)
1237       RefsInMBB.insert(RefMI);
1238   }
1239
1240   // Find a point to restore the value after the barrier.
1241   unsigned RestoreIndex = 0;
1242   MachineBasicBlock::iterator RestorePt =
1243     findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
1244   if (RestorePt == BarrierMBB->end())
1245     return false;
1246
1247   if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1248     if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1249                       RestoreIndex, RefsInMBB))
1250     return true;
1251
1252   // Add a spill either before the barrier or after the definition.
1253   MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1254   const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1255   unsigned SpillIndex = 0;
1256   MachineInstr *SpillMI = NULL;
1257   int SS = -1;
1258   if (ValNo->def == ~0U) {
1259     // If it's defined by a phi, we must split just before the barrier.
1260     if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1261                             BarrierMBB, SS, RefsInMBB))) {
1262       SpillIndex = LIs->getInstructionIndex(SpillMI);
1263     } else {
1264       MachineBasicBlock::iterator SpillPt = 
1265         findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1266       if (SpillPt == BarrierMBB->begin())
1267         return false; // No gap to insert spill.
1268       // Add spill.
1269     
1270       SS = CreateSpillStackSlot(CurrLI->reg, RC);
1271       TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1272       SpillMI = prior(SpillPt);
1273       LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1274     }
1275   } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1276                                  RestoreIndex, SpillIndex, SS)) {
1277     // If it's already split, just restore the value. There is no need to spill
1278     // the def again.
1279     if (!DefMI)
1280       return false; // Def is dead. Do nothing.
1281     
1282     if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1283                             BarrierMBB, SS, RefsInMBB))) {
1284       SpillIndex = LIs->getInstructionIndex(SpillMI);
1285     } else {
1286       // Check if it's possible to insert a spill after the def MI.
1287       MachineBasicBlock::iterator SpillPt;
1288       if (DefMBB == BarrierMBB) {
1289         // Add spill after the def and the last use before the barrier.
1290         SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1291                                  RefsInMBB, SpillIndex);
1292         if (SpillPt == DefMBB->begin())
1293           return false; // No gap to insert spill.
1294       } else {
1295         SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1296         if (SpillPt == DefMBB->end())
1297           return false; // No gap to insert spill.
1298       }
1299       // Add spill. The store instruction kills the register if def is before
1300       // the barrier in the barrier block.
1301       SS = CreateSpillStackSlot(CurrLI->reg, RC);
1302       TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
1303                                DefMBB == BarrierMBB, SS, RC);
1304       SpillMI = prior(SpillPt);
1305       LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1306     }
1307   }
1308
1309   // Remember def instruction index to spill index mapping.
1310   if (DefMI && SpillMI)
1311     Def2SpillMap[ValNo->def] = SpillIndex;
1312
1313   // Add restore.
1314   TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1315   MachineInstr *LoadMI = prior(RestorePt);
1316   LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1317
1318   // If live interval is spilled in the same block as the barrier, just
1319   // create a hole in the interval.
1320   if (!DefMBB ||
1321       (SpillMI && SpillMI->getParent() == BarrierMBB)) {
1322     // Update spill stack slot live interval.
1323     UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1324                             LIs->getDefIndex(RestoreIndex));
1325
1326     VNInfo* After = UpdateRegisterInterval(ValNo,
1327                            LIs->getUseIndex(SpillIndex)+1,
1328                            LIs->getDefIndex(RestoreIndex));
1329     RenumberValno(After);
1330    
1331     ++NumSplits;
1332     return true;
1333   }
1334
1335   // Update spill stack slot live interval.
1336   UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1337                           LIs->getDefIndex(RestoreIndex));
1338
1339   RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIndex);
1340   
1341   ++NumSplits;
1342   return true;
1343 }
1344
1345 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1346 /// barrier that's being processed.
1347 bool
1348 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1349                                          SmallPtrSet<LiveInterval*, 8>& Split) {
1350   // First find all the virtual registers whose live intervals are intercepted
1351   // by the current barrier.
1352   SmallVector<LiveInterval*, 8> Intervals;
1353   for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1354     if (TII->IgnoreRegisterClassBarriers(*RC))
1355       continue;
1356     std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1357     for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1358       unsigned Reg = VRs[i];
1359       if (!LIs->hasInterval(Reg))
1360         continue;
1361       LiveInterval *LI = &LIs->getInterval(Reg);
1362       if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1363         // Virtual register live interval is intercepted by the barrier. We
1364         // should split and shrink wrap its interval if possible.
1365         Intervals.push_back(LI);
1366     }
1367   }
1368
1369   // Process the affected live intervals.
1370   bool Change = false;
1371   while (!Intervals.empty()) {
1372     if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1373       break;
1374     else if (NumSplits == 4)
1375       Change |= Change;
1376     LiveInterval *LI = Intervals.back();
1377     Intervals.pop_back();
1378     bool result = SplitRegLiveInterval(LI);
1379     if (result) Split.insert(LI);
1380     Change |= result;
1381   }
1382
1383   return Change;
1384 }
1385
1386 unsigned PreAllocSplitting::getNumberOfSpills(
1387                                   SmallPtrSet<MachineInstr*, 4>& MIs,
1388                                   unsigned Reg, int FrameIndex) {
1389   unsigned Spills = 0;
1390   for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1391        UI != UI; ++UI) {
1392     int StoreFrameIndex;
1393     unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1394     if (StoreVReg == Reg && StoreFrameIndex == FrameIndex)
1395       Spills++;
1396   }
1397   
1398   return Spills;
1399 }
1400
1401 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1402 /// split, and see if any of the spills are unnecessary.  If so, remove them.
1403 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1404   bool changed = false;
1405   
1406   for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1407        LE = split.end(); LI != LE; ++LI) {
1408     DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1409     
1410     for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1411          UE = MRI->use_end(); UI != UE; ++UI) {
1412       unsigned index = LIs->getInstructionIndex(&*UI);
1413       index = LiveIntervals::getUseIndex(index);
1414       
1415       const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1416       VNUseCount[LR->valno].insert(&*UI);
1417     }
1418     
1419     for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1420          VE = (*LI)->vni_end(); VI != VE; ++VI) {
1421       VNInfo* CurrVN = *VI;
1422       if (CurrVN->hasPHIKill) continue;
1423       
1424       unsigned DefIdx = CurrVN->def;
1425       if (DefIdx == ~0U || DefIdx == ~1U) continue;
1426     
1427       MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
1428       int FrameIndex;
1429       if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1430       
1431       if (VNUseCount[CurrVN].size() == 0) {
1432         LIs->RemoveMachineInstrFromMaps(DefMI);
1433         (*LI)->removeValNo(CurrVN);
1434         DefMI->eraseFromParent();
1435         NumDeadSpills++;
1436         changed = true;
1437         continue;
1438       }
1439       
1440       unsigned SpillCount = getNumberOfSpills(VNUseCount[CurrVN],
1441                                               (*LI)->reg, FrameIndex);
1442       if (SpillCount != VNUseCount[CurrVN].size()) continue;
1443         
1444       for (SmallPtrSet<MachineInstr*, 4>::iterator UI = 
1445            VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1446            UI != UI; ++UI) {
1447         LIs->RemoveMachineInstrFromMaps(*UI);
1448         (*UI)->eraseFromParent();
1449       }
1450         
1451       LIs->RemoveMachineInstrFromMaps(DefMI);
1452       (*LI)->removeValNo(CurrVN);
1453       DefMI->eraseFromParent();
1454       NumDeadSpills++;
1455       changed = true;
1456     }
1457   }
1458   
1459   return changed;
1460 }
1461
1462 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1463                                        MachineBasicBlock* DefMBB,
1464                                        MachineBasicBlock* BarrierMBB) {
1465   if (DefMBB == BarrierMBB)
1466     return false;
1467   
1468   if (LR->valno->hasPHIKill)
1469     return false;
1470   
1471   unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1472   if (LR->end < MBBEnd)
1473     return false;
1474   
1475   MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1476   if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1477     return true;
1478   
1479   MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1480   SmallPtrSet<MachineBasicBlock*, 4> Visited;
1481   typedef std::pair<MachineBasicBlock*,
1482                     MachineBasicBlock::succ_iterator> ItPair;
1483   SmallVector<ItPair, 4> Stack;
1484   Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1485   
1486   while (!Stack.empty()) {
1487     ItPair P = Stack.back();
1488     Stack.pop_back();
1489     
1490     MachineBasicBlock* PredMBB = P.first;
1491     MachineBasicBlock::succ_iterator S = P.second;
1492     
1493     if (S == PredMBB->succ_end())
1494       continue;
1495     else if (Visited.count(*S)) {
1496       Stack.push_back(std::make_pair(PredMBB, ++S));
1497       continue;
1498     } else
1499       Stack.push_back(std::make_pair(PredMBB, S+1));
1500     
1501     MachineBasicBlock* MBB = *S;
1502     Visited.insert(MBB);
1503     
1504     if (MBB == BarrierMBB)
1505       return true;
1506     
1507     MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1508     MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1509     MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1510     while (MDTN) {
1511       if (MDTN == DefMDTN)
1512         return true;
1513       else if (MDTN == BarrierMDTN)
1514         break;
1515       MDTN = MDTN->getIDom();
1516     }
1517     
1518     MBBEnd = LIs->getMBBEndIdx(MBB);
1519     if (LR->end > MBBEnd)
1520       Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1521   }
1522   
1523   return false;
1524
1525   
1526
1527 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1528   CurrMF = &MF;
1529   TM     = &MF.getTarget();
1530   TII    = TM->getInstrInfo();
1531   MFI    = MF.getFrameInfo();
1532   MRI    = &MF.getRegInfo();
1533   LIs    = &getAnalysis<LiveIntervals>();
1534   LSs    = &getAnalysis<LiveStacks>();
1535
1536   bool MadeChange = false;
1537
1538   // Make sure blocks are numbered in order.
1539   MF.RenumberBlocks();
1540
1541   MachineBasicBlock *Entry = MF.begin();
1542   SmallPtrSet<MachineBasicBlock*,16> Visited;
1543
1544   SmallPtrSet<LiveInterval*, 8> Split;
1545
1546   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1547          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1548        DFI != E; ++DFI) {
1549     BarrierMBB = *DFI;
1550     for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1551            E = BarrierMBB->end(); I != E; ++I) {
1552       Barrier = &*I;
1553       const TargetRegisterClass **BarrierRCs =
1554         Barrier->getDesc().getRegClassBarriers();
1555       if (!BarrierRCs)
1556         continue;
1557       BarrierIdx = LIs->getInstructionIndex(Barrier);
1558       MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1559     }
1560   }
1561
1562   MadeChange |= removeDeadSpills(Split);
1563
1564   return MadeChange;
1565 }