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