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/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachineMemOperand.h"
45 #include "llvm/CodeGen/MachineModuleInfo.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/SlotIndexes.h"
48 #include "llvm/DebugInfo.h"
49 #include "llvm/Function.h"
50 #include "llvm/Instructions.h"
51 #include "llvm/MC/MCInstrItineraries.h"
52 #include "llvm/Module.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetInstrInfo.h"
57 #include "llvm/Target/TargetRegisterInfo.h"
62 DisableColoring("no-stack-coloring",
63 cl::init(false), cl::Hidden,
64 cl::desc("Disable stack coloring"));
66 /// The user may write code that uses allocas outside of the declared lifetime
67 /// zone. This can happen when the user returns a reference to a local
68 /// data-structure. We can detect these cases and decide not to optimize the
69 /// code. If this flag is enabled, we try to save the user.
71 ProtectFromEscapedAllocas("protect-from-escaped-allocas",
72 cl::init(false), cl::Hidden,
73 cl::desc("Do not optimize lifetime zones that are broken"));
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,
79 "Number of allocas that escaped the lifetime region");
81 //===----------------------------------------------------------------------===//
83 //===----------------------------------------------------------------------===//
86 /// StackColoring - A machine pass for merging disjoint stack allocations,
87 /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
88 class StackColoring : public MachineFunctionPass {
89 MachineFrameInfo *MFI;
92 /// A class representing liveness information for a single basic block.
93 /// Each bit in the BitVector represents the liveness property
94 /// for a different stack slot.
95 struct BlockLifetimeInfo {
96 /// Which slots BEGINs in each basic block.
98 /// Which slots ENDs in each basic block.
100 /// Which slots are marked as LIVE_IN, coming into each basic block.
102 /// Which slots are marked as LIVE_OUT, coming out of each basic block.
106 /// Maps active slots (per bit) for each basic block.
107 DenseMap<MachineBasicBlock*, BlockLifetimeInfo> BlockLiveness;
109 /// Maps serial numbers to basic blocks.
110 DenseMap<MachineBasicBlock*, int> BasicBlocks;
111 /// Maps basic blocks to a serial number.
112 SmallVector<MachineBasicBlock*, 8> BasicBlockNumbering;
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;
121 /// The list of lifetime markers found. These markers are to be removed
122 /// once the coloring is done.
123 SmallVector<MachineInstr*, 8> Markers;
125 /// SlotSizeSorter - A Sort utility for arranging stack slots according
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);
141 StackColoring() : MachineFunctionPass(ID) {
142 initializeStackColoringPass(*PassRegistry::getPassRegistry());
144 void getAnalysisUsage(AnalysisUsage &AU) const;
145 bool runOnMachineFunction(MachineFunction &MF);
151 /// Removes all of the lifetime marker instructions from the function.
152 /// \returns true if any markers were removed.
153 bool removeAllMarkers();
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);
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();
166 /// Construct the LiveIntervals for the slots.
167 void calculateLiveIntervals(unsigned NumSlots);
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);
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();
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);
185 } // end anonymous namespace
187 char StackColoring::ID = 0;
188 char &llvm::StackColoringID = StackColoring::ID;
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)
197 void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
198 AU.addRequired<MachineDominatorTree>();
199 AU.addPreserved<MachineDominatorTree>();
200 AU.addRequired<SlotIndexes>();
201 MachineFunctionPass::getAnalysisUsage(AU);
204 void StackColoring::dump() {
205 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
207 unsigned Num = BasicBlocks[*FI];
208 DEBUG(dbgs()<<"Inspecting block #"<<Num<<" ["<<FI->getName()<<"]\n");
210 DEBUG(dbgs()<<"BEGIN : {");
211 for (unsigned i=0; i < BlockLiveness[*FI].Begin.size(); ++i)
212 DEBUG(dbgs()<<BlockLiveness[*FI].Begin.test(i)<<" ");
213 DEBUG(dbgs()<<"}\n");
215 DEBUG(dbgs()<<"END : {");
216 for (unsigned i=0; i < BlockLiveness[*FI].End.size(); ++i)
217 DEBUG(dbgs()<<BlockLiveness[*FI].End.test(i)<<" ");
219 DEBUG(dbgs()<<"}\n");
221 DEBUG(dbgs()<<"LIVE_IN: {");
222 for (unsigned i=0; i < BlockLiveness[*FI].LiveIn.size(); ++i)
223 DEBUG(dbgs()<<BlockLiveness[*FI].LiveIn.test(i)<<" ");
225 DEBUG(dbgs()<<"}\n");
226 DEBUG(dbgs()<<"LIVEOUT: {");
227 for (unsigned i=0; i < BlockLiveness[*FI].LiveOut.size(); ++i)
228 DEBUG(dbgs()<<BlockLiveness[*FI].LiveOut.test(i)<<" ");
229 DEBUG(dbgs()<<"}\n");
233 unsigned StackColoring::collectMarkers(unsigned NumSlot) {
234 unsigned MarkersFound = 0;
235 // Scan the function to find all lifetime markers.
236 // NOTE: We use the a reverse-post-order iteration to ensure that we obtain a
237 // deterministic numbering, and because we'll need a post-order iteration
238 // later for solving the liveness dataflow problem.
239 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
242 // Assign a serial number to this basic block.
243 BasicBlocks[*FI] = BasicBlockNumbering.size();
244 BasicBlockNumbering.push_back(*FI);
246 BlockLiveness[*FI].Begin.resize(NumSlot);
247 BlockLiveness[*FI].End.resize(NumSlot);
249 for (MachineBasicBlock::iterator BI = (*FI)->begin(), BE = (*FI)->end();
252 if (BI->getOpcode() != TargetOpcode::LIFETIME_START &&
253 BI->getOpcode() != TargetOpcode::LIFETIME_END)
256 Markers.push_back(BI);
258 bool IsStart = BI->getOpcode() == TargetOpcode::LIFETIME_START;
259 MachineOperand &MI = BI->getOperand(0);
260 unsigned Slot = MI.getIndex();
264 const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
266 DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<<
267 " with allocation: "<< Allocation->getName()<<"\n");
271 BlockLiveness[*FI].Begin.set(Slot);
273 if (BlockLiveness[*FI].Begin.test(Slot)) {
274 // Allocas that start and end within a single block are handled
275 // specially when computing the LiveIntervals to avoid pessimizing
276 // the liveness propagation.
277 BlockLiveness[*FI].Begin.reset(Slot);
279 BlockLiveness[*FI].End.set(Slot);
285 // Update statistics.
286 NumMarkerSeen += MarkersFound;
290 void StackColoring::calculateLocalLiveness() {
291 // Perform a standard reverse dataflow computation to solve for
292 // global liveness. The BEGIN set here is equivalent to KILL in the standard
293 // formulation, and END is equivalent to GEN. The result of this computation
294 // is a map from blocks to bitvectors where the bitvectors represent which
295 // allocas are live in/out of that block.
296 SmallPtrSet<MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
297 BasicBlockNumbering.end());
298 unsigned NumSSMIters = 0;
304 SmallPtrSet<MachineBasicBlock*, 8> NextBBSet;
306 for (SmallVector<MachineBasicBlock*, 8>::iterator
307 PI = BasicBlockNumbering.begin(), PE = BasicBlockNumbering.end();
310 MachineBasicBlock *BB = *PI;
311 if (!BBSet.count(BB)) continue;
313 BitVector LocalLiveIn;
314 BitVector LocalLiveOut;
316 // Forward propagation from begins to ends.
317 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
318 PE = BB->pred_end(); PI != PE; ++PI)
319 LocalLiveIn |= BlockLiveness[*PI].LiveOut;
320 LocalLiveIn |= BlockLiveness[BB].End;
321 LocalLiveIn.reset(BlockLiveness[BB].Begin);
323 // Reverse propagation from ends to begins.
324 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
325 SE = BB->succ_end(); SI != SE; ++SI)
326 LocalLiveOut |= BlockLiveness[*SI].LiveIn;
327 LocalLiveOut |= BlockLiveness[BB].Begin;
328 LocalLiveOut.reset(BlockLiveness[BB].End);
330 LocalLiveIn |= LocalLiveOut;
331 LocalLiveOut |= LocalLiveIn;
333 // After adopting the live bits, we need to turn-off the bits which
334 // are de-activated in this block.
335 LocalLiveOut.reset(BlockLiveness[BB].End);
336 LocalLiveIn.reset(BlockLiveness[BB].Begin);
338 // If we have both BEGIN and END markers in the same basic block then
339 // we know that the BEGIN marker comes after the END, because we already
340 // handle the case where the BEGIN comes before the END when collecting
341 // the markers (and building the BEGIN/END vectore).
342 // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
343 // BEGIN and END because it means that the value lives before and after
345 BitVector LocalEndBegin = BlockLiveness[BB].End;
346 LocalEndBegin &= BlockLiveness[BB].Begin;
347 LocalLiveIn |= LocalEndBegin;
348 LocalLiveOut |= LocalEndBegin;
350 if (LocalLiveIn.test(BlockLiveness[BB].LiveIn)) {
352 BlockLiveness[BB].LiveIn |= LocalLiveIn;
354 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
355 PE = BB->pred_end(); PI != PE; ++PI)
356 NextBBSet.insert(*PI);
359 if (LocalLiveOut.test(BlockLiveness[BB].LiveOut)) {
361 BlockLiveness[BB].LiveOut |= LocalLiveOut;
363 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
364 SE = BB->succ_end(); SI != SE; ++SI)
365 NextBBSet.insert(*SI);
373 void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
374 SmallVector<SlotIndex, 16> Starts;
375 SmallVector<SlotIndex, 16> Finishes;
377 // For each block, find which slots are active within this block
378 // and update the live intervals.
379 for (MachineFunction::iterator MBB = MF->begin(), MBBe = MF->end();
380 MBB != MBBe; ++MBB) {
382 Starts.resize(NumSlots);
384 Finishes.resize(NumSlots);
386 // Create the interval for the basic blocks with lifetime markers in them.
387 for (SmallVector<MachineInstr*, 8>::iterator it = Markers.begin(),
388 e = Markers.end(); it != e; ++it) {
389 MachineInstr *MI = *it;
390 if (MI->getParent() != MBB)
393 assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
394 MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
395 "Invalid Lifetime marker");
397 bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
398 MachineOperand &Mo = MI->getOperand(0);
399 int Slot = Mo.getIndex();
400 assert(Slot >= 0 && "Invalid slot");
402 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
405 if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
406 Starts[Slot] = ThisIndex;
408 if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
409 Finishes[Slot] = ThisIndex;
413 // Create the interval of the blocks that we previously found to be 'alive'.
414 BitVector Alive = BlockLiveness[MBB].LiveIn;
415 Alive |= BlockLiveness[MBB].LiveOut;
418 for (int pos = Alive.find_first(); pos != -1;
419 pos = Alive.find_next(pos)) {
420 if (!Starts[pos].isValid())
421 Starts[pos] = Indexes->getMBBStartIdx(MBB);
422 if (!Finishes[pos].isValid())
423 Finishes[pos] = Indexes->getMBBEndIdx(MBB);
427 for (unsigned i = 0; i < NumSlots; ++i) {
428 assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
429 if (!Starts[i].isValid())
432 assert(Starts[i] && Finishes[i] && "Invalid interval");
433 VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
434 SlotIndex S = Starts[i];
435 SlotIndex F = Finishes[i];
437 // We have a single consecutive region.
438 Intervals[i]->addRange(LiveRange(S, F, ValNum));
440 // We have two non consecutive regions. This happens when
441 // LIFETIME_START appears after the LIFETIME_END marker.
442 SlotIndex NewStart = Indexes->getMBBStartIdx(MBB);
443 SlotIndex NewFin = Indexes->getMBBEndIdx(MBB);
444 Intervals[i]->addRange(LiveRange(NewStart, F, ValNum));
445 Intervals[i]->addRange(LiveRange(S, NewFin, ValNum));
451 bool StackColoring::removeAllMarkers() {
453 for (unsigned i = 0; i < Markers.size(); ++i) {
454 Markers[i]->eraseFromParent();
459 DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
463 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
464 unsigned FixedInstr = 0;
465 unsigned FixedMemOp = 0;
466 unsigned FixedDbg = 0;
467 MachineModuleInfo *MMI = &MF->getMMI();
469 // Remap debug information that refers to stack slots.
470 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
471 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
472 VE = VMap.end(); VI != VE; ++VI) {
473 const MDNode *Var = VI->first;
475 std::pair<unsigned, DebugLoc> &VP = VI->second;
476 if (SlotRemap.count(VP.first)) {
477 DEBUG(dbgs()<<"Remapping debug info for ["<<Var->getName()<<"].\n");
478 VP.first = SlotRemap[VP.first];
483 // Keep a list of *allocas* which need to be remapped.
484 DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
485 for (DenseMap<int, int>::iterator it = SlotRemap.begin(),
486 e = SlotRemap.end(); it != e; ++it) {
487 const AllocaInst *From = MFI->getObjectAllocation(it->first);
488 const AllocaInst *To = MFI->getObjectAllocation(it->second);
489 assert(To && From && "Invalid allocation object");
493 // Remap all instructions to the new stack slots.
494 MachineFunction::iterator BB, BBE;
495 MachineBasicBlock::iterator I, IE;
496 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
497 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
499 // Skip lifetime markers. We'll remove them soon.
500 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
501 I->getOpcode() == TargetOpcode::LIFETIME_END)
504 // Update the MachineMemOperand to use the new alloca.
505 for (MachineInstr::mmo_iterator MM = I->memoperands_begin(),
506 E = I->memoperands_end(); MM != E; ++MM) {
507 MachineMemOperand *MMO = *MM;
509 const Value *V = MMO->getValue();
514 // Climb up and find the original alloca.
515 V = GetUnderlyingObject(V);
516 // If we did not find one, or if the one that we found is not in our
517 // map, then move on.
518 if (!V || !isa<AllocaInst>(V)) {
519 // Clear mem operand since we don't know for sure that it doesn't
520 // alias a merged alloca.
524 const AllocaInst *AI= cast<AllocaInst>(V);
525 if (!Allocas.count(AI))
528 MMO->setValue(Allocas[AI]);
532 // Update all of the machine instruction operands.
533 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
534 MachineOperand &MO = I->getOperand(i);
538 int FromSlot = MO.getIndex();
540 // Don't touch arguments.
544 // Only look at mapped slots.
545 if (!SlotRemap.count(FromSlot))
548 // In a debug build, check that the instruction that we are modifying is
549 // inside the expected live range. If the instruction is not inside
550 // the calculated range then it means that the alloca usage moved
551 // outside of the lifetime markers, or that the user has a bug.
552 // NOTE: Alloca address calculations which happen outside the lifetime
553 // zone are are okay, despite the fact that we don't have a good way
554 // for validating all of the usages of the calculation.
556 bool TouchesMemory = I->mayLoad() || I->mayStore();
557 // If we *don't* protect the user from escaped allocas, don't bother
558 // validating the instructions.
559 if (!I->isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) {
560 SlotIndex Index = Indexes->getInstructionIndex(I);
561 LiveInterval *Interval = Intervals[FromSlot];
562 assert(Interval->find(Index) != Interval->end() &&
563 "Found instruction usage outside of live range.");
567 // Fix the machine instructions.
568 int ToSlot = SlotRemap[FromSlot];
574 DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
575 DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
576 DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
579 void StackColoring::removeInvalidSlotRanges() {
580 MachineFunction::iterator BB, BBE;
581 MachineBasicBlock::iterator I, IE;
582 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
583 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
585 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
586 I->getOpcode() == TargetOpcode::LIFETIME_END || I->isDebugValue())
589 // Some intervals are suspicious! In some cases we find address
590 // calculations outside of the lifetime zone, but not actual memory
591 // read or write. Memory accesses outside of the lifetime zone are a clear
592 // violation, but address calculations are okay. This can happen when
593 // GEPs are hoisted outside of the lifetime zone.
594 // So, in here we only check instructions which can read or write memory.
595 if (!I->mayLoad() && !I->mayStore())
598 // Check all of the machine operands.
599 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
600 MachineOperand &MO = I->getOperand(i);
605 int Slot = MO.getIndex();
610 if (Intervals[Slot]->empty())
613 // Check that the used slot is inside the calculated lifetime range.
614 // If it is not, warn about it and invalidate the range.
615 LiveInterval *Interval = Intervals[Slot];
616 SlotIndex Index = Indexes->getInstructionIndex(I);
617 if (Interval->find(Index) == Interval->end()) {
618 Intervals[Slot]->clear();
619 DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
626 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
628 // Expunge slot remap map.
629 for (unsigned i=0; i < NumSlots; ++i) {
630 // If we are remapping i
631 if (SlotRemap.count(i)) {
632 int Target = SlotRemap[i];
633 // As long as our target is mapped to something else, follow it.
634 while (SlotRemap.count(Target)) {
635 Target = SlotRemap[Target];
636 SlotRemap[i] = Target;
642 bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
643 DEBUG(dbgs() << "********** Stack Coloring **********\n"
644 << "********** Function: "
645 << ((const Value*)Func.getFunction())->getName() << '\n');
647 MFI = MF->getFrameInfo();
648 Indexes = &getAnalysis<SlotIndexes>();
649 BlockLiveness.clear();
651 BasicBlockNumbering.clear();
654 VNInfoAllocator.Reset();
656 unsigned NumSlots = MFI->getObjectIndexEnd();
658 // If there are no stack slots then there are no markers to remove.
662 SmallVector<int, 8> SortedSlots;
664 SortedSlots.reserve(NumSlots);
665 Intervals.reserve(NumSlots);
667 unsigned NumMarkers = collectMarkers(NumSlots);
669 unsigned TotalSize = 0;
670 DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
671 DEBUG(dbgs()<<"Slot structure:\n");
673 for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
674 DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
675 TotalSize += MFI->getObjectSize(i);
678 DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
680 // Don't continue because there are not enough lifetime markers, or the
681 // stack is too small, or we are told not to optimize the slots.
682 if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
683 DEBUG(dbgs()<<"Will not try to merge slots.\n");
684 return removeAllMarkers();
687 for (unsigned i=0; i < NumSlots; ++i) {
688 LiveInterval *LI = new LiveInterval(i, 0);
689 Intervals.push_back(LI);
690 LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
691 SortedSlots.push_back(i);
694 // Calculate the liveness of each block.
695 calculateLocalLiveness();
697 // Propagate the liveness information.
698 calculateLiveIntervals(NumSlots);
700 // Search for allocas which are used outside of the declared lifetime
702 if (ProtectFromEscapedAllocas)
703 removeInvalidSlotRanges();
705 // Maps old slots to new slots.
706 DenseMap<int, int> SlotRemap;
707 unsigned RemovedSlots = 0;
708 unsigned ReducedSize = 0;
710 // Do not bother looking at empty intervals.
711 for (unsigned I = 0; I < NumSlots; ++I) {
712 if (Intervals[SortedSlots[I]]->empty())
716 // This is a simple greedy algorithm for merging allocas. First, sort the
717 // slots, placing the largest slots first. Next, perform an n^2 scan and look
718 // for disjoint slots. When you find disjoint slots, merge the samller one
719 // into the bigger one and update the live interval. Remove the small alloca
722 // Sort the slots according to their size. Place unused slots at the end.
723 // Use stable sort to guarantee deterministic code generation.
724 std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
725 SlotSizeSorter(MFI));
730 for (unsigned I = 0; I < NumSlots; ++I) {
731 if (SortedSlots[I] == -1)
734 for (unsigned J=I+1; J < NumSlots; ++J) {
735 if (SortedSlots[J] == -1)
738 int FirstSlot = SortedSlots[I];
739 int SecondSlot = SortedSlots[J];
740 LiveInterval *First = Intervals[FirstSlot];
741 LiveInterval *Second = Intervals[SecondSlot];
742 assert (!First->empty() && !Second->empty() && "Found an empty range");
744 // Merge disjoint slots.
745 if (!First->overlaps(*Second)) {
747 First->MergeRangesInAsValue(*Second, First->getValNumInfo(0));
748 SlotRemap[SecondSlot] = FirstSlot;
750 DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
751 SecondSlot<<" together.\n");
752 unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
753 MFI->getObjectAlignment(SecondSlot));
755 assert(MFI->getObjectSize(FirstSlot) >=
756 MFI->getObjectSize(SecondSlot) &&
757 "Merging a small object into a larger one");
760 ReducedSize += MFI->getObjectSize(SecondSlot);
761 MFI->setObjectAlignment(FirstSlot, MaxAlignment);
762 MFI->RemoveStackObject(SecondSlot);
768 // Record statistics.
769 StackSpaceSaved += ReducedSize;
770 StackSlotMerged += RemovedSlots;
771 DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
772 ReducedSize<<" bytes\n");
774 // Scan the entire function and update all machine operands that use frame
775 // indices to use the remapped frame index.
776 expungeSlotMap(SlotRemap, NumSlots);
777 remapInstructions(SlotRemap);
779 // Release the intervals.
780 for (unsigned I = 0; I < NumSlots; ++I) {
784 return removeAllMarkers();