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 "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/Function.h"
49 #include "llvm/Instructions.h"
50 #include "llvm/MC/MCInstrItineraries.h"
51 #include "llvm/Module.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"
61 DisableColoring("no-stack-coloring",
62 cl::init(false), cl::Hidden,
63 cl::desc("Disable stack coloring"));
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.
70 ProtectFromEscapedAllocas("protect-from-escaped-allocas",
71 cl::init(false), cl::Hidden,
72 cl::desc("Do not optimize lifetime zones that are broken"));
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");
80 //===----------------------------------------------------------------------===//
82 //===----------------------------------------------------------------------===//
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;
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.
97 /// Which slots ENDs in each basic block.
99 /// Which slots are marked as LIVE_IN, coming into each basic block.
101 /// Which slots are marked as LIVE_OUT, coming out of each basic block.
105 /// Maps active slots (per bit) for each basic block.
106 DenseMap<MachineBasicBlock*, BlockLifetimeInfo> BlockLiveness;
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;
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;
120 /// The list of lifetime markers found. These markers are to be removed
121 /// once the coloring is done.
122 SmallVector<MachineInstr*, 8> Markers;
124 /// SlotSizeSorter - A Sort utility for arranging stack slots according
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);
140 StackColoring() : MachineFunctionPass(ID) {
141 initializeStackColoringPass(*PassRegistry::getPassRegistry());
143 void getAnalysisUsage(AnalysisUsage &AU) const;
144 bool runOnMachineFunction(MachineFunction &MF);
150 /// Removes all of the lifetime marker instructions from the function.
151 /// \returns true if any markers were removed.
152 bool removeAllMarkers();
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);
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();
165 /// Construct the LiveIntervals for the slots.
166 void calculateLiveIntervals(unsigned NumSlots);
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);
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();
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);
184 } // end anonymous namespace
186 char StackColoring::ID = 0;
187 char &llvm::StackColoringID = StackColoring::ID;
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)
196 void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
197 AU.addRequired<MachineDominatorTree>();
198 AU.addPreserved<MachineDominatorTree>();
199 AU.addRequired<SlotIndexes>();
200 MachineFunctionPass::getAnalysisUsage(AU);
203 void StackColoring::dump() {
204 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
206 unsigned Num = BasicBlocks[*FI];
207 DEBUG(dbgs()<<"Inspecting block #"<<Num<<" ["<<FI->getName()<<"]\n");
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");
214 DEBUG(dbgs()<<"END : {");
215 for (unsigned i=0; i < BlockLiveness[*FI].End.size(); ++i)
216 DEBUG(dbgs()<<BlockLiveness[*FI].End.test(i)<<" ");
218 DEBUG(dbgs()<<"}\n");
220 DEBUG(dbgs()<<"LIVE_IN: {");
221 for (unsigned i=0; i < BlockLiveness[*FI].LiveIn.size(); ++i)
222 DEBUG(dbgs()<<BlockLiveness[*FI].LiveIn.test(i)<<" ");
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");
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);
241 // Assign a serial number to this basic block.
242 BasicBlocks[*FI] = BasicBlockNumbering.size();
243 BasicBlockNumbering.push_back(*FI);
245 BlockLiveness[*FI].Begin.resize(NumSlot);
246 BlockLiveness[*FI].End.resize(NumSlot);
248 for (MachineBasicBlock::iterator BI = (*FI)->begin(), BE = (*FI)->end();
251 if (BI->getOpcode() != TargetOpcode::LIFETIME_START &&
252 BI->getOpcode() != TargetOpcode::LIFETIME_END)
255 Markers.push_back(BI);
257 bool IsStart = BI->getOpcode() == TargetOpcode::LIFETIME_START;
258 MachineOperand &MI = BI->getOperand(0);
259 unsigned Slot = MI.getIndex();
263 const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
265 DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<<
266 " with allocation: "<< Allocation->getName()<<"\n");
270 BlockLiveness[*FI].Begin.set(Slot);
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);
278 BlockLiveness[*FI].End.set(Slot);
284 // Update statistics.
285 NumMarkerSeen += MarkersFound;
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;
303 SmallPtrSet<MachineBasicBlock*, 8> NextBBSet;
305 for (SmallVector<MachineBasicBlock*, 8>::iterator
306 PI = BasicBlockNumbering.begin(), PE = BasicBlockNumbering.end();
309 MachineBasicBlock *BB = *PI;
310 if (!BBSet.count(BB)) continue;
312 BitVector LocalLiveIn;
313 BitVector LocalLiveOut;
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);
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);
329 LocalLiveIn |= LocalLiveOut;
330 LocalLiveOut |= LocalLiveIn;
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);
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
344 BitVector LocalEndBegin = BlockLiveness[BB].End;
345 LocalEndBegin &= BlockLiveness[BB].Begin;
346 LocalLiveIn |= LocalEndBegin;
347 LocalLiveOut |= LocalEndBegin;
349 if (LocalLiveIn.test(BlockLiveness[BB].LiveIn)) {
351 BlockLiveness[BB].LiveIn |= LocalLiveIn;
353 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
354 PE = BB->pred_end(); PI != PE; ++PI)
355 NextBBSet.insert(*PI);
358 if (LocalLiveOut.test(BlockLiveness[BB].LiveOut)) {
360 BlockLiveness[BB].LiveOut |= LocalLiveOut;
362 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
363 SE = BB->succ_end(); SI != SE; ++SI)
364 NextBBSet.insert(*SI);
372 void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
373 SmallVector<SlotIndex, 16> Starts;
374 SmallVector<SlotIndex, 16> Finishes;
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) {
381 Starts.resize(NumSlots);
383 Finishes.resize(NumSlots);
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)
392 assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
393 MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
394 "Invalid Lifetime marker");
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");
401 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
404 if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
405 Starts[Slot] = ThisIndex;
407 if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
408 Finishes[Slot] = ThisIndex;
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;
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);
426 for (unsigned i = 0; i < NumSlots; ++i) {
427 assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
428 if (!Starts[i].isValid())
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];
436 // We have a single consecutive region.
437 Intervals[i]->addRange(LiveRange(S, F, ValNum));
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));
450 bool StackColoring::removeAllMarkers() {
452 for (unsigned i = 0; i < Markers.size(); ++i) {
453 Markers[i]->eraseFromParent();
458 DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
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();
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;
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];
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");
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) {
498 // Skip lifetime markers. We'll remove them soon.
499 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
500 I->getOpcode() == TargetOpcode::LIFETIME_END)
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;
508 const Value *V = MMO->getValue();
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.
523 const AllocaInst *AI= cast<AllocaInst>(V);
524 if (!Allocas.count(AI))
527 MMO->setValue(Allocas[AI]);
531 // Update all of the machine instruction operands.
532 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
533 MachineOperand &MO = I->getOperand(i);
537 int FromSlot = MO.getIndex();
539 // Don't touch arguments.
543 // Only look at mapped slots.
544 if (!SlotRemap.count(FromSlot))
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.
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.");
566 // Fix the machine instructions.
567 int ToSlot = SlotRemap[FromSlot];
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");
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) {
584 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
585 I->getOpcode() == TargetOpcode::LIFETIME_END || I->isDebugValue())
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())
597 // Check all of the machine operands.
598 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
599 MachineOperand &MO = I->getOperand(i);
604 int Slot = MO.getIndex();
609 if (Intervals[Slot]->empty())
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");
625 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
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;
641 bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
642 DEBUG(dbgs() << "********** Stack Coloring **********\n"
643 << "********** Function: "
644 << ((const Value*)Func.getFunction())->getName() << '\n');
646 MFI = MF->getFrameInfo();
647 Indexes = &getAnalysis<SlotIndexes>();
648 BlockLiveness.clear();
650 BasicBlockNumbering.clear();
653 VNInfoAllocator.Reset();
655 unsigned NumSlots = MFI->getObjectIndexEnd();
657 // If there are no stack slots then there are no markers to remove.
661 SmallVector<int, 8> SortedSlots;
663 SortedSlots.reserve(NumSlots);
664 Intervals.reserve(NumSlots);
666 unsigned NumMarkers = collectMarkers(NumSlots);
668 unsigned TotalSize = 0;
669 DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
670 DEBUG(dbgs()<<"Slot structure:\n");
672 for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
673 DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
674 TotalSize += MFI->getObjectSize(i);
677 DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
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();
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);
693 // Calculate the liveness of each block.
694 calculateLocalLiveness();
696 // Propagate the liveness information.
697 calculateLiveIntervals(NumSlots);
699 // Search for allocas which are used outside of the declared lifetime
701 if (ProtectFromEscapedAllocas)
702 removeInvalidSlotRanges();
704 // Maps old slots to new slots.
705 DenseMap<int, int> SlotRemap;
706 unsigned RemovedSlots = 0;
707 unsigned ReducedSize = 0;
709 // Do not bother looking at empty intervals.
710 for (unsigned I = 0; I < NumSlots; ++I) {
711 if (Intervals[SortedSlots[I]]->empty())
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
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));
729 for (unsigned I = 0; I < NumSlots; ++I) {
730 if (SortedSlots[I] == -1)
733 for (unsigned J=I+1; J < NumSlots; ++J) {
734 if (SortedSlots[J] == -1)
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");
743 // Merge disjoint slots.
744 if (!First->overlaps(*Second)) {
746 First->MergeRangesInAsValue(*Second, First->getValNumInfo(0));
747 SlotRemap[SecondSlot] = FirstSlot;
749 DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
750 SecondSlot<<" together.\n");
751 unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
752 MFI->getObjectAlignment(SecondSlot));
754 assert(MFI->getObjectSize(FirstSlot) >=
755 MFI->getObjectSize(SecondSlot) &&
756 "Merging a small object into a larger one");
759 ReducedSize += MFI->getObjectSize(SecondSlot);
760 MFI->setObjectAlignment(FirstSlot, MaxAlignment);
761 MFI->RemoveStackObject(SecondSlot);
767 // Record statistics.
768 StackSpaceSaved += ReducedSize;
769 StackSlotMerged += RemovedSlots;
770 DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
771 ReducedSize<<" bytes\n");
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);
778 // Release the intervals.
779 for (unsigned I = 0; I < NumSlots; ++I) {
783 return removeAllMarkers();