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