Remove unused variable.
[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/Function.h"
17 #include "llvm/Module.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/LiveStackAnalysis.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/ADT/BitVector.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include <vector>
36 using namespace llvm;
37
38 static cl::opt<bool>
39 DisableSharing("no-stack-slot-sharing",
40              cl::init(false), cl::Hidden,
41              cl::desc("Suppress slot sharing during stack coloring"));
42
43 static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
44
45 STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
46 STATISTIC(NumDead,       "Number of trivially dead stack accesses eliminated");
47
48 namespace {
49   class StackSlotColoring : public MachineFunctionPass {
50     bool ColorWithRegs;
51     LiveStacks* LS;
52     MachineFrameInfo *MFI;
53     const TargetInstrInfo  *TII;
54     const MachineLoopInfo *loopInfo;
55
56     // SSIntervals - Spill slot intervals.
57     std::vector<LiveInterval*> SSIntervals;
58
59     // SSRefs - Keep a list of frame index references for each spill slot.
60     SmallVector<SmallVector<MachineInstr*, 8>, 16> SSRefs;
61
62     // OrigAlignments - Alignments of stack objects before coloring.
63     SmallVector<unsigned, 16> OrigAlignments;
64
65     // OrigSizes - Sizess of stack objects before coloring.
66     SmallVector<unsigned, 16> OrigSizes;
67
68     // AllColors - If index is set, it's a spill slot, i.e. color.
69     // FIXME: This assumes PEI locate spill slot with smaller indices
70     // closest to stack pointer / frame pointer. Therefore, smaller
71     // index == better color.
72     BitVector AllColors;
73
74     // NextColor - Next "color" that's not yet used.
75     int NextColor;
76
77     // UsedColors - "Colors" that have been assigned.
78     BitVector UsedColors;
79
80     // Assignments - Color to intervals mapping.
81     SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
82
83   public:
84     static char ID; // Pass identification
85     StackSlotColoring() :
86       MachineFunctionPass(ID), ColorWithRegs(false), NextColor(-1) {
87         initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
88       }
89
90     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
91       AU.setPreservesCFG();
92       AU.addRequired<SlotIndexes>();
93       AU.addPreserved<SlotIndexes>();
94       AU.addRequired<LiveStacks>();
95       AU.addRequired<VirtRegMap>();
96       AU.addPreserved<VirtRegMap>();
97       AU.addRequired<MachineLoopInfo>();
98       AU.addPreserved<MachineLoopInfo>();
99       AU.addPreservedID(MachineDominatorsID);
100       MachineFunctionPass::getAnalysisUsage(AU);
101     }
102
103     virtual bool runOnMachineFunction(MachineFunction &MF);
104
105   private:
106     void InitializeSlots();
107     void ScanForSpillSlotRefs(MachineFunction &MF);
108     bool OverlapWithAssignments(LiveInterval *li, int Color) const;
109     int ColorSlot(LiveInterval *li);
110     bool ColorSlots(MachineFunction &MF);
111     void RewriteInstruction(MachineInstr *MI, int OldFI, int NewFI,
112                             MachineFunction &MF);
113     bool RemoveDeadStores(MachineBasicBlock* MBB);
114   };
115 } // end anonymous namespace
116
117 char StackSlotColoring::ID = 0;
118 char &llvm::StackSlotColoringID = StackSlotColoring::ID;
119
120 INITIALIZE_PASS_BEGIN(StackSlotColoring, "stack-slot-coloring",
121                 "Stack Slot Coloring", false, false)
122 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
123 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
124 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
125 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
126 INITIALIZE_PASS_END(StackSlotColoring, "stack-slot-coloring",
127                 "Stack Slot Coloring", false, false)
128
129 namespace {
130   // IntervalSorter - Comparison predicate that sort live intervals by
131   // their weight.
132   struct IntervalSorter {
133     bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
134       return LHS->weight > RHS->weight;
135     }
136   };
137 }
138
139 /// ScanForSpillSlotRefs - Scan all the machine instructions for spill slot
140 /// references and update spill slot weights.
141 void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) {
142   SSRefs.resize(MFI->getObjectIndexEnd());
143
144   // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
145   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
146        MBBI != E; ++MBBI) {
147     MachineBasicBlock *MBB = &*MBBI;
148     unsigned loopDepth = loopInfo->getLoopDepth(MBB);
149     for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
150          MII != EE; ++MII) {
151       MachineInstr *MI = &*MII;
152       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
153         MachineOperand &MO = MI->getOperand(i);
154         if (!MO.isFI())
155           continue;
156         int FI = MO.getIndex();
157         if (FI < 0)
158           continue;
159         if (!LS->hasInterval(FI))
160           continue;
161         LiveInterval &li = LS->getInterval(FI);
162         if (!MI->isDebugValue())
163           li.weight += LiveIntervals::getSpillWeight(false, true, loopDepth);
164         SSRefs[FI].push_back(MI);
165       }
166     }
167   }
168 }
169
170 /// InitializeSlots - Process all spill stack slot liveintervals and add them
171 /// to a sorted (by weight) list.
172 void StackSlotColoring::InitializeSlots() {
173   int LastFI = MFI->getObjectIndexEnd();
174   OrigAlignments.resize(LastFI);
175   OrigSizes.resize(LastFI);
176   AllColors.resize(LastFI);
177   UsedColors.resize(LastFI);
178   Assignments.resize(LastFI);
179
180   // Gather all spill slots into a list.
181   DEBUG(dbgs() << "Spill slot intervals:\n");
182   for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
183     LiveInterval &li = i->second;
184     DEBUG(li.dump());
185     int FI = TargetRegisterInfo::stackSlot2Index(li.reg);
186     if (MFI->isDeadObjectIndex(FI))
187       continue;
188     SSIntervals.push_back(&li);
189     OrigAlignments[FI] = MFI->getObjectAlignment(FI);
190     OrigSizes[FI]      = MFI->getObjectSize(FI);
191     AllColors.set(FI);
192   }
193   DEBUG(dbgs() << '\n');
194
195   // Sort them by weight.
196   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
197
198   // Get first "color".
199   NextColor = AllColors.find_first();
200 }
201
202 /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
203 /// LiveIntervals that have already been assigned to the specified color.
204 bool
205 StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
206   const SmallVector<LiveInterval*,4> &OtherLIs = Assignments[Color];
207   for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
208     LiveInterval *OtherLI = OtherLIs[i];
209     if (OtherLI->overlaps(*li))
210       return true;
211   }
212   return false;
213 }
214
215 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
216 ///
217 int StackSlotColoring::ColorSlot(LiveInterval *li) {
218   int Color = -1;
219   bool Share = false;
220   if (!DisableSharing) {
221     // Check if it's possible to reuse any of the used colors.
222     Color = UsedColors.find_first();
223     while (Color != -1) {
224       if (!OverlapWithAssignments(li, Color)) {
225         Share = true;
226         ++NumEliminated;
227         break;
228       }
229       Color = UsedColors.find_next(Color);
230     }
231   }
232
233   // Assign it to the first available color (assumed to be the best) if it's
234   // not possible to share a used color with other objects.
235   if (!Share) {
236     assert(NextColor != -1 && "No more spill slots?");
237     Color = NextColor;
238     UsedColors.set(Color);
239     NextColor = AllColors.find_next(NextColor);
240   }
241
242   // Record the assignment.
243   Assignments[Color].push_back(li);
244   int FI = TargetRegisterInfo::stackSlot2Index(li->reg);
245   DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n");
246
247   // Change size and alignment of the allocated slot. If there are multiple
248   // objects sharing the same slot, then make sure the size and alignment
249   // are large enough for all.
250   unsigned Align = OrigAlignments[FI];
251   if (!Share || Align > MFI->getObjectAlignment(Color))
252     MFI->setObjectAlignment(Color, Align);
253   int64_t Size = OrigSizes[FI];
254   if (!Share || Size > MFI->getObjectSize(Color))
255     MFI->setObjectSize(Color, Size);
256   return Color;
257 }
258
259 /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
260 /// operands in the function.
261 bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
262   unsigned NumObjs = MFI->getObjectIndexEnd();
263   SmallVector<int, 16> SlotMapping(NumObjs, -1);
264   SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
265   SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
266   BitVector UsedColors(NumObjs);
267
268   DEBUG(dbgs() << "Color spill slot intervals:\n");
269   bool Changed = false;
270   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
271     LiveInterval *li = SSIntervals[i];
272     int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
273     int NewSS = ColorSlot(li);
274     assert(NewSS >= 0 && "Stack coloring failed?");
275     SlotMapping[SS] = NewSS;
276     RevMap[NewSS].push_back(SS);
277     SlotWeights[NewSS] += li->weight;
278     UsedColors.set(NewSS);
279     Changed |= (SS != NewSS);
280   }
281
282   DEBUG(dbgs() << "\nSpill slots after coloring:\n");
283   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
284     LiveInterval *li = SSIntervals[i];
285     int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
286     li->weight = SlotWeights[SS];
287   }
288   // Sort them by new weight.
289   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
290
291 #ifndef NDEBUG
292   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
293     DEBUG(SSIntervals[i]->dump());
294   DEBUG(dbgs() << '\n');
295 #endif
296
297   if (!Changed)
298     return false;
299
300   // Rewrite all MO_FrameIndex operands.
301   SmallVector<SmallSet<unsigned, 4>, 4> NewDefs(MF.getNumBlockIDs());
302   for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
303     int NewFI = SlotMapping[SS];
304     if (NewFI == -1 || (NewFI == (int)SS))
305       continue;
306
307     SmallVector<MachineInstr*, 8> &RefMIs = SSRefs[SS];
308     for (unsigned i = 0, e = RefMIs.size(); i != e; ++i)
309       RewriteInstruction(RefMIs[i], SS, NewFI, MF);
310   }
311
312   // Delete unused stack slots.
313   while (NextColor != -1) {
314     DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n");
315     MFI->RemoveStackObject(NextColor);
316     NextColor = AllColors.find_next(NextColor);
317   }
318
319   return true;
320 }
321
322 /// RewriteInstruction - Rewrite specified instruction by replacing references
323 /// to old frame index with new one.
324 void StackSlotColoring::RewriteInstruction(MachineInstr *MI, int OldFI,
325                                            int NewFI, MachineFunction &MF) {
326   // Update the operands.
327   for (unsigned i = 0, ee = MI->getNumOperands(); i != ee; ++i) {
328     MachineOperand &MO = MI->getOperand(i);
329     if (!MO.isFI())
330       continue;
331     int FI = MO.getIndex();
332     if (FI != OldFI)
333       continue;
334     MO.setIndex(NewFI);
335   }
336
337   // Update the memory references. This changes the MachineMemOperands
338   // directly. They may be in use by multiple instructions, however all
339   // instructions using OldFI are being rewritten to use NewFI.
340   const Value *OldSV = PseudoSourceValue::getFixedStack(OldFI);
341   const Value *NewSV = PseudoSourceValue::getFixedStack(NewFI);
342   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
343        E = MI->memoperands_end(); I != E; ++I)
344     if ((*I)->getValue() == OldSV)
345       (*I)->setValue(NewSV);
346 }
347
348
349 /// RemoveDeadStores - Scan through a basic block and look for loads followed
350 /// by stores.  If they're both using the same stack slot, then the store is
351 /// definitely dead.  This could obviously be much more aggressive (consider
352 /// pairs with instructions between them), but such extensions might have a
353 /// considerable compile time impact.
354 bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
355   // FIXME: This could be much more aggressive, but we need to investigate
356   // the compile time impact of doing so.
357   bool changed = false;
358
359   SmallVector<MachineInstr*, 4> toErase;
360
361   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
362        I != E; ++I) {
363     if (DCELimit != -1 && (int)NumDead >= DCELimit)
364       break;
365
366     MachineBasicBlock::iterator NextMI = llvm::next(I);
367     if (NextMI == MBB->end()) continue;
368
369     int FirstSS, SecondSS;
370     unsigned LoadReg = 0;
371     unsigned StoreReg = 0;
372     if (!(LoadReg = TII->isLoadFromStackSlot(I, FirstSS))) continue;
373     if (!(StoreReg = TII->isStoreToStackSlot(NextMI, SecondSS))) continue;
374     if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1) continue;
375
376     ++NumDead;
377     changed = true;
378
379     if (NextMI->findRegisterUseOperandIdx(LoadReg, true, 0) != -1) {
380       ++NumDead;
381       toErase.push_back(I);
382     }
383
384     toErase.push_back(NextMI);
385     ++I;
386   }
387
388   for (SmallVector<MachineInstr*, 4>::iterator I = toErase.begin(),
389        E = toErase.end(); I != E; ++I)
390     (*I)->eraseFromParent();
391
392   return changed;
393 }
394
395
396 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
397   DEBUG({
398       dbgs() << "********** Stack Slot Coloring **********\n"
399              << "********** Function: "
400              << MF.getFunction()->getName() << '\n';
401     });
402
403   MFI = MF.getFrameInfo();
404   TII = MF.getTarget().getInstrInfo();
405   LS = &getAnalysis<LiveStacks>();
406   loopInfo = &getAnalysis<MachineLoopInfo>();
407
408   bool Changed = false;
409
410   unsigned NumSlots = LS->getNumIntervals();
411   if (NumSlots == 0)
412     // Nothing to do!
413     return false;
414
415   // If there are calls to setjmp or sigsetjmp, don't perform stack slot
416   // coloring. The stack could be modified before the longjmp is executed,
417   // resulting in the wrong value being used afterwards. (See
418   // <rdar://problem/8007500>.)
419   if (MF.exposesReturnsTwice())
420     return false;
421
422   // Gather spill slot references
423   ScanForSpillSlotRefs(MF);
424   InitializeSlots();
425   Changed = ColorSlots(MF);
426
427   NextColor = -1;
428   SSIntervals.clear();
429   for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
430     SSRefs[i].clear();
431   SSRefs.clear();
432   OrigAlignments.clear();
433   OrigSizes.clear();
434   AllColors.clear();
435   UsedColors.clear();
436   for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
437     Assignments[i].clear();
438   Assignments.clear();
439
440   if (Changed) {
441     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
442       Changed |= RemoveDeadStores(I);
443   }
444
445   return Changed;
446 }