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