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