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