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