Enable stack coloring with regs at -O3.
[oota-llvm.git] / lib / CodeGen / StackSlotColoring.cpp
1 //===-- StackSlotColoring.cpp - Stack slot coloring 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 stack slot coloring pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "stackcoloring"
15 #include "VirtRegMap.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/LiveStackAnalysis.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineLoopInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/PseudoSourceValue.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include <vector>
32 using namespace llvm;
33
34 static cl::opt<bool>
35 DisableSharing("no-stack-slot-sharing",
36              cl::init(false), cl::Hidden,
37              cl::desc("Suppress slot sharing during stack coloring"));
38
39 static cl::opt<bool>
40 ColorWithRegsOpt("color-ss-with-regs",
41                  cl::init(false), cl::Hidden,
42                  cl::desc("Color stack slots with free registers"));
43
44
45 static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
46
47 STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
48 STATISTIC(NumRegRepl,    "Number of stack slot refs replaced with reg refs");
49 STATISTIC(NumLoadElim,   "Number of loads eliminated");
50 STATISTIC(NumStoreElim,  "Number of stores eliminated");
51 STATISTIC(NumDead,       "Number of trivially dead stack accesses eliminated");
52
53 namespace {
54   class VISIBILITY_HIDDEN StackSlotColoring : public MachineFunctionPass {
55     bool ColorWithRegs;
56     LiveStacks* LS;
57     VirtRegMap* VRM;
58     MachineFrameInfo *MFI;
59     MachineRegisterInfo *MRI;
60     const TargetInstrInfo  *TII;
61     const TargetRegisterInfo *TRI;
62     const MachineLoopInfo *loopInfo;
63
64     // SSIntervals - Spill slot intervals.
65     std::vector<LiveInterval*> SSIntervals;
66
67     // SSRefs - Keep a list of frame index references for each spill slot.
68     SmallVector<SmallVector<MachineInstr*, 8>, 16> SSRefs;
69
70     // OrigAlignments - Alignments of stack objects before coloring.
71     SmallVector<unsigned, 16> OrigAlignments;
72
73     // OrigSizes - Sizess of stack objects before coloring.
74     SmallVector<unsigned, 16> OrigSizes;
75
76     // AllColors - If index is set, it's a spill slot, i.e. color.
77     // FIXME: This assumes PEI locate spill slot with smaller indices
78     // closest to stack pointer / frame pointer. Therefore, smaller
79     // index == better color.
80     BitVector AllColors;
81
82     // NextColor - Next "color" that's not yet used.
83     int NextColor;
84
85     // UsedColors - "Colors" that have been assigned.
86     BitVector UsedColors;
87
88     // Assignments - Color to intervals mapping.
89     SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
90
91   public:
92     static char ID; // Pass identification
93     StackSlotColoring() :
94       MachineFunctionPass(&ID), ColorWithRegs(false), NextColor(-1) {}
95     StackSlotColoring(bool RegColor) :
96       MachineFunctionPass(&ID), ColorWithRegs(RegColor), NextColor(-1) {}
97     
98     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
99       AU.addRequired<LiveStacks>();
100       AU.addRequired<VirtRegMap>();
101       AU.addPreserved<VirtRegMap>();      
102       AU.addRequired<MachineLoopInfo>();
103       AU.addPreserved<MachineLoopInfo>();
104       AU.addPreservedID(MachineDominatorsID);
105       MachineFunctionPass::getAnalysisUsage(AU);
106     }
107
108     virtual bool runOnMachineFunction(MachineFunction &MF);
109     virtual const char* getPassName() const {
110       return "Stack Slot Coloring";
111     }
112
113   private:
114     void InitializeSlots();
115     void ScanForSpillSlotRefs(MachineFunction &MF);
116     bool OverlapWithAssignments(LiveInterval *li, int Color) const;
117     int ColorSlot(LiveInterval *li);
118     bool ColorSlots(MachineFunction &MF);
119     bool ColorSlotsWithFreeRegs(SmallVector<int, 16> &SlotMapping,
120                                 SmallVector<SmallVector<int, 4>, 16> &RevMap,
121                                 BitVector &SlotIsReg);
122     void RewriteInstruction(MachineInstr *MI, int OldFI, int NewFI,
123                             MachineFunction &MF);
124     bool PropagateBackward(MachineBasicBlock::iterator MII,
125                            MachineBasicBlock *MBB,
126                            unsigned OldReg, unsigned NewReg);
127     bool PropagateForward(MachineBasicBlock::iterator MII,
128                           MachineBasicBlock *MBB,
129                           unsigned OldReg, unsigned NewReg);
130     void UnfoldAndRewriteInstruction(MachineInstr *MI, int OldFI,
131                                     unsigned Reg, const TargetRegisterClass *RC,
132                                     MachineFunction &MF);
133     bool AllMemRefsCanBeUnfolded(int SS);
134     bool RemoveDeadStores(MachineBasicBlock* MBB);
135   };
136 } // end anonymous namespace
137
138 char StackSlotColoring::ID = 0;
139
140 static RegisterPass<StackSlotColoring>
141 X("stack-slot-coloring", "Stack Slot Coloring");
142
143 FunctionPass *llvm::createStackSlotColoringPass(bool RegColor) {
144   return new StackSlotColoring(RegColor);
145 }
146
147 namespace {
148   // IntervalSorter - Comparison predicate that sort live intervals by
149   // their weight.
150   struct IntervalSorter {
151     bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
152       return LHS->weight > RHS->weight;
153     }
154   };
155 }
156
157 /// ScanForSpillSlotRefs - Scan all the machine instructions for spill slot
158 /// references and update spill slot weights.
159 void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) {
160   SSRefs.resize(MFI->getObjectIndexEnd());
161
162   // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
163   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
164        MBBI != E; ++MBBI) {
165     MachineBasicBlock *MBB = &*MBBI;
166     unsigned loopDepth = loopInfo->getLoopDepth(MBB);
167     for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
168          MII != EE; ++MII) {
169       MachineInstr *MI = &*MII;
170       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
171         MachineOperand &MO = MI->getOperand(i);
172         if (!MO.isFI())
173           continue;
174         int FI = MO.getIndex();
175         if (FI < 0)
176           continue;
177         if (!LS->hasInterval(FI))
178           continue;
179         LiveInterval &li = LS->getInterval(FI);
180         li.weight += LiveIntervals::getSpillWeight(false, true, loopDepth);
181         SSRefs[FI].push_back(MI);
182       }
183     }
184   }
185 }
186
187 /// InitializeSlots - Process all spill stack slot liveintervals and add them
188 /// to a sorted (by weight) list.
189 void StackSlotColoring::InitializeSlots() {
190   int LastFI = MFI->getObjectIndexEnd();
191   OrigAlignments.resize(LastFI);
192   OrigSizes.resize(LastFI);
193   AllColors.resize(LastFI);
194   UsedColors.resize(LastFI);
195   Assignments.resize(LastFI);
196
197   // Gather all spill slots into a list.
198   DOUT << "Spill slot intervals:\n";
199   for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
200     LiveInterval &li = i->second;
201     DEBUG(li.dump());
202     int FI = li.getStackSlotIndex();
203     if (MFI->isDeadObjectIndex(FI))
204       continue;
205     SSIntervals.push_back(&li);
206     OrigAlignments[FI] = MFI->getObjectAlignment(FI);
207     OrigSizes[FI]      = MFI->getObjectSize(FI);
208     AllColors.set(FI);
209   }
210   DOUT << '\n';
211
212   // Sort them by weight.
213   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
214
215   // Get first "color".
216   NextColor = AllColors.find_first();
217 }
218
219 /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
220 /// LiveIntervals that have already been assigned to the specified color.
221 bool
222 StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
223   const SmallVector<LiveInterval*,4> &OtherLIs = Assignments[Color];
224   for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
225     LiveInterval *OtherLI = OtherLIs[i];
226     if (OtherLI->overlaps(*li))
227       return true;
228   }
229   return false;
230 }
231
232 /// ColorSlotsWithFreeRegs - If there are any free registers available, try
233 /// replacing spill slots references with registers instead.
234 bool
235 StackSlotColoring::ColorSlotsWithFreeRegs(SmallVector<int, 16> &SlotMapping,
236                                    SmallVector<SmallVector<int, 4>, 16> &RevMap,
237                                    BitVector &SlotIsReg) {
238   if (!(ColorWithRegs || ColorWithRegsOpt) || !VRM->HasUnusedRegisters())
239     return false;
240
241   bool Changed = false;
242   DOUT << "Assigning unused registers to spill slots:\n";
243   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
244     LiveInterval *li = SSIntervals[i];
245     int SS = li->getStackSlotIndex();
246     if (!UsedColors[SS] || li->weight < 20)
247       // If the weight is < 20, i.e. two references in a loop with depth 1,
248       // don't bother with it.
249       continue;
250
251     // These slots allow to share the same registers.
252     bool AllColored = true;
253     SmallVector<unsigned, 4> ColoredRegs;
254     for (unsigned j = 0, ee = RevMap[SS].size(); j != ee; ++j) {
255       int RSS = RevMap[SS][j];
256       const TargetRegisterClass *RC = LS->getIntervalRegClass(RSS);
257       // If it's not colored to another stack slot, try coloring it
258       // to a "free" register.
259       if (!RC) {
260         AllColored = false;
261         continue;
262       }
263       unsigned Reg = VRM->getFirstUnusedRegister(RC);
264       if (!Reg) {
265         AllColored = false;
266         continue;
267       }
268       if (!AllMemRefsCanBeUnfolded(RSS)) {
269         AllColored = false;
270         continue;
271       } else {
272         DOUT << "Assigning fi#" << RSS << " to " << TRI->getName(Reg) << '\n';
273         ColoredRegs.push_back(Reg);
274         SlotMapping[RSS] = Reg;
275         SlotIsReg.set(RSS);
276         Changed = true;
277       }
278     }
279
280     // Register and its sub-registers are no longer free.
281     while (!ColoredRegs.empty()) {
282       unsigned Reg = ColoredRegs.back();
283       ColoredRegs.pop_back();
284       VRM->setRegisterUsed(Reg);
285       // If reg is a callee-saved register, it will have to be spilled in
286       // the prologue.
287       MRI->setPhysRegUsed(Reg);
288       for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
289         VRM->setRegisterUsed(*AS);
290         MRI->setPhysRegUsed(*AS);
291       }
292     }
293     // This spill slot is dead after the rewrites
294     if (AllColored) {
295       MFI->RemoveStackObject(SS);
296       ++NumEliminated;
297     }
298   }
299   DOUT << '\n';
300
301   return Changed;
302 }
303
304 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
305 ///
306 int StackSlotColoring::ColorSlot(LiveInterval *li) {
307   int Color = -1;
308   bool Share = false;
309   if (!DisableSharing) {
310     // Check if it's possible to reuse any of the used colors.
311     Color = UsedColors.find_first();
312     while (Color != -1) {
313       if (!OverlapWithAssignments(li, Color)) {
314         Share = true;
315         ++NumEliminated;
316         break;
317       }
318       Color = UsedColors.find_next(Color);
319     }
320   }
321
322   // Assign it to the first available color (assumed to be the best) if it's
323   // not possible to share a used color with other objects.
324   if (!Share) {
325     assert(NextColor != -1 && "No more spill slots?");
326     Color = NextColor;
327     UsedColors.set(Color);
328     NextColor = AllColors.find_next(NextColor);
329   }
330
331   // Record the assignment.
332   Assignments[Color].push_back(li);
333   int FI = li->getStackSlotIndex();
334   DOUT << "Assigning fi#" << FI << " to fi#" << Color << "\n";
335
336   // Change size and alignment of the allocated slot. If there are multiple
337   // objects sharing the same slot, then make sure the size and alignment
338   // are large enough for all.
339   unsigned Align = OrigAlignments[FI];
340   if (!Share || Align > MFI->getObjectAlignment(Color))
341     MFI->setObjectAlignment(Color, Align);
342   int64_t Size = OrigSizes[FI];
343   if (!Share || Size > MFI->getObjectSize(Color))
344     MFI->setObjectSize(Color, Size);
345   return Color;
346 }
347
348 /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
349 /// operands in the function.
350 bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
351   unsigned NumObjs = MFI->getObjectIndexEnd();
352   SmallVector<int, 16> SlotMapping(NumObjs, -1);
353   SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
354   SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
355   BitVector SlotIsReg(NumObjs);
356   BitVector UsedColors(NumObjs);
357
358   DOUT << "Color spill slot intervals:\n";
359   bool Changed = false;
360   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
361     LiveInterval *li = SSIntervals[i];
362     int SS = li->getStackSlotIndex();
363     int NewSS = ColorSlot(li);
364     assert(NewSS >= 0 && "Stack coloring failed?");
365     SlotMapping[SS] = NewSS;
366     RevMap[NewSS].push_back(SS);
367     SlotWeights[NewSS] += li->weight;
368     UsedColors.set(NewSS);
369     Changed |= (SS != NewSS);
370   }
371
372   DOUT << "\nSpill slots after coloring:\n";
373   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
374     LiveInterval *li = SSIntervals[i];
375     int SS = li->getStackSlotIndex();
376     li->weight = SlotWeights[SS];
377   }
378   // Sort them by new weight.
379   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
380
381 #ifndef NDEBUG
382   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
383     DEBUG(SSIntervals[i]->dump());
384   DOUT << '\n';
385 #endif
386
387   // Can we "color" a stack slot with a unused register?
388   Changed |= ColorSlotsWithFreeRegs(SlotMapping, RevMap, SlotIsReg);
389
390   if (!Changed)
391     return false;
392
393   // Rewrite all MO_FrameIndex operands.
394   for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
395     bool isReg = SlotIsReg[SS];
396     int NewFI = SlotMapping[SS];
397     if (NewFI == -1 || (NewFI == (int)SS && !isReg))
398       continue;
399
400     SmallVector<MachineInstr*, 8> &RefMIs = SSRefs[SS];
401     for (unsigned i = 0, e = RefMIs.size(); i != e; ++i)
402       if (!isReg)
403         RewriteInstruction(RefMIs[i], SS, NewFI, MF);
404       else {
405         // Rewrite to use a register instead.
406         const TargetRegisterClass *RC = LS->getIntervalRegClass(SS);
407         UnfoldAndRewriteInstruction(RefMIs[i], SS, NewFI, RC, MF);
408       }
409   }
410
411   // Delete unused stack slots.
412   while (NextColor != -1) {
413     DOUT << "Removing unused stack object fi#" << NextColor << "\n";
414     MFI->RemoveStackObject(NextColor);
415     NextColor = AllColors.find_next(NextColor);
416   }
417
418   return true;
419 }
420
421 /// AllMemRefsCanBeUnfolded - Return true if all references of the specified
422 /// spill slot index can be unfolded.
423 bool StackSlotColoring::AllMemRefsCanBeUnfolded(int SS) {
424   SmallVector<MachineInstr*, 8> &RefMIs = SSRefs[SS];
425   for (unsigned i = 0, e = RefMIs.size(); i != e; ++i) {
426     MachineInstr *MI = RefMIs[i];
427     if (TII->isLoadFromStackSlot(MI, SS) ||
428         TII->isStoreToStackSlot(MI, SS))
429       // Restore and spill will become copies.
430       return true;
431     if (!TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(), false, false))
432       return false;
433     for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
434       MachineOperand &MO = MI->getOperand(j);
435       if (MO.isFI() && MO.getIndex() != SS)
436         // If it uses another frameindex, we can, currently* unfold it.
437         return false;
438     }
439   }
440   return true;
441 }
442
443 /// RewriteInstruction - Rewrite specified instruction by replacing references
444 /// to old frame index with new one.
445 void StackSlotColoring::RewriteInstruction(MachineInstr *MI, int OldFI,
446                                            int NewFI, MachineFunction &MF) {
447   for (unsigned i = 0, ee = MI->getNumOperands(); i != ee; ++i) {
448     MachineOperand &MO = MI->getOperand(i);
449     if (!MO.isFI())
450       continue;
451     int FI = MO.getIndex();
452     if (FI != OldFI)
453       continue;
454     MO.setIndex(NewFI);
455   }
456
457   // Update the MachineMemOperand for the new memory location.
458   // FIXME: We need a better method of managing these too.
459   SmallVector<MachineMemOperand, 2> MMOs(MI->memoperands_begin(),
460                                          MI->memoperands_end());
461   MI->clearMemOperands(MF);
462   const Value *OldSV = PseudoSourceValue::getFixedStack(OldFI);
463   for (unsigned i = 0, ee = MMOs.size(); i != ee; ++i) {
464     if (MMOs[i].getValue() != OldSV)
465       MI->addMemOperand(MF, MMOs[i]);
466     else {
467       MachineMemOperand MMO(PseudoSourceValue::getFixedStack(NewFI),
468                             MMOs[i].getFlags(), MMOs[i].getOffset(),
469                             MMOs[i].getSize(),  MMOs[i].getAlignment());
470       MI->addMemOperand(MF, MMO);
471     }
472   }
473 }
474
475 /// PropagateBackward - Traverse backward and look for the definition of
476 /// OldReg. If it can successfully update all of the references with NewReg,
477 /// do so and return true.
478 bool StackSlotColoring::PropagateBackward(MachineBasicBlock::iterator MII,
479                                           MachineBasicBlock *MBB,
480                                           unsigned OldReg, unsigned NewReg) {
481   if (MII == MBB->begin())
482     return false;
483
484   SmallVector<MachineOperand*, 4> Refs;
485   while (--MII != MBB->begin()) {
486     bool FoundDef = false;  // Not counting 2address def.
487     bool FoundUse = false;
488     bool FoundKill = false;
489     const TargetInstrDesc &TID = MII->getDesc();
490     for (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
491       MachineOperand &MO = MII->getOperand(i);
492       if (!MO.isReg())
493         continue;
494       unsigned Reg = MO.getReg();
495       if (Reg == 0)
496         continue;
497       if (Reg == OldReg) {
498         const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TID, i);
499         if (RC && !RC->contains(NewReg))
500           return false;
501
502         if (MO.isUse()) {
503           FoundUse = true;
504           if (MO.isKill())
505             FoundKill = true;
506           Refs.push_back(&MO);
507         } else {
508           Refs.push_back(&MO);
509           if (!MII->isRegTiedToUseOperand(i))
510             FoundDef = true;
511         }
512       } else if (TRI->regsOverlap(Reg, NewReg)) {
513         return false;
514       } else if (TRI->regsOverlap(Reg, OldReg)) {
515         if (!MO.isUse() || !MO.isKill())
516           return false;
517       }
518     }
519     if (FoundDef) {
520       for (unsigned i = 0, e = Refs.size(); i != e; ++i)
521         Refs[i]->setReg(NewReg);
522       return true;
523     }
524   }
525   return false;
526 }
527
528 /// PropagateForward - Traverse forward and look for the kill of OldReg. If
529 /// it can successfully update all of the uses with NewReg, do so and
530 /// return true.
531 bool StackSlotColoring::PropagateForward(MachineBasicBlock::iterator MII,
532                                          MachineBasicBlock *MBB,
533                                          unsigned OldReg, unsigned NewReg) {
534   if (MII == MBB->end())
535     return false;
536
537   SmallVector<MachineOperand*, 4> Uses;
538   while (++MII != MBB->end()) {
539     bool FoundUse = false;
540     bool FoundKill = false;
541     const TargetInstrDesc &TID = MII->getDesc();
542     for (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
543       MachineOperand &MO = MII->getOperand(i);
544       if (!MO.isReg())
545         continue;
546       unsigned Reg = MO.getReg();
547       if (Reg == 0)
548         continue;
549       if (Reg == OldReg) {
550         if (MO.isDef())
551           return false;
552
553         const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TID, i);
554         if (RC && !RC->contains(NewReg))
555           return false;
556         FoundUse = true;
557         if (MO.isKill())
558           FoundKill = true;
559         Uses.push_back(&MO);
560       } else if (TRI->regsOverlap(Reg, NewReg) ||
561                  TRI->regsOverlap(Reg, OldReg))
562         return false;
563     }
564     if (FoundKill) {
565       for (unsigned i = 0, e = Uses.size(); i != e; ++i)
566         Uses[i]->setReg(NewReg);
567       return true;
568     }
569   }
570   return false;
571 }
572
573 /// UnfoldAndRewriteInstruction - Rewrite specified instruction by unfolding
574 /// folded memory references and replacing those references with register
575 /// references instead.
576 void StackSlotColoring::UnfoldAndRewriteInstruction(MachineInstr *MI, int OldFI,
577                                                   unsigned Reg,
578                                                   const TargetRegisterClass *RC,
579                                                   MachineFunction &MF) {
580   MachineBasicBlock *MBB = MI->getParent();
581   if (unsigned DstReg = TII->isLoadFromStackSlot(MI, OldFI)) {
582     if (PropagateForward(MI, MBB, DstReg, Reg)) {
583       DOUT << "Eliminated load: ";
584       DEBUG(MI->dump());
585       ++NumLoadElim;
586     } else {
587       TII->copyRegToReg(*MBB, MI, DstReg, Reg, RC, RC);
588       ++NumRegRepl;
589     }
590   } else if (unsigned SrcReg = TII->isStoreToStackSlot(MI, OldFI)) {
591     if (MI->killsRegister(SrcReg) && PropagateBackward(MI, MBB, SrcReg, Reg)) {
592       DOUT << "Eliminated store: ";
593       DEBUG(MI->dump());
594       ++NumStoreElim;
595     } else {
596       TII->copyRegToReg(*MBB, MI, Reg, SrcReg, RC, RC);
597       ++NumRegRepl;
598     }
599   } else {
600     SmallVector<MachineInstr*, 4> NewMIs;
601     bool Success = TII->unfoldMemoryOperand(MF, MI, Reg, false, false, NewMIs);
602     assert(Success && "Failed to unfold!");
603     MBB->insert(MI, NewMIs[0]);
604     ++NumRegRepl;
605   }
606   MBB->erase(MI);
607 }
608
609 /// RemoveDeadStores - Scan through a basic block and look for loads followed
610 /// by stores.  If they're both using the same stack slot, then the store is
611 /// definitely dead.  This could obviously be much more aggressive (consider
612 /// pairs with instructions between them), but such extensions might have a
613 /// considerable compile time impact.
614 bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
615   // FIXME: This could be much more aggressive, but we need to investigate
616   // the compile time impact of doing so.
617   bool changed = false;
618
619   SmallVector<MachineInstr*, 4> toErase;
620
621   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
622        I != E; ++I) {
623     if (DCELimit != -1 && (int)NumDead >= DCELimit)
624       break;
625     
626     MachineBasicBlock::iterator NextMI = next(I);
627     if (NextMI == MBB->end()) continue;
628     
629     int FirstSS, SecondSS;
630     unsigned LoadReg = 0;
631     unsigned StoreReg = 0;
632     if (!(LoadReg = TII->isLoadFromStackSlot(I, FirstSS))) continue;
633     if (!(StoreReg = TII->isStoreToStackSlot(NextMI, SecondSS))) continue;
634     if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1) continue;
635     
636     ++NumDead;
637     changed = true;
638     
639     if (NextMI->findRegisterUseOperandIdx(LoadReg, true, 0) != -1) {
640       ++NumDead;
641       toErase.push_back(I);
642     }
643     
644     toErase.push_back(NextMI);
645     ++I;
646   }
647   
648   for (SmallVector<MachineInstr*, 4>::iterator I = toErase.begin(),
649        E = toErase.end(); I != E; ++I)
650     (*I)->eraseFromParent();
651   
652   return changed;
653 }
654
655
656 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
657   DOUT << "********** Stack Slot Coloring **********\n";
658
659   MFI = MF.getFrameInfo();
660   MRI = &MF.getRegInfo(); 
661   TII = MF.getTarget().getInstrInfo();
662   TRI = MF.getTarget().getRegisterInfo();
663   LS = &getAnalysis<LiveStacks>();
664   VRM = &getAnalysis<VirtRegMap>();
665   loopInfo = &getAnalysis<MachineLoopInfo>();
666
667   bool Changed = false;
668
669   unsigned NumSlots = LS->getNumIntervals();
670   if (NumSlots < 2) {
671     if (NumSlots == 0 || !VRM->HasUnusedRegisters())
672       // Nothing to do!
673       return false;
674   }
675
676   // Gather spill slot references
677   ScanForSpillSlotRefs(MF);
678   InitializeSlots();
679   Changed = ColorSlots(MF);
680
681   NextColor = -1;
682   SSIntervals.clear();
683   for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
684     SSRefs[i].clear();
685   SSRefs.clear();
686   OrigAlignments.clear();
687   OrigSizes.clear();
688   AllColors.clear();
689   UsedColors.clear();
690   for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
691     Assignments[i].clear();
692   Assignments.clear();
693
694   if (Changed) {
695     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
696       Changed |= RemoveDeadStores(I);
697   }
698
699   return Changed;
700 }