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