1 //===-- StackSlotColoring.cpp - Stack slot coloring pass. -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the stack slot coloring pass.
12 //===----------------------------------------------------------------------===//
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"
39 DisableSharing("no-stack-slot-sharing",
40 cl::init(false), cl::Hidden,
41 cl::desc("Suppress slot sharing during stack coloring"));
43 static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
45 STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
46 STATISTIC(NumDead, "Number of trivially dead stack accesses eliminated");
49 class StackSlotColoring : public MachineFunctionPass {
52 MachineFrameInfo *MFI;
53 const TargetInstrInfo *TII;
54 const MachineLoopInfo *loopInfo;
56 // SSIntervals - Spill slot intervals.
57 std::vector<LiveInterval*> SSIntervals;
59 // SSRefs - Keep a list of frame index references for each spill slot.
60 SmallVector<SmallVector<MachineInstr*, 8>, 16> SSRefs;
62 // OrigAlignments - Alignments of stack objects before coloring.
63 SmallVector<unsigned, 16> OrigAlignments;
65 // OrigSizes - Sizess of stack objects before coloring.
66 SmallVector<unsigned, 16> OrigSizes;
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.
74 // NextColor - Next "color" that's not yet used.
77 // UsedColors - "Colors" that have been assigned.
80 // Assignments - Color to intervals mapping.
81 SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
84 static char ID; // Pass identification
86 MachineFunctionPass(ID), ColorWithRegs(false), NextColor(-1) {
87 initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
90 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
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);
103 virtual bool runOnMachineFunction(MachineFunction &MF);
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);
115 } // end anonymous namespace
117 char StackSlotColoring::ID = 0;
118 char &llvm::StackSlotColoringID = StackSlotColoring::ID;
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)
130 // IntervalSorter - Comparison predicate that sort live intervals by
132 struct IntervalSorter {
133 bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
134 return LHS->weight > RHS->weight;
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());
144 // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
145 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
147 MachineBasicBlock *MBB = &*MBBI;
148 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
149 for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
151 MachineInstr *MI = &*MII;
152 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
153 MachineOperand &MO = MI->getOperand(i);
156 int FI = MO.getIndex();
159 if (!LS->hasInterval(FI))
161 LiveInterval &li = LS->getInterval(FI);
162 if (!MI->isDebugValue())
163 li.weight += LiveIntervals::getSpillWeight(false, true, loopDepth);
164 SSRefs[FI].push_back(MI);
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);
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;
185 int FI = TargetRegisterInfo::stackSlot2Index(li.reg);
186 if (MFI->isDeadObjectIndex(FI))
188 SSIntervals.push_back(&li);
189 OrigAlignments[FI] = MFI->getObjectAlignment(FI);
190 OrigSizes[FI] = MFI->getObjectSize(FI);
193 DEBUG(dbgs() << '\n');
195 // Sort them by weight.
196 std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
198 // Get first "color".
199 NextColor = AllColors.find_first();
202 /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
203 /// LiveIntervals that have already been assigned to the specified color.
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))
215 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
217 int StackSlotColoring::ColorSlot(LiveInterval *li) {
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)) {
229 Color = UsedColors.find_next(Color);
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.
236 assert(NextColor != -1 && "No more spill slots?");
238 UsedColors.set(Color);
239 NextColor = AllColors.find_next(NextColor);
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");
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);
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);
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);
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];
288 // Sort them by new weight.
289 std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
292 for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
293 DEBUG(SSIntervals[i]->dump());
294 DEBUG(dbgs() << '\n');
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))
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);
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);
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);
331 int FI = MO.getIndex();
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);
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;
359 SmallVector<MachineInstr*, 4> toErase;
361 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
363 if (DCELimit != -1 && (int)NumDead >= DCELimit)
366 MachineBasicBlock::iterator NextMI = llvm::next(I);
367 if (NextMI == MBB->end()) continue;
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;
379 if (NextMI->findRegisterUseOperandIdx(LoadReg, true, 0) != -1) {
381 toErase.push_back(I);
384 toErase.push_back(NextMI);
388 for (SmallVector<MachineInstr*, 4>::iterator I = toErase.begin(),
389 E = toErase.end(); I != E; ++I)
390 (*I)->eraseFromParent();
396 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
398 dbgs() << "********** Stack Slot Coloring **********\n"
399 << "********** Function: "
400 << MF.getFunction()->getName() << '\n';
403 MFI = MF.getFrameInfo();
404 TII = MF.getTarget().getInstrInfo();
405 LS = &getAnalysis<LiveStacks>();
406 loopInfo = &getAnalysis<MachineLoopInfo>();
408 bool Changed = false;
410 unsigned NumSlots = LS->getNumIntervals();
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())
422 // Gather spill slot references
423 ScanForSpillSlotRefs(MF);
425 Changed = ColorSlots(MF);
429 for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
432 OrigAlignments.clear();
436 for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
437 Assignments[i].clear();
441 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
442 Changed |= RemoveDeadStores(I);