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