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/ValueTracking.h"
34 #include "llvm/CodeGen/LiveInterval.h"
35 #include "llvm/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
37 #include "llvm/CodeGen/MachineDominators.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunctionPass.h"
40 #include "llvm/CodeGen/MachineLoopInfo.h"
41 #include "llvm/CodeGen/MachineMemOperand.h"
42 #include "llvm/CodeGen/MachineModuleInfo.h"
43 #include "llvm/CodeGen/MachineRegisterInfo.h"
44 #include "llvm/CodeGen/PseudoSourceValue.h"
45 #include "llvm/CodeGen/SlotIndexes.h"
46 #include "llvm/CodeGen/StackProtector.h"
47 #include "llvm/DebugInfo.h"
48 #include "llvm/IR/Dominators.h"
49 #include "llvm/IR/Function.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/MC/MCInstrItineraries.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 "
76 STATISTIC(NumMarkerSeen, "Number of lifetime markers found.");
77 STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
78 STATISTIC(StackSlotMerged, "Number of stack slot merged.");
79 STATISTIC(EscapedAllocas, "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 typedef DenseMap<const MachineBasicBlock*, BlockLifetimeInfo> LivenessMap;
108 LivenessMap BlockLiveness;
110 /// Maps serial numbers to basic blocks.
111 DenseMap<const MachineBasicBlock*, int> BasicBlocks;
112 /// Maps basic blocks to a serial number.
113 SmallVector<const MachineBasicBlock*, 8> BasicBlockNumbering;
115 /// Maps liveness intervals for each slot.
116 SmallVector<LiveInterval*, 16> Intervals;
117 /// VNInfo is used for the construction of LiveIntervals.
118 VNInfo::Allocator VNInfoAllocator;
119 /// SlotIndex analysis object.
120 SlotIndexes *Indexes;
121 /// The stack protector object.
124 /// The list of lifetime markers found. These markers are to be removed
125 /// once the coloring is done.
126 SmallVector<MachineInstr*, 8> Markers;
128 /// SlotSizeSorter - A Sort utility for arranging stack slots according
130 struct SlotSizeSorter {
131 MachineFrameInfo *MFI;
132 SlotSizeSorter(MachineFrameInfo *mfi) : MFI(mfi) { }
133 bool operator()(int LHS, int RHS) {
134 // We use -1 to denote a uninteresting slot. Place these slots at the end.
135 if (LHS == -1) return false;
136 if (RHS == -1) return true;
137 // Sort according to size.
138 return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
144 StackColoring() : MachineFunctionPass(ID) {
145 initializeStackColoringPass(*PassRegistry::getPassRegistry());
147 void getAnalysisUsage(AnalysisUsage &AU) const;
148 bool runOnMachineFunction(MachineFunction &MF);
154 /// Removes all of the lifetime marker instructions from the function.
155 /// \returns true if any markers were removed.
156 bool removeAllMarkers();
158 /// Scan the machine function and find all of the lifetime markers.
159 /// Record the findings in the BEGIN and END vectors.
160 /// \returns the number of markers found.
161 unsigned collectMarkers(unsigned NumSlot);
163 /// Perform the dataflow calculation and calculate the lifetime for each of
164 /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
165 /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
166 /// in and out blocks.
167 void calculateLocalLiveness();
169 /// Construct the LiveIntervals for the slots.
170 void calculateLiveIntervals(unsigned NumSlots);
172 /// Go over the machine function and change instructions which use stack
173 /// slots to use the joint slots.
174 void remapInstructions(DenseMap<int, int> &SlotRemap);
176 /// The input program may contain instructions which are not inside lifetime
177 /// markers. This can happen due to a bug in the compiler or due to a bug in
178 /// user code (for example, returning a reference to a local variable).
179 /// This procedure checks all of the instructions in the function and
180 /// invalidates lifetime ranges which do not contain all of the instructions
181 /// which access that frame slot.
182 void removeInvalidSlotRanges();
184 /// Map entries which point to other entries to their destination.
185 /// A->B->C becomes A->C.
186 void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
188 } // end anonymous namespace
190 char StackColoring::ID = 0;
191 char &llvm::StackColoringID = StackColoring::ID;
193 INITIALIZE_PASS_BEGIN(StackColoring,
194 "stack-coloring", "Merge disjoint stack slots", false, false)
195 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
196 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
197 INITIALIZE_PASS_DEPENDENCY(StackProtector)
198 INITIALIZE_PASS_END(StackColoring,
199 "stack-coloring", "Merge disjoint stack slots", false, false)
201 void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
202 AU.addRequired<MachineDominatorTree>();
203 AU.addPreserved<MachineDominatorTree>();
204 AU.addRequired<SlotIndexes>();
205 AU.addRequired<StackProtector>();
206 MachineFunctionPass::getAnalysisUsage(AU);
209 void StackColoring::dump() const {
210 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
212 DEBUG(dbgs()<<"Inspecting block #"<<BasicBlocks.lookup(*FI)<<
213 " ["<<FI->getName()<<"]\n");
215 LivenessMap::const_iterator BI = BlockLiveness.find(*FI);
216 assert(BI != BlockLiveness.end() && "Block not found");
217 const BlockLifetimeInfo &BlockInfo = BI->second;
219 DEBUG(dbgs()<<"BEGIN : {");
220 for (unsigned i=0; i < BlockInfo.Begin.size(); ++i)
221 DEBUG(dbgs()<<BlockInfo.Begin.test(i)<<" ");
222 DEBUG(dbgs()<<"}\n");
224 DEBUG(dbgs()<<"END : {");
225 for (unsigned i=0; i < BlockInfo.End.size(); ++i)
226 DEBUG(dbgs()<<BlockInfo.End.test(i)<<" ");
228 DEBUG(dbgs()<<"}\n");
230 DEBUG(dbgs()<<"LIVE_IN: {");
231 for (unsigned i=0; i < BlockInfo.LiveIn.size(); ++i)
232 DEBUG(dbgs()<<BlockInfo.LiveIn.test(i)<<" ");
234 DEBUG(dbgs()<<"}\n");
235 DEBUG(dbgs()<<"LIVEOUT: {");
236 for (unsigned i=0; i < BlockInfo.LiveOut.size(); ++i)
237 DEBUG(dbgs()<<BlockInfo.LiveOut.test(i)<<" ");
238 DEBUG(dbgs()<<"}\n");
242 unsigned StackColoring::collectMarkers(unsigned NumSlot) {
243 unsigned MarkersFound = 0;
244 // Scan the function to find all lifetime markers.
245 // NOTE: We use the a reverse-post-order iteration to ensure that we obtain a
246 // deterministic numbering, and because we'll need a post-order iteration
247 // later for solving the liveness dataflow problem.
248 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
251 // Assign a serial number to this basic block.
252 BasicBlocks[*FI] = BasicBlockNumbering.size();
253 BasicBlockNumbering.push_back(*FI);
255 // Keep a reference to avoid repeated lookups.
256 BlockLifetimeInfo &BlockInfo = BlockLiveness[*FI];
258 BlockInfo.Begin.resize(NumSlot);
259 BlockInfo.End.resize(NumSlot);
261 for (MachineBasicBlock::iterator BI = (*FI)->begin(), BE = (*FI)->end();
264 if (BI->getOpcode() != TargetOpcode::LIFETIME_START &&
265 BI->getOpcode() != TargetOpcode::LIFETIME_END)
268 Markers.push_back(BI);
270 bool IsStart = BI->getOpcode() == TargetOpcode::LIFETIME_START;
271 const MachineOperand &MI = BI->getOperand(0);
272 unsigned Slot = MI.getIndex();
276 const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
278 DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<<
279 " with allocation: "<< Allocation->getName()<<"\n");
283 BlockInfo.Begin.set(Slot);
285 if (BlockInfo.Begin.test(Slot)) {
286 // Allocas that start and end within a single block are handled
287 // specially when computing the LiveIntervals to avoid pessimizing
288 // the liveness propagation.
289 BlockInfo.Begin.reset(Slot);
291 BlockInfo.End.set(Slot);
297 // Update statistics.
298 NumMarkerSeen += MarkersFound;
302 void StackColoring::calculateLocalLiveness() {
303 // Perform a standard reverse dataflow computation to solve for
304 // global liveness. The BEGIN set here is equivalent to KILL in the standard
305 // formulation, and END is equivalent to GEN. The result of this computation
306 // is a map from blocks to bitvectors where the bitvectors represent which
307 // allocas are live in/out of that block.
308 SmallPtrSet<const MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
309 BasicBlockNumbering.end());
310 unsigned NumSSMIters = 0;
316 SmallPtrSet<const MachineBasicBlock*, 8> NextBBSet;
318 for (SmallVectorImpl<const MachineBasicBlock *>::iterator
319 PI = BasicBlockNumbering.begin(), PE = BasicBlockNumbering.end();
322 const MachineBasicBlock *BB = *PI;
323 if (!BBSet.count(BB)) continue;
325 // Use an iterator to avoid repeated lookups.
326 LivenessMap::iterator BI = BlockLiveness.find(BB);
327 assert(BI != BlockLiveness.end() && "Block not found");
328 BlockLifetimeInfo &BlockInfo = BI->second;
330 BitVector LocalLiveIn;
331 BitVector LocalLiveOut;
333 // Forward propagation from begins to ends.
334 for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
335 PE = BB->pred_end(); PI != PE; ++PI) {
336 LivenessMap::const_iterator I = BlockLiveness.find(*PI);
337 assert(I != BlockLiveness.end() && "Predecessor not found");
338 LocalLiveIn |= I->second.LiveOut;
340 LocalLiveIn |= BlockInfo.End;
341 LocalLiveIn.reset(BlockInfo.Begin);
343 // Reverse propagation from ends to begins.
344 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
345 SE = BB->succ_end(); SI != SE; ++SI) {
346 LivenessMap::const_iterator I = BlockLiveness.find(*SI);
347 assert(I != BlockLiveness.end() && "Successor not found");
348 LocalLiveOut |= I->second.LiveIn;
350 LocalLiveOut |= BlockInfo.Begin;
351 LocalLiveOut.reset(BlockInfo.End);
353 LocalLiveIn |= LocalLiveOut;
354 LocalLiveOut |= LocalLiveIn;
356 // After adopting the live bits, we need to turn-off the bits which
357 // are de-activated in this block.
358 LocalLiveOut.reset(BlockInfo.End);
359 LocalLiveIn.reset(BlockInfo.Begin);
361 // If we have both BEGIN and END markers in the same basic block then
362 // we know that the BEGIN marker comes after the END, because we already
363 // handle the case where the BEGIN comes before the END when collecting
364 // the markers (and building the BEGIN/END vectore).
365 // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
366 // BEGIN and END because it means that the value lives before and after
368 BitVector LocalEndBegin = BlockInfo.End;
369 LocalEndBegin &= BlockInfo.Begin;
370 LocalLiveIn |= LocalEndBegin;
371 LocalLiveOut |= LocalEndBegin;
373 if (LocalLiveIn.test(BlockInfo.LiveIn)) {
375 BlockInfo.LiveIn |= LocalLiveIn;
377 for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
378 PE = BB->pred_end(); PI != PE; ++PI)
379 NextBBSet.insert(*PI);
382 if (LocalLiveOut.test(BlockInfo.LiveOut)) {
384 BlockInfo.LiveOut |= LocalLiveOut;
386 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
387 SE = BB->succ_end(); SI != SE; ++SI)
388 NextBBSet.insert(*SI);
396 void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
397 SmallVector<SlotIndex, 16> Starts;
398 SmallVector<SlotIndex, 16> Finishes;
400 // For each block, find which slots are active within this block
401 // and update the live intervals.
402 for (MachineFunction::iterator MBB = MF->begin(), MBBe = MF->end();
403 MBB != MBBe; ++MBB) {
405 Starts.resize(NumSlots);
407 Finishes.resize(NumSlots);
409 // Create the interval for the basic blocks with lifetime markers in them.
410 for (SmallVectorImpl<MachineInstr*>::const_iterator it = Markers.begin(),
411 e = Markers.end(); it != e; ++it) {
412 const MachineInstr *MI = *it;
413 if (MI->getParent() != MBB)
416 assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
417 MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
418 "Invalid Lifetime marker");
420 bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
421 const MachineOperand &Mo = MI->getOperand(0);
422 int Slot = Mo.getIndex();
423 assert(Slot >= 0 && "Invalid slot");
425 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
428 if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
429 Starts[Slot] = ThisIndex;
431 if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
432 Finishes[Slot] = ThisIndex;
436 // Create the interval of the blocks that we previously found to be 'alive'.
437 BlockLifetimeInfo &MBBLiveness = BlockLiveness[MBB];
438 for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1;
439 pos = MBBLiveness.LiveIn.find_next(pos)) {
440 Starts[pos] = Indexes->getMBBStartIdx(MBB);
442 for (int pos = MBBLiveness.LiveOut.find_first(); pos != -1;
443 pos = MBBLiveness.LiveOut.find_next(pos)) {
444 Finishes[pos] = Indexes->getMBBEndIdx(MBB);
447 for (unsigned i = 0; i < NumSlots; ++i) {
448 assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
449 if (!Starts[i].isValid())
452 assert(Starts[i] && Finishes[i] && "Invalid interval");
453 VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
454 SlotIndex S = Starts[i];
455 SlotIndex F = Finishes[i];
457 // We have a single consecutive region.
458 Intervals[i]->addSegment(LiveInterval::Segment(S, F, ValNum));
460 // We have two non-consecutive regions. This happens when
461 // LIFETIME_START appears after the LIFETIME_END marker.
462 SlotIndex NewStart = Indexes->getMBBStartIdx(MBB);
463 SlotIndex NewFin = Indexes->getMBBEndIdx(MBB);
464 Intervals[i]->addSegment(LiveInterval::Segment(NewStart, F, ValNum));
465 Intervals[i]->addSegment(LiveInterval::Segment(S, NewFin, ValNum));
471 bool StackColoring::removeAllMarkers() {
473 for (unsigned i = 0; i < Markers.size(); ++i) {
474 Markers[i]->eraseFromParent();
479 DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
483 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
484 unsigned FixedInstr = 0;
485 unsigned FixedMemOp = 0;
486 unsigned FixedDbg = 0;
487 MachineModuleInfo *MMI = &MF->getMMI();
489 // Remap debug information that refers to stack slots.
490 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
491 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
492 VE = VMap.end(); VI != VE; ++VI) {
493 const MDNode *Var = VI->first;
495 std::pair<unsigned, DebugLoc> &VP = VI->second;
496 if (SlotRemap.count(VP.first)) {
497 DEBUG(dbgs()<<"Remapping debug info for ["<<Var->getName()<<"].\n");
498 VP.first = SlotRemap[VP.first];
503 // Keep a list of *allocas* which need to be remapped.
504 DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
505 for (DenseMap<int, int>::const_iterator it = SlotRemap.begin(),
506 e = SlotRemap.end(); it != e; ++it) {
507 const AllocaInst *From = MFI->getObjectAllocation(it->first);
508 const AllocaInst *To = MFI->getObjectAllocation(it->second);
509 assert(To && From && "Invalid allocation object");
512 // AA might be used later for instruction scheduling, and we need it to be
513 // able to deduce the correct aliasing releationships between pointers
514 // derived from the alloca being remapped and the target of that remapping.
515 // The only safe way, without directly informing AA about the remapping
516 // somehow, is to directly update the IR to reflect the change being made
518 Instruction *Inst = const_cast<AllocaInst *>(To);
519 if (From->getType() != To->getType()) {
520 BitCastInst *Cast = new BitCastInst(Inst, From->getType());
521 Cast->insertAfter(Inst);
525 // Allow the stack protector to adjust its value map to account for the
526 // upcoming replacement.
527 SP->adjustForColoring(From, To);
529 // Note that this will not replace uses in MMOs (which we'll update below),
530 // or anywhere else (which is why we won't delete the original
532 const_cast<AllocaInst *>(From)->replaceAllUsesWith(Inst);
535 // Remap all instructions to the new stack slots.
536 MachineFunction::iterator BB, BBE;
537 MachineBasicBlock::iterator I, IE;
538 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
539 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
541 // Skip lifetime markers. We'll remove them soon.
542 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
543 I->getOpcode() == TargetOpcode::LIFETIME_END)
546 // Update the MachineMemOperand to use the new alloca.
547 for (MachineInstr::mmo_iterator MM = I->memoperands_begin(),
548 E = I->memoperands_end(); MM != E; ++MM) {
549 MachineMemOperand *MMO = *MM;
551 const Value *V = MMO->getValue();
556 // We've replaced IR-level uses of the remapped allocas, so we only
557 // need to replace direct uses here.
558 if (!isa<AllocaInst>(V))
561 const AllocaInst *AI= cast<AllocaInst>(V);
562 if (!Allocas.count(AI))
565 MMO->setValue(Allocas[AI]);
569 // Update all of the machine instruction operands.
570 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
571 MachineOperand &MO = I->getOperand(i);
575 int FromSlot = MO.getIndex();
577 // Don't touch arguments.
581 // Only look at mapped slots.
582 if (!SlotRemap.count(FromSlot))
585 // In a debug build, check that the instruction that we are modifying is
586 // inside the expected live range. If the instruction is not inside
587 // the calculated range then it means that the alloca usage moved
588 // outside of the lifetime markers, or that the user has a bug.
589 // NOTE: Alloca address calculations which happen outside the lifetime
590 // zone are are okay, despite the fact that we don't have a good way
591 // for validating all of the usages of the calculation.
593 bool TouchesMemory = I->mayLoad() || I->mayStore();
594 // If we *don't* protect the user from escaped allocas, don't bother
595 // validating the instructions.
596 if (!I->isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) {
597 SlotIndex Index = Indexes->getInstructionIndex(I);
598 LiveInterval *Interval = Intervals[FromSlot];
599 assert(Interval->find(Index) != Interval->end() &&
600 "Found instruction usage outside of live range.");
604 // Fix the machine instructions.
605 int ToSlot = SlotRemap[FromSlot];
611 DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
612 DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
613 DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
616 void StackColoring::removeInvalidSlotRanges() {
617 MachineFunction::const_iterator BB, BBE;
618 MachineBasicBlock::const_iterator I, IE;
619 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
620 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
622 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
623 I->getOpcode() == TargetOpcode::LIFETIME_END || I->isDebugValue())
626 // Some intervals are suspicious! In some cases we find address
627 // calculations outside of the lifetime zone, but not actual memory
628 // read or write. Memory accesses outside of the lifetime zone are a clear
629 // violation, but address calculations are okay. This can happen when
630 // GEPs are hoisted outside of the lifetime zone.
631 // So, in here we only check instructions which can read or write memory.
632 if (!I->mayLoad() && !I->mayStore())
635 // Check all of the machine operands.
636 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
637 const MachineOperand &MO = I->getOperand(i);
642 int Slot = MO.getIndex();
647 if (Intervals[Slot]->empty())
650 // Check that the used slot is inside the calculated lifetime range.
651 // If it is not, warn about it and invalidate the range.
652 LiveInterval *Interval = Intervals[Slot];
653 SlotIndex Index = Indexes->getInstructionIndex(I);
654 if (Interval->find(Index) == Interval->end()) {
655 Intervals[Slot]->clear();
656 DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
663 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
665 // Expunge slot remap map.
666 for (unsigned i=0; i < NumSlots; ++i) {
667 // If we are remapping i
668 if (SlotRemap.count(i)) {
669 int Target = SlotRemap[i];
670 // As long as our target is mapped to something else, follow it.
671 while (SlotRemap.count(Target)) {
672 Target = SlotRemap[Target];
673 SlotRemap[i] = Target;
679 bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
680 DEBUG(dbgs() << "********** Stack Coloring **********\n"
681 << "********** Function: "
682 << ((const Value*)Func.getFunction())->getName() << '\n');
684 MFI = MF->getFrameInfo();
685 Indexes = &getAnalysis<SlotIndexes>();
686 SP = &getAnalysis<StackProtector>();
687 BlockLiveness.clear();
689 BasicBlockNumbering.clear();
692 VNInfoAllocator.Reset();
694 unsigned NumSlots = MFI->getObjectIndexEnd();
696 // If there are no stack slots then there are no markers to remove.
700 SmallVector<int, 8> SortedSlots;
702 SortedSlots.reserve(NumSlots);
703 Intervals.reserve(NumSlots);
705 unsigned NumMarkers = collectMarkers(NumSlots);
707 unsigned TotalSize = 0;
708 DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
709 DEBUG(dbgs()<<"Slot structure:\n");
711 for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
712 DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
713 TotalSize += MFI->getObjectSize(i);
716 DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
718 // Don't continue because there are not enough lifetime markers, or the
719 // stack is too small, or we are told not to optimize the slots.
720 if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
721 DEBUG(dbgs()<<"Will not try to merge slots.\n");
722 return removeAllMarkers();
725 for (unsigned i=0; i < NumSlots; ++i) {
726 LiveInterval *LI = new LiveInterval(i, 0);
727 Intervals.push_back(LI);
728 LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
729 SortedSlots.push_back(i);
732 // Calculate the liveness of each block.
733 calculateLocalLiveness();
735 // Propagate the liveness information.
736 calculateLiveIntervals(NumSlots);
738 // Search for allocas which are used outside of the declared lifetime
740 if (ProtectFromEscapedAllocas)
741 removeInvalidSlotRanges();
743 // Maps old slots to new slots.
744 DenseMap<int, int> SlotRemap;
745 unsigned RemovedSlots = 0;
746 unsigned ReducedSize = 0;
748 // Do not bother looking at empty intervals.
749 for (unsigned I = 0; I < NumSlots; ++I) {
750 if (Intervals[SortedSlots[I]]->empty())
754 // This is a simple greedy algorithm for merging allocas. First, sort the
755 // slots, placing the largest slots first. Next, perform an n^2 scan and look
756 // for disjoint slots. When you find disjoint slots, merge the samller one
757 // into the bigger one and update the live interval. Remove the small alloca
760 // Sort the slots according to their size. Place unused slots at the end.
761 // Use stable sort to guarantee deterministic code generation.
762 std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
763 SlotSizeSorter(MFI));
768 for (unsigned I = 0; I < NumSlots; ++I) {
769 if (SortedSlots[I] == -1)
772 for (unsigned J=I+1; J < NumSlots; ++J) {
773 if (SortedSlots[J] == -1)
776 int FirstSlot = SortedSlots[I];
777 int SecondSlot = SortedSlots[J];
778 LiveInterval *First = Intervals[FirstSlot];
779 LiveInterval *Second = Intervals[SecondSlot];
780 assert (!First->empty() && !Second->empty() && "Found an empty range");
782 // Merge disjoint slots.
783 if (!First->overlaps(*Second)) {
785 First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0));
786 SlotRemap[SecondSlot] = FirstSlot;
788 DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
789 SecondSlot<<" together.\n");
790 unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
791 MFI->getObjectAlignment(SecondSlot));
793 assert(MFI->getObjectSize(FirstSlot) >=
794 MFI->getObjectSize(SecondSlot) &&
795 "Merging a small object into a larger one");
798 ReducedSize += MFI->getObjectSize(SecondSlot);
799 MFI->setObjectAlignment(FirstSlot, MaxAlignment);
800 MFI->RemoveStackObject(SecondSlot);
806 // Record statistics.
807 StackSpaceSaved += ReducedSize;
808 StackSlotMerged += RemovedSlots;
809 DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
810 ReducedSize<<" bytes\n");
812 // Scan the entire function and update all machine operands that use frame
813 // indices to use the remapped frame index.
814 expungeSlotMap(SlotRemap, NumSlots);
815 remapInstructions(SlotRemap);
817 // Release the intervals.
818 for (unsigned I = 0; I < NumSlots; ++I) {
822 return removeAllMarkers();