Instead of adding an isSS field to LiveInterval to denote stack slot. Use top bit...
[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 "llvm/CodeGen/Passes.h"
16 #include "llvm/CodeGen/LiveStackAnalysis.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include <vector>
25 using namespace llvm;
26
27 static cl::opt<bool>
28 DisableSharing("no-stack-slot-sharing",
29              cl::init(false), cl::Hidden,
30              cl::desc("Surpress slot sharing during stack coloring"));
31
32 static cl::opt<int>
33 DeleteLimit("slot-delete-limit", cl::init(-1), cl::Hidden,
34              cl::desc("Stack coloring slot deletion limit"));
35
36 STATISTIC(NumEliminated,   "Number of stack slots eliminated due to coloring");
37
38 namespace {
39   class VISIBILITY_HIDDEN StackSlotColoring : public MachineFunctionPass {
40     LiveStacks* LS;
41     MachineFrameInfo *MFI;
42
43     // SSIntervals - Spill slot intervals.
44     std::vector<LiveInterval*> SSIntervals;
45
46     // OrigAlignments - Alignments of stack objects before coloring.
47     SmallVector<unsigned, 16> OrigAlignments;
48
49     // OrigSizes - Sizess of stack objects before coloring.
50     SmallVector<unsigned, 16> OrigSizes;
51
52     // AllColors - If index is set, it's a spill slot, i.e. color.
53     // FIXME: This assumes PEI locate spill slot with smaller indices
54     // closest to stack pointer / frame pointer. Therefore, smaller
55     // index == better color.
56     BitVector AllColors;
57
58     // NextColor - Next "color" that's not yet used.
59     int NextColor;
60
61     // UsedColors - "Colors" that have been assigned.
62     BitVector UsedColors;
63
64     // Assignments - Color to intervals mapping.
65     SmallVector<SmallVector<LiveInterval*,4>,16> Assignments;
66
67   public:
68     static char ID; // Pass identification
69     StackSlotColoring() : MachineFunctionPass((intptr_t)&ID), NextColor(-1) {}
70     
71     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72       AU.addRequired<LiveStacks>();
73       MachineFunctionPass::getAnalysisUsage(AU);
74     }
75
76     virtual bool runOnMachineFunction(MachineFunction &MF);
77     virtual const char* getPassName() const {
78       return "Stack Slot Coloring";
79     }
80
81   private:
82     bool InitializeSlots();
83     bool OverlapWithAssignments(LiveInterval *li, int Color) const;
84     int ColorSlot(LiveInterval *li);
85     bool ColorSlots(MachineFunction &MF);
86   };
87 } // end anonymous namespace
88
89 char StackSlotColoring::ID = 0;
90
91 static RegisterPass<StackSlotColoring>
92 X("stack-slot-coloring", "Stack Slot Coloring");
93
94 FunctionPass *llvm::createStackSlotColoringPass() {
95   return new StackSlotColoring();
96 }
97
98 namespace {
99   // IntervalSorter - Comparison predicate that sort live intervals by
100   // their weight.
101   struct IntervalSorter {
102     bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
103       return LHS->weight > RHS->weight;
104     }
105   };
106 }
107
108 /// InitializeSlots - Process all spill stack slot liveintervals and add them
109 /// to a sorted (by weight) list.
110 bool StackSlotColoring::InitializeSlots() {
111   if (LS->getNumIntervals() < 2)
112     return false;
113
114   int LastFI = MFI->getObjectIndexEnd();
115   OrigAlignments.resize(LastFI);
116   OrigSizes.resize(LastFI);
117   AllColors.resize(LastFI);
118   UsedColors.resize(LastFI);
119   Assignments.resize(LastFI);
120
121   // Gather all spill slots into a list.
122   for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
123     LiveInterval &li = i->second;
124     int FI = li.getStackSlotIndex();
125     if (MFI->isDeadObjectIndex(FI))
126       continue;
127     SSIntervals.push_back(&li);
128     OrigAlignments[FI] = MFI->getObjectAlignment(FI);
129     OrigSizes[FI]      = MFI->getObjectSize(FI);
130     AllColors.set(FI);
131   }
132
133   // Sort them by weight.
134   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
135
136   // Get first "color".
137   NextColor = AllColors.find_first();
138   return true;
139 }
140
141 /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
142 /// LiveIntervals that have already been assigned to the specified color.
143 bool
144 StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
145   const SmallVector<LiveInterval*,4> &OtherLIs = Assignments[Color];
146   for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
147     LiveInterval *OtherLI = OtherLIs[i];
148     if (OtherLI->overlaps(*li))
149       return true;
150   }
151   return false;
152 }
153
154 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
155 ///
156 int StackSlotColoring::ColorSlot(LiveInterval *li) {
157   int Color = -1;
158   bool Share = false;
159   if (!DisableSharing &&
160       (DeleteLimit == -1 || (int)NumEliminated < DeleteLimit)) {
161     // Check if it's possible to reuse any of the used colors.
162     Color = UsedColors.find_first();
163     while (Color != -1) {
164       if (!OverlapWithAssignments(li, Color)) {
165         Share = true;
166         ++NumEliminated;
167         break;
168       }
169       Color = UsedColors.find_next(Color);
170     }
171   }
172
173   // Assign it to the first available color (assumed to be the best) if it's
174   // not possible to share a used color with other objects.
175   if (!Share) {
176     assert(NextColor != -1 && "No more spill slots?");
177     Color = NextColor;
178     UsedColors.set(Color);
179     NextColor = AllColors.find_next(NextColor);
180   }
181
182   // Record the assignment.
183   Assignments[Color].push_back(li);
184   int FI = li->getStackSlotIndex();
185   DOUT << "Assigning fi #" << FI << " to fi #" << Color << "\n";
186
187   // Change size and alignment of the allocated slot. If there are multiple
188   // objects sharing the same slot, then make sure the size and alignment
189   // are large enough for all.
190   unsigned Align = OrigAlignments[FI];
191   if (!Share || Align > MFI->getObjectAlignment(Color))
192     MFI->setObjectAlignment(Color, Align);
193   int64_t Size = OrigSizes[FI];
194   if (!Share || Size > MFI->getObjectSize(Color))
195     MFI->setObjectSize(Color, Size);
196   return Color;
197 }
198
199 /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
200 /// operands in the function.
201 bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
202   unsigned NumObjs = MFI->getObjectIndexEnd();
203   std::vector<int> SlotMapping(NumObjs, -1);
204
205   bool Changed = false;
206   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
207     LiveInterval *li = SSIntervals[i];
208     int SS = li->getStackSlotIndex();
209     int NewSS = ColorSlot(li);
210     SlotMapping[SS] = NewSS;
211     Changed |= (SS != NewSS);
212   }
213
214   if (!Changed)
215     return false;
216
217   // Rewrite all MO_FrameIndex operands.
218   // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
219   for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
220        MBB != E; ++MBB) {
221     for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
222          MII != EE; ++MII) {
223       MachineInstr &MI = *MII;
224       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
225         MachineOperand &MO = MI.getOperand(i);
226         if (!MO.isFrameIndex())
227           continue;
228         int FI = MO.getIndex();
229         if (FI < 0)
230           continue;
231         FI = SlotMapping[FI];
232         if (FI == -1)
233           continue;
234         MO.setIndex(FI);
235       }
236     }
237   }
238
239   // Delete unused stack slots.
240   while (NextColor != -1) {
241     DOUT << "Removing unused stack object fi #" << NextColor << "\n";
242     MFI->RemoveStackObject(NextColor);
243     NextColor = AllColors.find_next(NextColor);
244   }
245
246   return true;
247 }
248
249 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
250   DOUT << "******** Stack Slot Coloring ********\n";
251
252   MFI = MF.getFrameInfo();
253   LS = &getAnalysis<LiveStacks>();
254
255   bool Changed = false;
256   if (InitializeSlots())
257     Changed = ColorSlots(MF);
258
259   NextColor = -1;
260   SSIntervals.clear();
261   OrigAlignments.clear();
262   OrigSizes.clear();
263   AllColors.clear();
264   UsedColors.clear();
265   for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
266     Assignments[i].clear();
267   Assignments.clear();
268
269   return Changed;
270 }