StackColoring.cpp revision f1af1feeee0f0ec797410762c006211f9c1e2a0f
1//===-- StackColoring.cpp -------------------------------------------------===//
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 pass implements the stack-coloring optimization that looks for
11// lifetime markers machine instructions (LIFESTART_BEGIN and LIFESTART_END),
12// which represent the possible lifetime of stack slots. It attempts to
13// merge disjoint stack slots and reduce the used stack space.
14// NOTE: This pass is not StackSlotColoring, which optimizes spill slots.
15//
16// TODO: In the future we plan to improve stack coloring in the following ways:
17// 1. Allow merging multiple small slots into a single larger slot at different
18//    offsets.
19// 2. Merge this pass with StackSlotColoring and allow merging of allocas with
20//    spill slots.
21//
22//===----------------------------------------------------------------------===//
23
24#define DEBUG_TYPE "stackcoloring"
25#include "llvm/CodeGen/Passes.h"
26#include "llvm/ADT/BitVector.h"
27#include "llvm/ADT/DepthFirstIterator.h"
28#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SparseSet.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/Analysis/Dominators.h"
34#include "llvm/Analysis/ValueTracking.h"
35#include "llvm/CodeGen/LiveInterval.h"
36#include "llvm/CodeGen/MachineBasicBlock.h"
37#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
38#include "llvm/CodeGen/MachineDominators.h"
39#include "llvm/CodeGen/MachineFrameInfo.h"
40#include "llvm/CodeGen/MachineFunctionPass.h"
41#include "llvm/CodeGen/MachineLoopInfo.h"
42#include "llvm/CodeGen/MachineMemOperand.h"
43#include "llvm/CodeGen/MachineModuleInfo.h"
44#include "llvm/CodeGen/MachineRegisterInfo.h"
45#include "llvm/CodeGen/SlotIndexes.h"
46#include "llvm/DebugInfo.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/Instructions.h"
49#include "llvm/IR/Module.h"
50#include "llvm/MC/MCInstrItineraries.h"
51#include "llvm/Support/CommandLine.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Support/raw_ostream.h"
54#include "llvm/Target/TargetInstrInfo.h"
55#include "llvm/Target/TargetRegisterInfo.h"
56
57using namespace llvm;
58
59static cl::opt<bool>
60DisableColoring("no-stack-coloring",
61        cl::init(false), cl::Hidden,
62        cl::desc("Disable stack coloring"));
63
64/// The user may write code that uses allocas outside of the declared lifetime
65/// zone. This can happen when the user returns a reference to a local
66/// data-structure. We can detect these cases and decide not to optimize the
67/// code. If this flag is enabled, we try to save the user.
68static cl::opt<bool>
69ProtectFromEscapedAllocas("protect-from-escaped-allocas",
70        cl::init(false), cl::Hidden,
71        cl::desc("Do not optimize lifetime zones that are broken"));
72
73STATISTIC(NumMarkerSeen,  "Number of lifetime markers found.");
74STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
75STATISTIC(StackSlotMerged, "Number of stack slot merged.");
76STATISTIC(EscapedAllocas,
77          "Number of allocas that escaped the lifetime region");
78
79//===----------------------------------------------------------------------===//
80//                           StackColoring Pass
81//===----------------------------------------------------------------------===//
82
83namespace {
84/// StackColoring - A machine pass for merging disjoint stack allocations,
85/// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
86class StackColoring : public MachineFunctionPass {
87  MachineFrameInfo *MFI;
88  MachineFunction *MF;
89
90  /// A class representing liveness information for a single basic block.
91  /// Each bit in the BitVector represents the liveness property
92  /// for a different stack slot.
93  struct BlockLifetimeInfo {
94    /// Which slots BEGINs in each basic block.
95    BitVector Begin;
96    /// Which slots ENDs in each basic block.
97    BitVector End;
98    /// Which slots are marked as LIVE_IN, coming into each basic block.
99    BitVector LiveIn;
100    /// Which slots are marked as LIVE_OUT, coming out of each basic block.
101    BitVector LiveOut;
102  };
103
104  /// Maps active slots (per bit) for each basic block.
105  DenseMap<MachineBasicBlock*, BlockLifetimeInfo> BlockLiveness;
106
107  /// Maps serial numbers to basic blocks.
108  DenseMap<MachineBasicBlock*, int> BasicBlocks;
109  /// Maps basic blocks to a serial number.
110  SmallVector<MachineBasicBlock*, 8> BasicBlockNumbering;
111
112  /// Maps liveness intervals for each slot.
113  SmallVector<LiveInterval*, 16> Intervals;
114  /// VNInfo is used for the construction of LiveIntervals.
115  VNInfo::Allocator VNInfoAllocator;
116  /// SlotIndex analysis object.
117  SlotIndexes *Indexes;
118
119  /// The list of lifetime markers found. These markers are to be removed
120  /// once the coloring is done.
121  SmallVector<MachineInstr*, 8> Markers;
122
123  /// SlotSizeSorter - A Sort utility for arranging stack slots according
124  /// to their size.
125  struct SlotSizeSorter {
126    MachineFrameInfo *MFI;
127    SlotSizeSorter(MachineFrameInfo *mfi) : MFI(mfi) { }
128    bool operator()(int LHS, int RHS) {
129      // We use -1 to denote a uninteresting slot. Place these slots at the end.
130      if (LHS == -1) return false;
131      if (RHS == -1) return true;
132      // Sort according to size.
133      return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
134  }
135};
136
137public:
138  static char ID;
139  StackColoring() : MachineFunctionPass(ID) {
140    initializeStackColoringPass(*PassRegistry::getPassRegistry());
141  }
142  void getAnalysisUsage(AnalysisUsage &AU) const;
143  bool runOnMachineFunction(MachineFunction &MF);
144
145private:
146  /// Debug.
147  void dump();
148
149  /// Removes all of the lifetime marker instructions from the function.
150  /// \returns true if any markers were removed.
151  bool removeAllMarkers();
152
153  /// Scan the machine function and find all of the lifetime markers.
154  /// Record the findings in the BEGIN and END vectors.
155  /// \returns the number of markers found.
156  unsigned collectMarkers(unsigned NumSlot);
157
158  /// Perform the dataflow calculation and calculate the lifetime for each of
159  /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
160  /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
161  /// in and out blocks.
162  void calculateLocalLiveness();
163
164  /// Construct the LiveIntervals for the slots.
165  void calculateLiveIntervals(unsigned NumSlots);
166
167  /// Go over the machine function and change instructions which use stack
168  /// slots to use the joint slots.
169  void remapInstructions(DenseMap<int, int> &SlotRemap);
170
171  /// The input program may contain intructions which are not inside lifetime
172  /// markers. This can happen due to a bug in the compiler or due to a bug in
173  /// user code (for example, returning a reference to a local variable).
174  /// This procedure checks all of the instructions in the function and
175  /// invalidates lifetime ranges which do not contain all of the instructions
176  /// which access that frame slot.
177  void removeInvalidSlotRanges();
178
179  /// Map entries which point to other entries to their destination.
180  ///   A->B->C becomes A->C.
181   void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
182};
183} // end anonymous namespace
184
185char StackColoring::ID = 0;
186char &llvm::StackColoringID = StackColoring::ID;
187
188INITIALIZE_PASS_BEGIN(StackColoring,
189                   "stack-coloring", "Merge disjoint stack slots", false, false)
190INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
191INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
192INITIALIZE_PASS_END(StackColoring,
193                   "stack-coloring", "Merge disjoint stack slots", false, false)
194
195void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
196  AU.addRequired<MachineDominatorTree>();
197  AU.addPreserved<MachineDominatorTree>();
198  AU.addRequired<SlotIndexes>();
199  MachineFunctionPass::getAnalysisUsage(AU);
200}
201
202void StackColoring::dump() {
203  for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
204       FI != FE; ++FI) {
205    DEBUG(dbgs()<<"Inspecting block #"<<BasicBlocks[*FI]<<
206          " ["<<FI->getName()<<"]\n");
207    DEBUG(dbgs()<<"BEGIN  : {");
208    for (unsigned i=0; i < BlockLiveness[*FI].Begin.size(); ++i)
209      DEBUG(dbgs()<<BlockLiveness[*FI].Begin.test(i)<<" ");
210    DEBUG(dbgs()<<"}\n");
211
212    DEBUG(dbgs()<<"END    : {");
213    for (unsigned i=0; i < BlockLiveness[*FI].End.size(); ++i)
214      DEBUG(dbgs()<<BlockLiveness[*FI].End.test(i)<<" ");
215
216    DEBUG(dbgs()<<"}\n");
217
218    DEBUG(dbgs()<<"LIVE_IN: {");
219    for (unsigned i=0; i < BlockLiveness[*FI].LiveIn.size(); ++i)
220      DEBUG(dbgs()<<BlockLiveness[*FI].LiveIn.test(i)<<" ");
221
222    DEBUG(dbgs()<<"}\n");
223    DEBUG(dbgs()<<"LIVEOUT: {");
224    for (unsigned i=0; i < BlockLiveness[*FI].LiveOut.size(); ++i)
225      DEBUG(dbgs()<<BlockLiveness[*FI].LiveOut.test(i)<<" ");
226    DEBUG(dbgs()<<"}\n");
227  }
228}
229
230unsigned StackColoring::collectMarkers(unsigned NumSlot) {
231  unsigned MarkersFound = 0;
232  // Scan the function to find all lifetime markers.
233  // NOTE: We use the a reverse-post-order iteration to ensure that we obtain a
234  // deterministic numbering, and because we'll need a post-order iteration
235  // later for solving the liveness dataflow problem.
236  for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
237       FI != FE; ++FI) {
238
239    // Assign a serial number to this basic block.
240    BasicBlocks[*FI] = BasicBlockNumbering.size();
241    BasicBlockNumbering.push_back(*FI);
242
243    BlockLiveness[*FI].Begin.resize(NumSlot);
244    BlockLiveness[*FI].End.resize(NumSlot);
245
246    for (MachineBasicBlock::iterator BI = (*FI)->begin(), BE = (*FI)->end();
247         BI != BE; ++BI) {
248
249      if (BI->getOpcode() != TargetOpcode::LIFETIME_START &&
250          BI->getOpcode() != TargetOpcode::LIFETIME_END)
251        continue;
252
253      Markers.push_back(BI);
254
255      bool IsStart = BI->getOpcode() == TargetOpcode::LIFETIME_START;
256      MachineOperand &MI = BI->getOperand(0);
257      unsigned Slot = MI.getIndex();
258
259      MarkersFound++;
260
261      const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
262      if (Allocation) {
263        DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<<
264              " with allocation: "<< Allocation->getName()<<"\n");
265      }
266
267      if (IsStart) {
268        BlockLiveness[*FI].Begin.set(Slot);
269      } else {
270        if (BlockLiveness[*FI].Begin.test(Slot)) {
271          // Allocas that start and end within a single block are handled
272          // specially when computing the LiveIntervals to avoid pessimizing
273          // the liveness propagation.
274          BlockLiveness[*FI].Begin.reset(Slot);
275        } else {
276          BlockLiveness[*FI].End.set(Slot);
277        }
278      }
279    }
280  }
281
282  // Update statistics.
283  NumMarkerSeen += MarkersFound;
284  return MarkersFound;
285}
286
287void StackColoring::calculateLocalLiveness() {
288  // Perform a standard reverse dataflow computation to solve for
289  // global liveness.  The BEGIN set here is equivalent to KILL in the standard
290  // formulation, and END is equivalent to GEN.  The result of this computation
291  // is a map from blocks to bitvectors where the bitvectors represent which
292  // allocas are live in/out of that block.
293  SmallPtrSet<MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
294                                           BasicBlockNumbering.end());
295  unsigned NumSSMIters = 0;
296  bool changed = true;
297  while (changed) {
298    changed = false;
299    ++NumSSMIters;
300
301    SmallPtrSet<MachineBasicBlock*, 8> NextBBSet;
302
303    for (SmallVector<MachineBasicBlock*, 8>::iterator
304         PI = BasicBlockNumbering.begin(), PE = BasicBlockNumbering.end();
305         PI != PE; ++PI) {
306
307      MachineBasicBlock *BB = *PI;
308      if (!BBSet.count(BB)) continue;
309
310      BitVector LocalLiveIn;
311      BitVector LocalLiveOut;
312
313      // Forward propagation from begins to ends.
314      for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
315           PE = BB->pred_end(); PI != PE; ++PI)
316        LocalLiveIn |= BlockLiveness[*PI].LiveOut;
317      LocalLiveIn |= BlockLiveness[BB].End;
318      LocalLiveIn.reset(BlockLiveness[BB].Begin);
319
320      // Reverse propagation from ends to begins.
321      for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
322           SE = BB->succ_end(); SI != SE; ++SI)
323        LocalLiveOut |= BlockLiveness[*SI].LiveIn;
324      LocalLiveOut |= BlockLiveness[BB].Begin;
325      LocalLiveOut.reset(BlockLiveness[BB].End);
326
327      LocalLiveIn |= LocalLiveOut;
328      LocalLiveOut |= LocalLiveIn;
329
330      // After adopting the live bits, we need to turn-off the bits which
331      // are de-activated in this block.
332      LocalLiveOut.reset(BlockLiveness[BB].End);
333      LocalLiveIn.reset(BlockLiveness[BB].Begin);
334
335      // If we have both BEGIN and END markers in the same basic block then
336      // we know that the BEGIN marker comes after the END, because we already
337      // handle the case where the BEGIN comes before the END when collecting
338      // the markers (and building the BEGIN/END vectore).
339      // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
340      // BEGIN and END because it means that the value lives before and after
341      // this basic block.
342      BitVector LocalEndBegin = BlockLiveness[BB].End;
343      LocalEndBegin &= BlockLiveness[BB].Begin;
344      LocalLiveIn |= LocalEndBegin;
345      LocalLiveOut |= LocalEndBegin;
346
347      if (LocalLiveIn.test(BlockLiveness[BB].LiveIn)) {
348        changed = true;
349        BlockLiveness[BB].LiveIn |= LocalLiveIn;
350
351        for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
352             PE = BB->pred_end(); PI != PE; ++PI)
353          NextBBSet.insert(*PI);
354      }
355
356      if (LocalLiveOut.test(BlockLiveness[BB].LiveOut)) {
357        changed = true;
358        BlockLiveness[BB].LiveOut |= LocalLiveOut;
359
360        for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
361             SE = BB->succ_end(); SI != SE; ++SI)
362          NextBBSet.insert(*SI);
363      }
364    }
365
366    BBSet = NextBBSet;
367  }// while changed.
368}
369
370void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
371  SmallVector<SlotIndex, 16> Starts;
372  SmallVector<SlotIndex, 16> Finishes;
373
374  // For each block, find which slots are active within this block
375  // and update the live intervals.
376  for (MachineFunction::iterator MBB = MF->begin(), MBBe = MF->end();
377       MBB != MBBe; ++MBB) {
378    Starts.clear();
379    Starts.resize(NumSlots);
380    Finishes.clear();
381    Finishes.resize(NumSlots);
382
383    // Create the interval for the basic blocks with lifetime markers in them.
384    for (SmallVector<MachineInstr*, 8>::iterator it = Markers.begin(),
385         e = Markers.end(); it != e; ++it) {
386      MachineInstr *MI = *it;
387      if (MI->getParent() != MBB)
388        continue;
389
390      assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
391              MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
392             "Invalid Lifetime marker");
393
394      bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
395      MachineOperand &Mo = MI->getOperand(0);
396      int Slot = Mo.getIndex();
397      assert(Slot >= 0 && "Invalid slot");
398
399      SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
400
401      if (IsStart) {
402        if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
403          Starts[Slot] = ThisIndex;
404      } else {
405        if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
406          Finishes[Slot] = ThisIndex;
407      }
408    }
409
410    // Create the interval of the blocks that we previously found to be 'alive'.
411    BitVector Alive = BlockLiveness[MBB].LiveIn;
412    Alive |= BlockLiveness[MBB].LiveOut;
413
414    if (Alive.any()) {
415      for (int pos = Alive.find_first(); pos != -1;
416           pos = Alive.find_next(pos)) {
417        if (!Starts[pos].isValid())
418          Starts[pos] = Indexes->getMBBStartIdx(MBB);
419        if (!Finishes[pos].isValid())
420          Finishes[pos] = Indexes->getMBBEndIdx(MBB);
421      }
422    }
423
424    for (unsigned i = 0; i < NumSlots; ++i) {
425      assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
426      if (!Starts[i].isValid())
427        continue;
428
429      assert(Starts[i] && Finishes[i] && "Invalid interval");
430      VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
431      SlotIndex S = Starts[i];
432      SlotIndex F = Finishes[i];
433      if (S < F) {
434        // We have a single consecutive region.
435        Intervals[i]->addRange(LiveRange(S, F, ValNum));
436      } else {
437        // We have two non consecutive regions. This happens when
438        // LIFETIME_START appears after the LIFETIME_END marker.
439        SlotIndex NewStart = Indexes->getMBBStartIdx(MBB);
440        SlotIndex NewFin = Indexes->getMBBEndIdx(MBB);
441        Intervals[i]->addRange(LiveRange(NewStart, F, ValNum));
442        Intervals[i]->addRange(LiveRange(S, NewFin, ValNum));
443      }
444    }
445  }
446}
447
448bool StackColoring::removeAllMarkers() {
449  unsigned Count = 0;
450  for (unsigned i = 0; i < Markers.size(); ++i) {
451    Markers[i]->eraseFromParent();
452    Count++;
453  }
454  Markers.clear();
455
456  DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
457  return Count;
458}
459
460void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
461  unsigned FixedInstr = 0;
462  unsigned FixedMemOp = 0;
463  unsigned FixedDbg = 0;
464  MachineModuleInfo *MMI = &MF->getMMI();
465
466  // Remap debug information that refers to stack slots.
467  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
468  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
469       VE = VMap.end(); VI != VE; ++VI) {
470    const MDNode *Var = VI->first;
471    if (!Var) continue;
472    std::pair<unsigned, DebugLoc> &VP = VI->second;
473    if (SlotRemap.count(VP.first)) {
474      DEBUG(dbgs()<<"Remapping debug info for ["<<Var->getName()<<"].\n");
475      VP.first = SlotRemap[VP.first];
476      FixedDbg++;
477    }
478  }
479
480  // Keep a list of *allocas* which need to be remapped.
481  DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
482  for (DenseMap<int, int>::iterator it = SlotRemap.begin(),
483       e = SlotRemap.end(); it != e; ++it) {
484    const AllocaInst *From = MFI->getObjectAllocation(it->first);
485    const AllocaInst *To = MFI->getObjectAllocation(it->second);
486    assert(To && From && "Invalid allocation object");
487    Allocas[From] = To;
488  }
489
490  // Remap all instructions to the new stack slots.
491  MachineFunction::iterator BB, BBE;
492  MachineBasicBlock::iterator I, IE;
493  for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
494    for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
495
496      // Skip lifetime markers. We'll remove them soon.
497      if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
498          I->getOpcode() == TargetOpcode::LIFETIME_END)
499        continue;
500
501      // Update the MachineMemOperand to use the new alloca.
502      for (MachineInstr::mmo_iterator MM = I->memoperands_begin(),
503           E = I->memoperands_end(); MM != E; ++MM) {
504        MachineMemOperand *MMO = *MM;
505
506        const Value *V = MMO->getValue();
507
508        if (!V)
509          continue;
510
511        // Climb up and find the original alloca.
512        V = GetUnderlyingObject(V);
513        // If we did not find one, or if the one that we found is not in our
514        // map, then move on.
515        if (!V || !isa<AllocaInst>(V)) {
516          // Clear mem operand since we don't know for sure that it doesn't
517          // alias a merged alloca.
518          MMO->setValue(0);
519          continue;
520        }
521        const AllocaInst *AI= cast<AllocaInst>(V);
522        if (!Allocas.count(AI))
523          continue;
524
525        MMO->setValue(Allocas[AI]);
526        FixedMemOp++;
527      }
528
529      // Update all of the machine instruction operands.
530      for (unsigned i = 0 ; i <  I->getNumOperands(); ++i) {
531        MachineOperand &MO = I->getOperand(i);
532
533        if (!MO.isFI())
534          continue;
535        int FromSlot = MO.getIndex();
536
537        // Don't touch arguments.
538        if (FromSlot<0)
539          continue;
540
541        // Only look at mapped slots.
542        if (!SlotRemap.count(FromSlot))
543          continue;
544
545        // In a debug build, check that the instruction that we are modifying is
546        // inside the expected live range. If the instruction is not inside
547        // the calculated range then it means that the alloca usage moved
548        // outside of the lifetime markers, or that the user has a bug.
549        // NOTE: Alloca address calculations which happen outside the lifetime
550        // zone are are okay, despite the fact that we don't have a good way
551        // for validating all of the usages of the calculation.
552#ifndef NDEBUG
553        bool TouchesMemory = I->mayLoad() || I->mayStore();
554        // If we *don't* protect the user from escaped allocas, don't bother
555        // validating the instructions.
556        if (!I->isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) {
557          SlotIndex Index = Indexes->getInstructionIndex(I);
558          LiveInterval *Interval = Intervals[FromSlot];
559          assert(Interval->find(Index) != Interval->end() &&
560               "Found instruction usage outside of live range.");
561        }
562#endif
563
564        // Fix the machine instructions.
565        int ToSlot = SlotRemap[FromSlot];
566        MO.setIndex(ToSlot);
567        FixedInstr++;
568      }
569    }
570
571  DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
572  DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
573  DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
574}
575
576void StackColoring::removeInvalidSlotRanges() {
577  MachineFunction::iterator BB, BBE;
578  MachineBasicBlock::iterator I, IE;
579  for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
580    for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
581
582      if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
583          I->getOpcode() == TargetOpcode::LIFETIME_END || I->isDebugValue())
584        continue;
585
586      // Some intervals are suspicious! In some cases we find address
587      // calculations outside of the lifetime zone, but not actual memory
588      // read or write. Memory accesses outside of the lifetime zone are a clear
589      // violation, but address calculations are okay. This can happen when
590      // GEPs are hoisted outside of the lifetime zone.
591      // So, in here we only check instructions which can read or write memory.
592      if (!I->mayLoad() && !I->mayStore())
593        continue;
594
595      // Check all of the machine operands.
596      for (unsigned i = 0 ; i <  I->getNumOperands(); ++i) {
597        MachineOperand &MO = I->getOperand(i);
598
599        if (!MO.isFI())
600          continue;
601
602        int Slot = MO.getIndex();
603
604        if (Slot<0)
605          continue;
606
607        if (Intervals[Slot]->empty())
608          continue;
609
610        // Check that the used slot is inside the calculated lifetime range.
611        // If it is not, warn about it and invalidate the range.
612        LiveInterval *Interval = Intervals[Slot];
613        SlotIndex Index = Indexes->getInstructionIndex(I);
614        if (Interval->find(Index) == Interval->end()) {
615          Intervals[Slot]->clear();
616          DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
617          EscapedAllocas++;
618        }
619      }
620    }
621}
622
623void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
624                                   unsigned NumSlots) {
625  // Expunge slot remap map.
626  for (unsigned i=0; i < NumSlots; ++i) {
627    // If we are remapping i
628    if (SlotRemap.count(i)) {
629      int Target = SlotRemap[i];
630      // As long as our target is mapped to something else, follow it.
631      while (SlotRemap.count(Target)) {
632        Target = SlotRemap[Target];
633        SlotRemap[i] = Target;
634      }
635    }
636  }
637}
638
639bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
640  DEBUG(dbgs() << "********** Stack Coloring **********\n"
641               << "********** Function: "
642               << ((const Value*)Func.getFunction())->getName() << '\n');
643  MF = &Func;
644  MFI = MF->getFrameInfo();
645  Indexes = &getAnalysis<SlotIndexes>();
646  BlockLiveness.clear();
647  BasicBlocks.clear();
648  BasicBlockNumbering.clear();
649  Markers.clear();
650  Intervals.clear();
651  VNInfoAllocator.Reset();
652
653  unsigned NumSlots = MFI->getObjectIndexEnd();
654
655  // If there are no stack slots then there are no markers to remove.
656  if (!NumSlots)
657    return false;
658
659  SmallVector<int, 8> SortedSlots;
660
661  SortedSlots.reserve(NumSlots);
662  Intervals.reserve(NumSlots);
663
664  unsigned NumMarkers = collectMarkers(NumSlots);
665
666  unsigned TotalSize = 0;
667  DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
668  DEBUG(dbgs()<<"Slot structure:\n");
669
670  for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
671    DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
672    TotalSize += MFI->getObjectSize(i);
673  }
674
675  DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
676
677  // Don't continue because there are not enough lifetime markers, or the
678  // stack is too small, or we are told not to optimize the slots.
679  if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
680    DEBUG(dbgs()<<"Will not try to merge slots.\n");
681    return removeAllMarkers();
682  }
683
684  for (unsigned i=0; i < NumSlots; ++i) {
685    LiveInterval *LI = new LiveInterval(i, 0);
686    Intervals.push_back(LI);
687    LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
688    SortedSlots.push_back(i);
689  }
690
691  // Calculate the liveness of each block.
692  calculateLocalLiveness();
693
694  // Propagate the liveness information.
695  calculateLiveIntervals(NumSlots);
696
697  // Search for allocas which are used outside of the declared lifetime
698  // markers.
699  if (ProtectFromEscapedAllocas)
700    removeInvalidSlotRanges();
701
702  // Maps old slots to new slots.
703  DenseMap<int, int> SlotRemap;
704  unsigned RemovedSlots = 0;
705  unsigned ReducedSize = 0;
706
707  // Do not bother looking at empty intervals.
708  for (unsigned I = 0; I < NumSlots; ++I) {
709    if (Intervals[SortedSlots[I]]->empty())
710      SortedSlots[I] = -1;
711  }
712
713  // This is a simple greedy algorithm for merging allocas. First, sort the
714  // slots, placing the largest slots first. Next, perform an n^2 scan and look
715  // for disjoint slots. When you find disjoint slots, merge the samller one
716  // into the bigger one and update the live interval. Remove the small alloca
717  // and continue.
718
719  // Sort the slots according to their size. Place unused slots at the end.
720  // Use stable sort to guarantee deterministic code generation.
721  std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
722                   SlotSizeSorter(MFI));
723
724  bool Chanded = true;
725  while (Chanded) {
726    Chanded = false;
727    for (unsigned I = 0; I < NumSlots; ++I) {
728      if (SortedSlots[I] == -1)
729        continue;
730
731      for (unsigned J=I+1; J < NumSlots; ++J) {
732        if (SortedSlots[J] == -1)
733          continue;
734
735        int FirstSlot = SortedSlots[I];
736        int SecondSlot = SortedSlots[J];
737        LiveInterval *First = Intervals[FirstSlot];
738        LiveInterval *Second = Intervals[SecondSlot];
739        assert (!First->empty() && !Second->empty() && "Found an empty range");
740
741        // Merge disjoint slots.
742        if (!First->overlaps(*Second)) {
743          Chanded = true;
744          First->MergeRangesInAsValue(*Second, First->getValNumInfo(0));
745          SlotRemap[SecondSlot] = FirstSlot;
746          SortedSlots[J] = -1;
747          DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
748                SecondSlot<<" together.\n");
749          unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
750                                           MFI->getObjectAlignment(SecondSlot));
751
752          assert(MFI->getObjectSize(FirstSlot) >=
753                 MFI->getObjectSize(SecondSlot) &&
754                 "Merging a small object into a larger one");
755
756          RemovedSlots+=1;
757          ReducedSize += MFI->getObjectSize(SecondSlot);
758          MFI->setObjectAlignment(FirstSlot, MaxAlignment);
759          MFI->RemoveStackObject(SecondSlot);
760        }
761      }
762    }
763  }// While changed.
764
765  // Record statistics.
766  StackSpaceSaved += ReducedSize;
767  StackSlotMerged += RemovedSlots;
768  DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
769        ReducedSize<<" bytes\n");
770
771  // Scan the entire function and update all machine operands that use frame
772  // indices to use the remapped frame index.
773  expungeSlotMap(SlotRemap, NumSlots);
774  remapInstructions(SlotRemap);
775
776  // Release the intervals.
777  for (unsigned I = 0; I < NumSlots; ++I) {
778    delete Intervals[I];
779  }
780
781  return removeAllMarkers();
782}
783