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 "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/PostOrderIterator.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SparseSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/Dominators.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/CodeGen/LiveInterval.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
38 #include "llvm/CodeGen/MachineDominators.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunctionPass.h"
41 #include "llvm/CodeGen/MachineLoopInfo.h"
42 #include "llvm/CodeGen/MachineMemOperand.h"
43 #include "llvm/CodeGen/MachineModuleInfo.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/CodeGen/SlotIndexes.h"
46 #include "llvm/DebugInfo.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/MC/MCInstrItineraries.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetInstrInfo.h"
55 #include "llvm/Target/TargetRegisterInfo.h"
60 DisableColoring("no-stack-coloring",
61 cl::init(false), cl::Hidden,
62 cl::desc("Disable stack coloring"));
64 /// The user may write code that uses allocas outside of the declared lifetime
65 /// zone. This can happen when the user returns a reference to a local
66 /// data-structure. We can detect these cases and decide not to optimize the
67 /// code. If this flag is enabled, we try to save the user.
69 ProtectFromEscapedAllocas("protect-from-escaped-allocas",
70 cl::init(false), cl::Hidden,
71 cl::desc("Do not optimize lifetime zones that are broken"));
73 STATISTIC(NumMarkerSeen, "Number of lifetime markers found.");
74 STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
75 STATISTIC(StackSlotMerged, "Number of stack slot merged.");
76 STATISTIC(EscapedAllocas,
77 "Number of allocas that escaped the lifetime region");
79 //===----------------------------------------------------------------------===//
81 //===----------------------------------------------------------------------===//
84 /// StackColoring - A machine pass for merging disjoint stack allocations,
85 /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
86 class StackColoring : public MachineFunctionPass {
87 MachineFrameInfo *MFI;
90 /// A class representing liveness information for a single basic block.
91 /// Each bit in the BitVector represents the liveness property
92 /// for a different stack slot.
93 struct BlockLifetimeInfo {
94 /// Which slots BEGINs in each basic block.
96 /// Which slots ENDs in each basic block.
98 /// Which slots are marked as LIVE_IN, coming into each basic block.
100 /// Which slots are marked as LIVE_OUT, coming out of each basic block.
104 /// Maps active slots (per bit) for each basic block.
105 typedef DenseMap<const MachineBasicBlock*, BlockLifetimeInfo> LivenessMap;
106 LivenessMap BlockLiveness;
108 /// Maps serial numbers to basic blocks.
109 DenseMap<const MachineBasicBlock*, int> BasicBlocks;
110 /// Maps basic blocks to a serial number.
111 SmallVector<const 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() const {
204 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
206 DEBUG(dbgs()<<"Inspecting block #"<<BasicBlocks.lookup(*FI)<<
207 " ["<<FI->getName()<<"]\n");
209 LivenessMap::const_iterator BI = BlockLiveness.find(*FI);
210 assert(BI != BlockLiveness.end() && "Block not found");
211 const BlockLifetimeInfo &BlockInfo = BI->second;
213 DEBUG(dbgs()<<"BEGIN : {");
214 for (unsigned i=0; i < BlockInfo.Begin.size(); ++i)
215 DEBUG(dbgs()<<BlockInfo.Begin.test(i)<<" ");
216 DEBUG(dbgs()<<"}\n");
218 DEBUG(dbgs()<<"END : {");
219 for (unsigned i=0; i < BlockInfo.End.size(); ++i)
220 DEBUG(dbgs()<<BlockInfo.End.test(i)<<" ");
222 DEBUG(dbgs()<<"}\n");
224 DEBUG(dbgs()<<"LIVE_IN: {");
225 for (unsigned i=0; i < BlockInfo.LiveIn.size(); ++i)
226 DEBUG(dbgs()<<BlockInfo.LiveIn.test(i)<<" ");
228 DEBUG(dbgs()<<"}\n");
229 DEBUG(dbgs()<<"LIVEOUT: {");
230 for (unsigned i=0; i < BlockInfo.LiveOut.size(); ++i)
231 DEBUG(dbgs()<<BlockInfo.LiveOut.test(i)<<" ");
232 DEBUG(dbgs()<<"}\n");
236 unsigned StackColoring::collectMarkers(unsigned NumSlot) {
237 unsigned MarkersFound = 0;
238 // Scan the function to find all lifetime markers.
239 // NOTE: We use the a reverse-post-order iteration to ensure that we obtain a
240 // deterministic numbering, and because we'll need a post-order iteration
241 // later for solving the liveness dataflow problem.
242 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
245 // Assign a serial number to this basic block.
246 BasicBlocks[*FI] = BasicBlockNumbering.size();
247 BasicBlockNumbering.push_back(*FI);
249 // Keep a reference to avoid repeated lookups.
250 BlockLifetimeInfo &BlockInfo = BlockLiveness[*FI];
252 BlockInfo.Begin.resize(NumSlot);
253 BlockInfo.End.resize(NumSlot);
255 for (MachineBasicBlock::iterator BI = (*FI)->begin(), BE = (*FI)->end();
258 if (BI->getOpcode() != TargetOpcode::LIFETIME_START &&
259 BI->getOpcode() != TargetOpcode::LIFETIME_END)
262 Markers.push_back(BI);
264 bool IsStart = BI->getOpcode() == TargetOpcode::LIFETIME_START;
265 const MachineOperand &MI = BI->getOperand(0);
266 unsigned Slot = MI.getIndex();
270 const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
272 DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<<
273 " with allocation: "<< Allocation->getName()<<"\n");
277 BlockInfo.Begin.set(Slot);
279 if (BlockInfo.Begin.test(Slot)) {
280 // Allocas that start and end within a single block are handled
281 // specially when computing the LiveIntervals to avoid pessimizing
282 // the liveness propagation.
283 BlockInfo.Begin.reset(Slot);
285 BlockInfo.End.set(Slot);
291 // Update statistics.
292 NumMarkerSeen += MarkersFound;
296 void StackColoring::calculateLocalLiveness() {
297 // Perform a standard reverse dataflow computation to solve for
298 // global liveness. The BEGIN set here is equivalent to KILL in the standard
299 // formulation, and END is equivalent to GEN. The result of this computation
300 // is a map from blocks to bitvectors where the bitvectors represent which
301 // allocas are live in/out of that block.
302 SmallPtrSet<const MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
303 BasicBlockNumbering.end());
304 unsigned NumSSMIters = 0;
310 SmallPtrSet<const MachineBasicBlock*, 8> NextBBSet;
312 for (SmallVector<const MachineBasicBlock*, 8>::iterator
313 PI = BasicBlockNumbering.begin(), PE = BasicBlockNumbering.end();
316 const MachineBasicBlock *BB = *PI;
317 if (!BBSet.count(BB)) continue;
319 // Use an iterator to avoid repeated lookups.
320 LivenessMap::iterator BI = BlockLiveness.find(BB);
321 assert(BI != BlockLiveness.end() && "Block not found");
322 BlockLifetimeInfo &BlockInfo = BI->second;
324 BitVector LocalLiveIn;
325 BitVector LocalLiveOut;
327 // Forward propagation from begins to ends.
328 for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
329 PE = BB->pred_end(); PI != PE; ++PI) {
330 LivenessMap::const_iterator I = BlockLiveness.find(*PI);
331 assert(I != BlockLiveness.end() && "Predecessor not found");
332 LocalLiveIn |= I->second.LiveOut;
334 LocalLiveIn |= BlockInfo.End;
335 LocalLiveIn.reset(BlockInfo.Begin);
337 // Reverse propagation from ends to begins.
338 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
339 SE = BB->succ_end(); SI != SE; ++SI) {
340 LivenessMap::const_iterator I = BlockLiveness.find(*SI);
341 assert(I != BlockLiveness.end() && "Successor not found");
342 LocalLiveOut |= I->second.LiveIn;
344 LocalLiveOut |= BlockInfo.Begin;
345 LocalLiveOut.reset(BlockInfo.End);
347 LocalLiveIn |= LocalLiveOut;
348 LocalLiveOut |= LocalLiveIn;
350 // After adopting the live bits, we need to turn-off the bits which
351 // are de-activated in this block.
352 LocalLiveOut.reset(BlockInfo.End);
353 LocalLiveIn.reset(BlockInfo.Begin);
355 // If we have both BEGIN and END markers in the same basic block then
356 // we know that the BEGIN marker comes after the END, because we already
357 // handle the case where the BEGIN comes before the END when collecting
358 // the markers (and building the BEGIN/END vectore).
359 // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
360 // BEGIN and END because it means that the value lives before and after
362 BitVector LocalEndBegin = BlockInfo.End;
363 LocalEndBegin &= BlockInfo.Begin;
364 LocalLiveIn |= LocalEndBegin;
365 LocalLiveOut |= LocalEndBegin;
367 if (LocalLiveIn.test(BlockInfo.LiveIn)) {
369 BlockInfo.LiveIn |= LocalLiveIn;
371 for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
372 PE = BB->pred_end(); PI != PE; ++PI)
373 NextBBSet.insert(*PI);
376 if (LocalLiveOut.test(BlockInfo.LiveOut)) {
378 BlockInfo.LiveOut |= LocalLiveOut;
380 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
381 SE = BB->succ_end(); SI != SE; ++SI)
382 NextBBSet.insert(*SI);
390 void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
391 SmallVector<SlotIndex, 16> Starts;
392 SmallVector<SlotIndex, 16> Finishes;
394 // For each block, find which slots are active within this block
395 // and update the live intervals.
396 for (MachineFunction::iterator MBB = MF->begin(), MBBe = MF->end();
397 MBB != MBBe; ++MBB) {
399 Starts.resize(NumSlots);
401 Finishes.resize(NumSlots);
403 // Create the interval for the basic blocks with lifetime markers in them.
404 for (SmallVectorImpl<MachineInstr*>::const_iterator it = Markers.begin(),
405 e = Markers.end(); it != e; ++it) {
406 const MachineInstr *MI = *it;
407 if (MI->getParent() != MBB)
410 assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
411 MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
412 "Invalid Lifetime marker");
414 bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
415 const MachineOperand &Mo = MI->getOperand(0);
416 int Slot = Mo.getIndex();
417 assert(Slot >= 0 && "Invalid slot");
419 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
422 if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
423 Starts[Slot] = ThisIndex;
425 if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
426 Finishes[Slot] = ThisIndex;
430 // Create the interval of the blocks that we previously found to be 'alive'.
431 BitVector Alive = BlockLiveness[MBB].LiveIn;
432 Alive |= BlockLiveness[MBB].LiveOut;
435 for (int pos = Alive.find_first(); pos != -1;
436 pos = Alive.find_next(pos)) {
437 if (!Starts[pos].isValid())
438 Starts[pos] = Indexes->getMBBStartIdx(MBB);
439 if (!Finishes[pos].isValid())
440 Finishes[pos] = Indexes->getMBBEndIdx(MBB);
444 for (unsigned i = 0; i < NumSlots; ++i) {
445 assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
446 if (!Starts[i].isValid())
449 assert(Starts[i] && Finishes[i] && "Invalid interval");
450 VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
451 SlotIndex S = Starts[i];
452 SlotIndex F = Finishes[i];
454 // We have a single consecutive region.
455 Intervals[i]->addRange(LiveRange(S, F, ValNum));
457 // We have two non consecutive regions. This happens when
458 // LIFETIME_START appears after the LIFETIME_END marker.
459 SlotIndex NewStart = Indexes->getMBBStartIdx(MBB);
460 SlotIndex NewFin = Indexes->getMBBEndIdx(MBB);
461 Intervals[i]->addRange(LiveRange(NewStart, F, ValNum));
462 Intervals[i]->addRange(LiveRange(S, NewFin, ValNum));
468 bool StackColoring::removeAllMarkers() {
470 for (unsigned i = 0; i < Markers.size(); ++i) {
471 Markers[i]->eraseFromParent();
476 DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
480 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
481 unsigned FixedInstr = 0;
482 unsigned FixedMemOp = 0;
483 unsigned FixedDbg = 0;
484 MachineModuleInfo *MMI = &MF->getMMI();
486 // Remap debug information that refers to stack slots.
487 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
488 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
489 VE = VMap.end(); VI != VE; ++VI) {
490 const MDNode *Var = VI->first;
492 std::pair<unsigned, DebugLoc> &VP = VI->second;
493 if (SlotRemap.count(VP.first)) {
494 DEBUG(dbgs()<<"Remapping debug info for ["<<Var->getName()<<"].\n");
495 VP.first = SlotRemap[VP.first];
500 // Keep a list of *allocas* which need to be remapped.
501 DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
502 for (DenseMap<int, int>::const_iterator it = SlotRemap.begin(),
503 e = SlotRemap.end(); it != e; ++it) {
504 const AllocaInst *From = MFI->getObjectAllocation(it->first);
505 const AllocaInst *To = MFI->getObjectAllocation(it->second);
506 assert(To && From && "Invalid allocation object");
510 // Remap all instructions to the new stack slots.
511 MachineFunction::iterator BB, BBE;
512 MachineBasicBlock::iterator I, IE;
513 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
514 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
516 // Skip lifetime markers. We'll remove them soon.
517 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
518 I->getOpcode() == TargetOpcode::LIFETIME_END)
521 // Update the MachineMemOperand to use the new alloca.
522 for (MachineInstr::mmo_iterator MM = I->memoperands_begin(),
523 E = I->memoperands_end(); MM != E; ++MM) {
524 MachineMemOperand *MMO = *MM;
526 const Value *V = MMO->getValue();
531 // Climb up and find the original alloca.
532 V = GetUnderlyingObject(V);
533 // If we did not find one, or if the one that we found is not in our
534 // map, then move on.
535 if (!V || !isa<AllocaInst>(V)) {
536 // Clear mem operand since we don't know for sure that it doesn't
537 // alias a merged alloca.
541 const AllocaInst *AI= cast<AllocaInst>(V);
542 if (!Allocas.count(AI))
545 MMO->setValue(Allocas[AI]);
549 // Update all of the machine instruction operands.
550 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
551 MachineOperand &MO = I->getOperand(i);
555 int FromSlot = MO.getIndex();
557 // Don't touch arguments.
561 // Only look at mapped slots.
562 if (!SlotRemap.count(FromSlot))
565 // In a debug build, check that the instruction that we are modifying is
566 // inside the expected live range. If the instruction is not inside
567 // the calculated range then it means that the alloca usage moved
568 // outside of the lifetime markers, or that the user has a bug.
569 // NOTE: Alloca address calculations which happen outside the lifetime
570 // zone are are okay, despite the fact that we don't have a good way
571 // for validating all of the usages of the calculation.
573 bool TouchesMemory = I->mayLoad() || I->mayStore();
574 // If we *don't* protect the user from escaped allocas, don't bother
575 // validating the instructions.
576 if (!I->isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) {
577 SlotIndex Index = Indexes->getInstructionIndex(I);
578 LiveInterval *Interval = Intervals[FromSlot];
579 assert(Interval->find(Index) != Interval->end() &&
580 "Found instruction usage outside of live range.");
584 // Fix the machine instructions.
585 int ToSlot = SlotRemap[FromSlot];
591 DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
592 DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
593 DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
596 void StackColoring::removeInvalidSlotRanges() {
597 MachineFunction::const_iterator BB, BBE;
598 MachineBasicBlock::const_iterator I, IE;
599 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
600 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
602 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
603 I->getOpcode() == TargetOpcode::LIFETIME_END || I->isDebugValue())
606 // Some intervals are suspicious! In some cases we find address
607 // calculations outside of the lifetime zone, but not actual memory
608 // read or write. Memory accesses outside of the lifetime zone are a clear
609 // violation, but address calculations are okay. This can happen when
610 // GEPs are hoisted outside of the lifetime zone.
611 // So, in here we only check instructions which can read or write memory.
612 if (!I->mayLoad() && !I->mayStore())
615 // Check all of the machine operands.
616 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
617 const MachineOperand &MO = I->getOperand(i);
622 int Slot = MO.getIndex();
627 if (Intervals[Slot]->empty())
630 // Check that the used slot is inside the calculated lifetime range.
631 // If it is not, warn about it and invalidate the range.
632 LiveInterval *Interval = Intervals[Slot];
633 SlotIndex Index = Indexes->getInstructionIndex(I);
634 if (Interval->find(Index) == Interval->end()) {
635 Intervals[Slot]->clear();
636 DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
643 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
645 // Expunge slot remap map.
646 for (unsigned i=0; i < NumSlots; ++i) {
647 // If we are remapping i
648 if (SlotRemap.count(i)) {
649 int Target = SlotRemap[i];
650 // As long as our target is mapped to something else, follow it.
651 while (SlotRemap.count(Target)) {
652 Target = SlotRemap[Target];
653 SlotRemap[i] = Target;
659 bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
660 DEBUG(dbgs() << "********** Stack Coloring **********\n"
661 << "********** Function: "
662 << ((const Value*)Func.getFunction())->getName() << '\n');
664 MFI = MF->getFrameInfo();
665 Indexes = &getAnalysis<SlotIndexes>();
666 BlockLiveness.clear();
668 BasicBlockNumbering.clear();
671 VNInfoAllocator.Reset();
673 unsigned NumSlots = MFI->getObjectIndexEnd();
675 // If there are no stack slots then there are no markers to remove.
679 SmallVector<int, 8> SortedSlots;
681 SortedSlots.reserve(NumSlots);
682 Intervals.reserve(NumSlots);
684 unsigned NumMarkers = collectMarkers(NumSlots);
686 unsigned TotalSize = 0;
687 DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
688 DEBUG(dbgs()<<"Slot structure:\n");
690 for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
691 DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
692 TotalSize += MFI->getObjectSize(i);
695 DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
697 // Don't continue because there are not enough lifetime markers, or the
698 // stack is too small, or we are told not to optimize the slots.
699 if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
700 DEBUG(dbgs()<<"Will not try to merge slots.\n");
701 return removeAllMarkers();
704 for (unsigned i=0; i < NumSlots; ++i) {
705 LiveInterval *LI = new LiveInterval(i, 0);
706 Intervals.push_back(LI);
707 LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
708 SortedSlots.push_back(i);
711 // Calculate the liveness of each block.
712 calculateLocalLiveness();
714 // Propagate the liveness information.
715 calculateLiveIntervals(NumSlots);
717 // Search for allocas which are used outside of the declared lifetime
719 if (ProtectFromEscapedAllocas)
720 removeInvalidSlotRanges();
722 // Maps old slots to new slots.
723 DenseMap<int, int> SlotRemap;
724 unsigned RemovedSlots = 0;
725 unsigned ReducedSize = 0;
727 // Do not bother looking at empty intervals.
728 for (unsigned I = 0; I < NumSlots; ++I) {
729 if (Intervals[SortedSlots[I]]->empty())
733 // This is a simple greedy algorithm for merging allocas. First, sort the
734 // slots, placing the largest slots first. Next, perform an n^2 scan and look
735 // for disjoint slots. When you find disjoint slots, merge the samller one
736 // into the bigger one and update the live interval. Remove the small alloca
739 // Sort the slots according to their size. Place unused slots at the end.
740 // Use stable sort to guarantee deterministic code generation.
741 std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
742 SlotSizeSorter(MFI));
747 for (unsigned I = 0; I < NumSlots; ++I) {
748 if (SortedSlots[I] == -1)
751 for (unsigned J=I+1; J < NumSlots; ++J) {
752 if (SortedSlots[J] == -1)
755 int FirstSlot = SortedSlots[I];
756 int SecondSlot = SortedSlots[J];
757 LiveInterval *First = Intervals[FirstSlot];
758 LiveInterval *Second = Intervals[SecondSlot];
759 assert (!First->empty() && !Second->empty() && "Found an empty range");
761 // Merge disjoint slots.
762 if (!First->overlaps(*Second)) {
764 First->MergeRangesInAsValue(*Second, First->getValNumInfo(0));
765 SlotRemap[SecondSlot] = FirstSlot;
767 DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
768 SecondSlot<<" together.\n");
769 unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
770 MFI->getObjectAlignment(SecondSlot));
772 assert(MFI->getObjectSize(FirstSlot) >=
773 MFI->getObjectSize(SecondSlot) &&
774 "Merging a small object into a larger one");
777 ReducedSize += MFI->getObjectSize(SecondSlot);
778 MFI->setObjectAlignment(FirstSlot, MaxAlignment);
779 MFI->RemoveStackObject(SecondSlot);
785 // Record statistics.
786 StackSpaceSaved += ReducedSize;
787 StackSlotMerged += RemovedSlots;
788 DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
789 ReducedSize<<" bytes\n");
791 // Scan the entire function and update all machine operands that use frame
792 // indices to use the remapped frame index.
793 expungeSlotMap(SlotRemap, NumSlots);
794 remapInstructions(SlotRemap);
796 // Release the intervals.
797 for (unsigned I = 0; I < NumSlots; ++I) {
801 return removeAllMarkers();