1 //===-- StackColoring.cpp -------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This 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.
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
19 // 2. Merge this pass with StackSlotColoring and allow merging of allocas with
22 //===----------------------------------------------------------------------===//
24 #define DEBUG_TYPE "stackcoloring"
25 #include "MachineTraceMetrics.h"
26 #include "llvm/Function.h"
27 #include "llvm/Module.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/ADT/DepthFirstIterator.h"
32 #include "llvm/ADT/PostOrderIterator.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SparseSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/CodeGen/LiveInterval.h"
38 #include "llvm/CodeGen/MachineLoopInfo.h"
39 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
40 #include "llvm/CodeGen/MachineDominators.h"
41 #include "llvm/CodeGen/MachineBasicBlock.h"
42 #include "llvm/CodeGen/MachineFunctionPass.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineRegisterInfo.h"
46 #include "llvm/CodeGen/MachineFrameInfo.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/Passes.h"
49 #include "llvm/CodeGen/SlotIndexes.h"
50 #include "llvm/DebugInfo.h"
51 #include "llvm/MC/MCInstrItineraries.h"
52 #include "llvm/Target/TargetInstrInfo.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/raw_ostream.h"
61 DisableColoring("no-stack-coloring",
62 cl::init(false), cl::Hidden,
63 cl::desc("Disable stack coloring"));
66 CheckEscapedAllocas("stack-coloring-check-escaped",
67 cl::init(true), cl::Hidden,
68 cl::desc("Look for allocas which escaped the lifetime region"));
70 STATISTIC(NumMarkerSeen, "Number of lifetime markers found.");
71 STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
72 STATISTIC(StackSlotMerged, "Number of stack slot merged.");
73 STATISTIC(EscapedAllocas,
74 "Number of allocas that escaped the lifetime region");
77 //===----------------------------------------------------------------------===//
79 //===----------------------------------------------------------------------===//
82 /// StackColoring - A machine pass for merging disjoint stack allocations,
83 /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
84 class StackColoring : public MachineFunctionPass {
85 MachineFrameInfo *MFI;
88 /// A class representing liveness information for a single basic block.
89 /// Each bit in the BitVector represents the liveness property
90 /// for a different stack slot.
91 struct BlockLifetimeInfo {
92 /// Which slots BEGINs in each basic block.
94 /// Which slots ENDs in each basic block.
96 /// Which slots are marked as LIVE_IN, coming into each basic block.
98 /// Which slots are marked as LIVE_OUT, coming out of each basic block.
102 /// Maps active slots (per bit) for each basic block.
103 DenseMap<MachineBasicBlock*, BlockLifetimeInfo> BlockLiveness;
105 /// Maps serial numbers to basic blocks.
106 DenseMap<MachineBasicBlock*, int> BasicBlocks;
107 /// Maps basic blocks to a serial number.
108 SmallVector<MachineBasicBlock*, 8> BasicBlockNumbering;
110 /// Maps liveness intervals for each slot.
111 SmallVector<LiveInterval*, 16> Intervals;
112 /// VNInfo is used for the construction of LiveIntervals.
113 VNInfo::Allocator VNInfoAllocator;
114 /// SlotIndex analysis object.
115 SlotIndexes *Indexes;
117 /// The list of lifetime markers found. These markers are to be removed
118 /// once the coloring is done.
119 SmallVector<MachineInstr*, 8> Markers;
121 /// SlotSizeSorter - A Sort utility for arranging stack slots according
123 struct SlotSizeSorter {
124 MachineFrameInfo *MFI;
125 SlotSizeSorter(MachineFrameInfo *mfi) : MFI(mfi) { }
126 bool operator()(int LHS, int RHS) {
127 // We use -1 to denote a uninteresting slot. Place these slots at the end.
128 if (LHS == -1) return false;
129 if (RHS == -1) return true;
130 // Sort according to size.
131 return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
137 StackColoring() : MachineFunctionPass(ID) {
138 initializeStackColoringPass(*PassRegistry::getPassRegistry());
140 void getAnalysisUsage(AnalysisUsage &AU) const;
141 bool runOnMachineFunction(MachineFunction &MF);
147 /// Removes all of the lifetime marker instructions from the function.
148 /// \returns true if any markers were removed.
149 bool removeAllMarkers();
151 /// Scan the machine function and find all of the lifetime markers.
152 /// Record the findings in the BEGIN and END vectors.
153 /// \returns the number of markers found.
154 unsigned collectMarkers(unsigned NumSlot);
156 /// Perform the dataflow calculation and calculate the lifetime for each of
157 /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
158 /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
159 /// in and out blocks.
160 void calculateLocalLiveness();
162 /// Construct the LiveIntervals for the slots.
163 void calculateLiveIntervals(unsigned NumSlots);
165 /// Go over the machine function and change instructions which use stack
166 /// slots to use the joint slots.
167 void remapInstructions(DenseMap<int, int> &SlotRemap);
169 /// The input program may contain intructions which are not inside lifetime
170 /// markers. This can happen due to a bug in the compiler or due to a bug in
171 /// user code (for example, returning a reference to a local variable).
172 /// This procedure checks all of the instructions in the function and
173 /// invalidates lifetime ranges which do not contain all of the instructions
174 /// which access that frame slot.
175 void removeInvalidSlotRanges();
177 /// Map entries which point to other entries to their destination.
178 /// A->B->C becomes A->C.
179 void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
181 } // end anonymous namespace
183 char StackColoring::ID = 0;
184 char &llvm::StackColoringID = StackColoring::ID;
186 INITIALIZE_PASS_BEGIN(StackColoring,
187 "stack-coloring", "Merge disjoint stack slots", false, false)
188 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
189 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
190 INITIALIZE_PASS_END(StackColoring,
191 "stack-coloring", "Merge disjoint stack slots", false, false)
193 void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
194 AU.addRequired<MachineDominatorTree>();
195 AU.addPreserved<MachineDominatorTree>();
196 AU.addRequired<SlotIndexes>();
197 MachineFunctionPass::getAnalysisUsage(AU);
200 void StackColoring::dump() {
201 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
203 unsigned Num = BasicBlocks[*FI];
204 DEBUG(dbgs()<<"Inspecting block #"<<Num<<" ["<<FI->getName()<<"]\n");
206 DEBUG(dbgs()<<"BEGIN : {");
207 for (unsigned i=0; i < BlockLiveness[*FI].Begin.size(); ++i)
208 DEBUG(dbgs()<<BlockLiveness[*FI].Begin.test(i)<<" ");
209 DEBUG(dbgs()<<"}\n");
211 DEBUG(dbgs()<<"END : {");
212 for (unsigned i=0; i < BlockLiveness[*FI].End.size(); ++i)
213 DEBUG(dbgs()<<BlockLiveness[*FI].End.test(i)<<" ");
215 DEBUG(dbgs()<<"}\n");
217 DEBUG(dbgs()<<"LIVE_IN: {");
218 for (unsigned i=0; i < BlockLiveness[*FI].LiveIn.size(); ++i)
219 DEBUG(dbgs()<<BlockLiveness[*FI].LiveIn.test(i)<<" ");
221 DEBUG(dbgs()<<"}\n");
222 DEBUG(dbgs()<<"LIVEOUT: {");
223 for (unsigned i=0; i < BlockLiveness[*FI].LiveOut.size(); ++i)
224 DEBUG(dbgs()<<BlockLiveness[*FI].LiveOut.test(i)<<" ");
225 DEBUG(dbgs()<<"}\n");
229 unsigned StackColoring::collectMarkers(unsigned NumSlot) {
230 unsigned MarkersFound = 0;
231 // Scan the function to find all lifetime markers.
232 // NOTE: We use the a reverse-post-order iteration to ensure that we obtain a
233 // deterministic numbering, and because we'll need a post-order iteration
234 // later for solving the liveness dataflow problem.
235 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
238 // Assign a serial number to this basic block.
239 BasicBlocks[*FI] = BasicBlockNumbering.size();
240 BasicBlockNumbering.push_back(*FI);
242 BlockLiveness[*FI].Begin.resize(NumSlot);
243 BlockLiveness[*FI].End.resize(NumSlot);
245 for (MachineBasicBlock::iterator BI = (*FI)->begin(), BE = (*FI)->end();
248 if (BI->getOpcode() != TargetOpcode::LIFETIME_START &&
249 BI->getOpcode() != TargetOpcode::LIFETIME_END)
252 Markers.push_back(BI);
254 bool IsStart = BI->getOpcode() == TargetOpcode::LIFETIME_START;
255 MachineOperand &MI = BI->getOperand(0);
256 unsigned Slot = MI.getIndex();
260 const Value *Allocation = MFI->getObjectAllocation(Slot);
262 DEBUG(dbgs()<<"Found lifetime marker for allocation: "<<
263 Allocation->getName()<<"\n");
267 BlockLiveness[*FI].Begin.set(Slot);
269 if (BlockLiveness[*FI].Begin.test(Slot)) {
270 // Allocas that start and end within a single block are handled
271 // specially when computing the LiveIntervals to avoid pessimizing
272 // the liveness propagation.
273 BlockLiveness[*FI].Begin.reset(Slot);
275 BlockLiveness[*FI].End.set(Slot);
281 // Update statistics.
282 NumMarkerSeen += MarkersFound;
286 void StackColoring::calculateLocalLiveness() {
287 // Perform a standard reverse dataflow computation to solve for
288 // global liveness. The BEGIN set here is equivalent to KILL in the standard
289 // formulation, and END is equivalent to GEN. The result of this computation
290 // is a map from blocks to bitvectors where the bitvectors represent which
291 // allocas are live in/out of that block.
292 SmallPtrSet<MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
293 BasicBlockNumbering.end());
294 unsigned NumSSMIters = 0;
300 SmallPtrSet<MachineBasicBlock*, 8> NextBBSet;
302 for (SmallVector<MachineBasicBlock*, 8>::iterator
303 PI = BasicBlockNumbering.begin(), PE = BasicBlockNumbering.end();
306 MachineBasicBlock *BB = *PI;
307 if (!BBSet.count(BB)) continue;
309 BitVector LocalLiveIn;
310 BitVector LocalLiveOut;
312 // Forward propagation from begins to ends.
313 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
314 PE = BB->pred_end(); PI != PE; ++PI)
315 LocalLiveIn |= BlockLiveness[*PI].LiveOut;
316 LocalLiveIn |= BlockLiveness[BB].End;
317 LocalLiveIn.reset(BlockLiveness[BB].Begin);
319 // Reverse propagation from ends to begins.
320 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
321 SE = BB->succ_end(); SI != SE; ++SI)
322 LocalLiveOut |= BlockLiveness[*SI].LiveIn;
323 LocalLiveOut |= BlockLiveness[BB].Begin;
324 LocalLiveOut.reset(BlockLiveness[BB].End);
326 LocalLiveIn |= LocalLiveOut;
327 LocalLiveOut |= LocalLiveIn;
329 // After adopting the live bits, we need to turn-off the bits which
330 // are de-activated in this block.
331 LocalLiveOut.reset(BlockLiveness[BB].End);
332 LocalLiveIn.reset(BlockLiveness[BB].Begin);
334 // If we have both BEGIN and END markers in the same basic block then
335 // we know that the BEGIN marker comes after the END, because we already
336 // handle the case where the BEGIN comes before the END when collecting
337 // the markers (and building the BEGIN/END vectore).
338 // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
339 // BEGIN and END because it means that the value lives before and after
341 BitVector LocalEndBegin = BlockLiveness[BB].End;
342 LocalEndBegin &= BlockLiveness[BB].Begin;
343 LocalLiveIn |= LocalEndBegin;
344 LocalLiveOut |= LocalEndBegin;
346 if (LocalLiveIn.test(BlockLiveness[BB].LiveIn)) {
348 BlockLiveness[BB].LiveIn |= LocalLiveIn;
350 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
351 PE = BB->pred_end(); PI != PE; ++PI)
352 NextBBSet.insert(*PI);
355 if (LocalLiveOut.test(BlockLiveness[BB].LiveOut)) {
357 BlockLiveness[BB].LiveOut |= LocalLiveOut;
359 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
360 SE = BB->succ_end(); SI != SE; ++SI)
361 NextBBSet.insert(*SI);
369 void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
370 SmallVector<SlotIndex, 16> Starts;
371 SmallVector<SlotIndex, 16> Finishes;
373 // For each block, find which slots are active within this block
374 // and update the live intervals.
375 for (MachineFunction::iterator MBB = MF->begin(), MBBe = MF->end();
376 MBB != MBBe; ++MBB) {
378 Starts.resize(NumSlots);
380 Finishes.resize(NumSlots);
382 // Create the interval for the basic blocks with lifetime markers in them.
383 for (SmallVector<MachineInstr*, 8>::iterator it = Markers.begin(),
384 e = Markers.end(); it != e; ++it) {
385 MachineInstr *MI = *it;
386 if (MI->getParent() != MBB)
389 assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
390 MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
391 "Invalid Lifetime marker");
393 bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
394 MachineOperand &Mo = MI->getOperand(0);
395 int Slot = Mo.getIndex();
396 assert(Slot >= 0 && "Invalid slot");
398 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
401 if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
402 Starts[Slot] = ThisIndex;
404 if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
405 Finishes[Slot] = ThisIndex;
409 // Create the interval of the blocks that we previously found to be 'alive'.
410 BitVector Alive = BlockLiveness[MBB].LiveIn;
411 Alive |= BlockLiveness[MBB].LiveOut;
414 for (int pos = Alive.find_first(); pos != -1;
415 pos = Alive.find_next(pos)) {
416 if (!Starts[pos].isValid())
417 Starts[pos] = Indexes->getMBBStartIdx(MBB);
418 if (!Finishes[pos].isValid())
419 Finishes[pos] = Indexes->getMBBEndIdx(MBB);
423 for (unsigned i = 0; i < NumSlots; ++i) {
424 assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
425 if (!Starts[i].isValid())
428 assert(Starts[i] && Finishes[i] && "Invalid interval");
429 VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
430 SlotIndex S = Starts[i];
431 SlotIndex F = Finishes[i];
433 // We have a single consecutive region.
434 Intervals[i]->addRange(LiveRange(S, F, ValNum));
436 // We have two non consecutive regions. This happens when
437 // LIFETIME_START appears after the LIFETIME_END marker.
438 SlotIndex NewStart = Indexes->getMBBStartIdx(MBB);
439 SlotIndex NewFin = Indexes->getMBBEndIdx(MBB);
440 Intervals[i]->addRange(LiveRange(NewStart, F, ValNum));
441 Intervals[i]->addRange(LiveRange(S, NewFin, ValNum));
447 bool StackColoring::removeAllMarkers() {
449 for (unsigned i = 0; i < Markers.size(); ++i) {
450 Markers[i]->eraseFromParent();
455 DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
459 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
460 unsigned FixedInstr = 0;
461 unsigned FixedMemOp = 0;
462 unsigned FixedDbg = 0;
463 MachineModuleInfo *MMI = &MF->getMMI();
465 // Remap debug information that refers to stack slots.
466 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
467 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
468 VE = VMap.end(); VI != VE; ++VI) {
469 const MDNode *Var = VI->first;
471 std::pair<unsigned, DebugLoc> &VP = VI->second;
472 if (SlotRemap.count(VP.first)) {
473 DEBUG(dbgs()<<"Remapping debug info for ["<<Var->getName()<<"].\n");
474 VP.first = SlotRemap[VP.first];
479 // Keep a list of *allocas* which need to be remapped.
480 DenseMap<const Value*, const Value*> Allocas;
481 for (DenseMap<int, int>::iterator it = SlotRemap.begin(),
482 e = SlotRemap.end(); it != e; ++it) {
483 const Value *From = MFI->getObjectAllocation(it->first);
484 const Value *To = MFI->getObjectAllocation(it->second);
485 assert(To && From && "Invalid allocation object");
489 // Remap all instructions to the new stack slots.
490 MachineFunction::iterator BB, BBE;
491 MachineBasicBlock::iterator I, IE;
492 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
493 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
495 // Skip lifetime markers. We'll remove them soon.
496 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
497 I->getOpcode() == TargetOpcode::LIFETIME_END)
500 // Update the MachineMemOperand to use the new alloca.
501 for (MachineInstr::mmo_iterator MM = I->memoperands_begin(),
502 E = I->memoperands_end(); MM != E; ++MM) {
503 MachineMemOperand *MMO = *MM;
505 const Value *V = MMO->getValue();
510 // Climb up and find the original alloca.
511 V = GetUnderlyingObject(V);
512 // If we did not find one, or if the one that we found is not in our
513 // map, then move on.
514 if (!V || !Allocas.count(V))
517 MMO->setValue(Allocas[V]);
521 // Update all of the machine instruction operands.
522 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
523 MachineOperand &MO = I->getOperand(i);
527 int FromSlot = MO.getIndex();
529 // Don't touch arguments.
533 // Only look at mapped slots.
534 if (!SlotRemap.count(FromSlot))
537 // In a debug build, check that the instruction that we are modifying is
538 // inside the expected live range. If the instruction is not inside
539 // the calculated range then it means that the alloca usage moved
540 // outside of the lifetime markers.
542 if (!I->isDebugValue()) {
543 SlotIndex Index = Indexes->getInstructionIndex(I);
544 LiveInterval *Interval = Intervals[FromSlot];
545 assert(Interval->find(Index) != Interval->end() &&
546 "Found instruction usage outside of live range.");
550 // Fix the machine instructions.
551 int ToSlot = SlotRemap[FromSlot];
557 DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
558 DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
559 DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
562 void StackColoring::removeInvalidSlotRanges() {
563 MachineFunction::iterator BB, BBE;
564 MachineBasicBlock::iterator I, IE;
565 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
566 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
568 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
569 I->getOpcode() == TargetOpcode::LIFETIME_END || I->isDebugValue())
572 // Check all of the machine operands.
573 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
574 MachineOperand &MO = I->getOperand(i);
579 int Slot = MO.getIndex();
584 if (Intervals[Slot]->empty())
587 // Check that the used slot is inside the calculated lifetime range.
588 // If it is not, warn about it and invalidate the range.
589 LiveInterval *Interval = Intervals[Slot];
590 SlotIndex Index = Indexes->getInstructionIndex(I);
591 if (Interval->find(Index) == Interval->end()) {
592 Intervals[Slot]->clear();
593 DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
600 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
602 // Expunge slot remap map.
603 for (unsigned i=0; i < NumSlots; ++i) {
604 // If we are remapping i
605 if (SlotRemap.count(i)) {
606 int Target = SlotRemap[i];
607 // As long as our target is mapped to something else, follow it.
608 while (SlotRemap.count(Target)) {
609 Target = SlotRemap[Target];
610 SlotRemap[i] = Target;
616 bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
617 DEBUG(dbgs() << "********** Stack Coloring **********\n"
618 << "********** Function: "
619 << ((const Value*)Func.getFunction())->getName() << '\n');
621 MFI = MF->getFrameInfo();
622 Indexes = &getAnalysis<SlotIndexes>();
623 BlockLiveness.clear();
625 BasicBlockNumbering.clear();
628 VNInfoAllocator.Reset();
630 unsigned NumSlots = MFI->getObjectIndexEnd();
632 // If there are no stack slots then there are no markers to remove.
636 SmallVector<int, 8> SortedSlots;
638 SortedSlots.reserve(NumSlots);
639 Intervals.reserve(NumSlots);
641 unsigned NumMarkers = collectMarkers(NumSlots);
643 unsigned TotalSize = 0;
644 DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
645 DEBUG(dbgs()<<"Slot structure:\n");
647 for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
648 DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
649 TotalSize += MFI->getObjectSize(i);
652 DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
654 // Don't continue because there are not enough lifetime markers, or the
655 // stack or too small, or we are told not to optimize the slots.
656 if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
657 DEBUG(dbgs()<<"Will not try to merge slots.\n");
658 return removeAllMarkers();
661 for (unsigned i=0; i < NumSlots; ++i) {
662 LiveInterval *LI = new LiveInterval(i, 0);
663 Intervals.push_back(LI);
664 LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
665 SortedSlots.push_back(i);
668 // Calculate the liveness of each block.
669 calculateLocalLiveness();
671 // Propagate the liveness information.
672 calculateLiveIntervals(NumSlots);
674 // Search for allocas which are used outside of the declared lifetime
676 if (CheckEscapedAllocas)
677 removeInvalidSlotRanges();
679 // Maps old slots to new slots.
680 DenseMap<int, int> SlotRemap;
681 unsigned RemovedSlots = 0;
682 unsigned ReducedSize = 0;
684 // Do not bother looking at empty intervals.
685 for (unsigned I = 0; I < NumSlots; ++I) {
686 if (Intervals[SortedSlots[I]]->empty())
690 // This is a simple greedy algorithm for merging allocas. First, sort the
691 // slots, placing the largest slots first. Next, perform an n^2 scan and look
692 // for disjoint slots. When you find disjoint slots, merge the samller one
693 // into the bigger one and update the live interval. Remove the small alloca
696 // Sort the slots according to their size. Place unused slots at the end.
697 std::sort(SortedSlots.begin(), SortedSlots.end(), SlotSizeSorter(MFI));
702 for (unsigned I = 0; I < NumSlots; ++I) {
703 if (SortedSlots[I] == -1)
706 for (unsigned J=I+1; J < NumSlots; ++J) {
707 if (SortedSlots[J] == -1)
710 int FirstSlot = SortedSlots[I];
711 int SecondSlot = SortedSlots[J];
712 LiveInterval *First = Intervals[FirstSlot];
713 LiveInterval *Second = Intervals[SecondSlot];
714 assert (!First->empty() && !Second->empty() && "Found an empty range");
716 // Merge disjoint slots.
717 if (!First->overlaps(*Second)) {
719 First->MergeRangesInAsValue(*Second, First->getValNumInfo(0));
720 SlotRemap[SecondSlot] = FirstSlot;
722 DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
723 SecondSlot<<" together.\n");
724 unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
725 MFI->getObjectAlignment(SecondSlot));
727 assert(MFI->getObjectSize(FirstSlot) >=
728 MFI->getObjectSize(SecondSlot) &&
729 "Merging a small object into a larger one");
732 ReducedSize += MFI->getObjectSize(SecondSlot);
733 MFI->setObjectAlignment(FirstSlot, MaxAlignment);
734 MFI->RemoveStackObject(SecondSlot);
740 // Record statistics.
741 StackSpaceSaved += ReducedSize;
742 StackSlotMerged += RemovedSlots;
743 DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
744 ReducedSize<<" bytes\n");
746 // Scan the entire function and update all machine operands that use frame
747 // indices to use the remapped frame index.
748 expungeSlotMap(SlotRemap, NumSlots);
749 remapInstructions(SlotRemap);
751 // Release the intervals.
752 for (unsigned I = 0; I < NumSlots; ++I) {
756 return removeAllMarkers();