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