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