LLVM API Documentation

StackColoring.cpp
Go to the documentation of this file.
00001 //===-- StackColoring.cpp -------------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass implements the stack-coloring optimization that looks for
00011 // lifetime markers machine instructions (LIFESTART_BEGIN and LIFESTART_END),
00012 // which represent the possible lifetime of stack slots. It attempts to
00013 // merge disjoint stack slots and reduce the used stack space.
00014 // NOTE: This pass is not StackSlotColoring, which optimizes spill slots.
00015 //
00016 // TODO: In the future we plan to improve stack coloring in the following ways:
00017 // 1. Allow merging multiple small slots into a single larger slot at different
00018 //    offsets.
00019 // 2. Merge this pass with StackSlotColoring and allow merging of allocas with
00020 //    spill slots.
00021 //
00022 //===----------------------------------------------------------------------===//
00023 
00024 #include "llvm/CodeGen/Passes.h"
00025 #include "llvm/ADT/BitVector.h"
00026 #include "llvm/ADT/DepthFirstIterator.h"
00027 #include "llvm/ADT/PostOrderIterator.h"
00028 #include "llvm/ADT/SetVector.h"
00029 #include "llvm/ADT/SmallPtrSet.h"
00030 #include "llvm/ADT/SparseSet.h"
00031 #include "llvm/ADT/Statistic.h"
00032 #include "llvm/Analysis/ValueTracking.h"
00033 #include "llvm/CodeGen/LiveInterval.h"
00034 #include "llvm/CodeGen/MachineBasicBlock.h"
00035 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
00036 #include "llvm/CodeGen/MachineDominators.h"
00037 #include "llvm/CodeGen/MachineFrameInfo.h"
00038 #include "llvm/CodeGen/MachineFunctionPass.h"
00039 #include "llvm/CodeGen/MachineLoopInfo.h"
00040 #include "llvm/CodeGen/MachineMemOperand.h"
00041 #include "llvm/CodeGen/MachineModuleInfo.h"
00042 #include "llvm/CodeGen/MachineRegisterInfo.h"
00043 #include "llvm/CodeGen/PseudoSourceValue.h"
00044 #include "llvm/CodeGen/SlotIndexes.h"
00045 #include "llvm/CodeGen/StackProtector.h"
00046 #include "llvm/IR/DebugInfo.h"
00047 #include "llvm/IR/Dominators.h"
00048 #include "llvm/IR/Function.h"
00049 #include "llvm/IR/Instructions.h"
00050 #include "llvm/IR/Module.h"
00051 #include "llvm/MC/MCInstrItineraries.h"
00052 #include "llvm/Support/CommandLine.h"
00053 #include "llvm/Support/Debug.h"
00054 #include "llvm/Support/raw_ostream.h"
00055 #include "llvm/Target/TargetInstrInfo.h"
00056 #include "llvm/Target/TargetRegisterInfo.h"
00057 
00058 using namespace llvm;
00059 
00060 #define DEBUG_TYPE "stackcoloring"
00061 
00062 static cl::opt<bool>
00063 DisableColoring("no-stack-coloring",
00064         cl::init(false), cl::Hidden,
00065         cl::desc("Disable stack coloring"));
00066 
00067 /// The user may write code that uses allocas outside of the declared lifetime
00068 /// zone. This can happen when the user returns a reference to a local
00069 /// data-structure. We can detect these cases and decide not to optimize the
00070 /// code. If this flag is enabled, we try to save the user.
00071 static cl::opt<bool>
00072 ProtectFromEscapedAllocas("protect-from-escaped-allocas",
00073                           cl::init(false), cl::Hidden,
00074                           cl::desc("Do not optimize lifetime zones that "
00075                                    "are broken"));
00076 
00077 STATISTIC(NumMarkerSeen,  "Number of lifetime markers found.");
00078 STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
00079 STATISTIC(StackSlotMerged, "Number of stack slot merged.");
00080 STATISTIC(EscapedAllocas, "Number of allocas that escaped the lifetime region");
00081 
00082 //===----------------------------------------------------------------------===//
00083 //                           StackColoring Pass
00084 //===----------------------------------------------------------------------===//
00085 
00086 namespace {
00087 /// StackColoring - A machine pass for merging disjoint stack allocations,
00088 /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
00089 class StackColoring : public MachineFunctionPass {
00090   MachineFrameInfo *MFI;
00091   MachineFunction *MF;
00092 
00093   /// A class representing liveness information for a single basic block.
00094   /// Each bit in the BitVector represents the liveness property
00095   /// for a different stack slot.
00096   struct BlockLifetimeInfo {
00097     /// Which slots BEGINs in each basic block.
00098     BitVector Begin;
00099     /// Which slots ENDs in each basic block.
00100     BitVector End;
00101     /// Which slots are marked as LIVE_IN, coming into each basic block.
00102     BitVector LiveIn;
00103     /// Which slots are marked as LIVE_OUT, coming out of each basic block.
00104     BitVector LiveOut;
00105   };
00106 
00107   /// Maps active slots (per bit) for each basic block.
00108   typedef DenseMap<const MachineBasicBlock*, BlockLifetimeInfo> LivenessMap;
00109   LivenessMap BlockLiveness;
00110 
00111   /// Maps serial numbers to basic blocks.
00112   DenseMap<const MachineBasicBlock*, int> BasicBlocks;
00113   /// Maps basic blocks to a serial number.
00114   SmallVector<const MachineBasicBlock*, 8> BasicBlockNumbering;
00115 
00116   /// Maps liveness intervals for each slot.
00117   SmallVector<std::unique_ptr<LiveInterval>, 16> Intervals;
00118   /// VNInfo is used for the construction of LiveIntervals.
00119   VNInfo::Allocator VNInfoAllocator;
00120   /// SlotIndex analysis object.
00121   SlotIndexes *Indexes;
00122   /// The stack protector object.
00123   StackProtector *SP;
00124 
00125   /// The list of lifetime markers found. These markers are to be removed
00126   /// once the coloring is done.
00127   SmallVector<MachineInstr*, 8> Markers;
00128 
00129 public:
00130   static char ID;
00131   StackColoring() : MachineFunctionPass(ID) {
00132     initializeStackColoringPass(*PassRegistry::getPassRegistry());
00133   }
00134   void getAnalysisUsage(AnalysisUsage &AU) const override;
00135   bool runOnMachineFunction(MachineFunction &MF) override;
00136 
00137 private:
00138   /// Debug.
00139   void dump() const;
00140 
00141   /// Removes all of the lifetime marker instructions from the function.
00142   /// \returns true if any markers were removed.
00143   bool removeAllMarkers();
00144 
00145   /// Scan the machine function and find all of the lifetime markers.
00146   /// Record the findings in the BEGIN and END vectors.
00147   /// \returns the number of markers found.
00148   unsigned collectMarkers(unsigned NumSlot);
00149 
00150   /// Perform the dataflow calculation and calculate the lifetime for each of
00151   /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
00152   /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
00153   /// in and out blocks.
00154   void calculateLocalLiveness();
00155 
00156   /// Construct the LiveIntervals for the slots.
00157   void calculateLiveIntervals(unsigned NumSlots);
00158 
00159   /// Go over the machine function and change instructions which use stack
00160   /// slots to use the joint slots.
00161   void remapInstructions(DenseMap<int, int> &SlotRemap);
00162 
00163   /// The input program may contain instructions which are not inside lifetime
00164   /// markers. This can happen due to a bug in the compiler or due to a bug in
00165   /// user code (for example, returning a reference to a local variable).
00166   /// This procedure checks all of the instructions in the function and
00167   /// invalidates lifetime ranges which do not contain all of the instructions
00168   /// which access that frame slot.
00169   void removeInvalidSlotRanges();
00170 
00171   /// Map entries which point to other entries to their destination.
00172   ///   A->B->C becomes A->C.
00173    void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
00174 };
00175 } // end anonymous namespace
00176 
00177 char StackColoring::ID = 0;
00178 char &llvm::StackColoringID = StackColoring::ID;
00179 
00180 INITIALIZE_PASS_BEGIN(StackColoring,
00181                    "stack-coloring", "Merge disjoint stack slots", false, false)
00182 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
00183 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
00184 INITIALIZE_PASS_DEPENDENCY(StackProtector)
00185 INITIALIZE_PASS_END(StackColoring,
00186                    "stack-coloring", "Merge disjoint stack slots", false, false)
00187 
00188 void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
00189   AU.addRequired<MachineDominatorTree>();
00190   AU.addPreserved<MachineDominatorTree>();
00191   AU.addRequired<SlotIndexes>();
00192   AU.addRequired<StackProtector>();
00193   MachineFunctionPass::getAnalysisUsage(AU);
00194 }
00195 
00196 void StackColoring::dump() const {
00197   for (MachineBasicBlock *MBB : depth_first(MF)) {
00198     DEBUG(dbgs() << "Inspecting block #" << BasicBlocks.lookup(MBB) << " ["
00199                  << MBB->getName() << "]\n");
00200 
00201     LivenessMap::const_iterator BI = BlockLiveness.find(MBB);
00202     assert(BI != BlockLiveness.end() && "Block not found");
00203     const BlockLifetimeInfo &BlockInfo = BI->second;
00204 
00205     DEBUG(dbgs()<<"BEGIN  : {");
00206     for (unsigned i=0; i < BlockInfo.Begin.size(); ++i)
00207       DEBUG(dbgs()<<BlockInfo.Begin.test(i)<<" ");
00208     DEBUG(dbgs()<<"}\n");
00209 
00210     DEBUG(dbgs()<<"END    : {");
00211     for (unsigned i=0; i < BlockInfo.End.size(); ++i)
00212       DEBUG(dbgs()<<BlockInfo.End.test(i)<<" ");
00213 
00214     DEBUG(dbgs()<<"}\n");
00215 
00216     DEBUG(dbgs()<<"LIVE_IN: {");
00217     for (unsigned i=0; i < BlockInfo.LiveIn.size(); ++i)
00218       DEBUG(dbgs()<<BlockInfo.LiveIn.test(i)<<" ");
00219 
00220     DEBUG(dbgs()<<"}\n");
00221     DEBUG(dbgs()<<"LIVEOUT: {");
00222     for (unsigned i=0; i < BlockInfo.LiveOut.size(); ++i)
00223       DEBUG(dbgs()<<BlockInfo.LiveOut.test(i)<<" ");
00224     DEBUG(dbgs()<<"}\n");
00225   }
00226 }
00227 
00228 unsigned StackColoring::collectMarkers(unsigned NumSlot) {
00229   unsigned MarkersFound = 0;
00230   // Scan the function to find all lifetime markers.
00231   // NOTE: We use a reverse-post-order iteration to ensure that we obtain a
00232   // deterministic numbering, and because we'll need a post-order iteration
00233   // later for solving the liveness dataflow problem.
00234   for (MachineBasicBlock *MBB : depth_first(MF)) {
00235 
00236     // Assign a serial number to this basic block.
00237     BasicBlocks[MBB] = BasicBlockNumbering.size();
00238     BasicBlockNumbering.push_back(MBB);
00239 
00240     // Keep a reference to avoid repeated lookups.
00241     BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB];
00242 
00243     BlockInfo.Begin.resize(NumSlot);
00244     BlockInfo.End.resize(NumSlot);
00245 
00246     for (MachineInstr &MI : *MBB) {
00247       if (MI.getOpcode() != TargetOpcode::LIFETIME_START &&
00248           MI.getOpcode() != TargetOpcode::LIFETIME_END)
00249         continue;
00250 
00251       Markers.push_back(&MI);
00252 
00253       bool IsStart = MI.getOpcode() == TargetOpcode::LIFETIME_START;
00254       const MachineOperand &MO = MI.getOperand(0);
00255       unsigned Slot = MO.getIndex();
00256 
00257       MarkersFound++;
00258 
00259       const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
00260       if (Allocation) {
00261         DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<<
00262               " with allocation: "<< Allocation->getName()<<"\n");
00263       }
00264 
00265       if (IsStart) {
00266         BlockInfo.Begin.set(Slot);
00267       } else {
00268         if (BlockInfo.Begin.test(Slot)) {
00269           // Allocas that start and end within a single block are handled
00270           // specially when computing the LiveIntervals to avoid pessimizing
00271           // the liveness propagation.
00272           BlockInfo.Begin.reset(Slot);
00273         } else {
00274           BlockInfo.End.set(Slot);
00275         }
00276       }
00277     }
00278   }
00279 
00280   // Update statistics.
00281   NumMarkerSeen += MarkersFound;
00282   return MarkersFound;
00283 }
00284 
00285 void StackColoring::calculateLocalLiveness() {
00286   // Perform a standard reverse dataflow computation to solve for
00287   // global liveness.  The BEGIN set here is equivalent to KILL in the standard
00288   // formulation, and END is equivalent to GEN.  The result of this computation
00289   // is a map from blocks to bitvectors where the bitvectors represent which
00290   // allocas are live in/out of that block.
00291   SmallPtrSet<const MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
00292                                                  BasicBlockNumbering.end());
00293   unsigned NumSSMIters = 0;
00294   bool changed = true;
00295   while (changed) {
00296     changed = false;
00297     ++NumSSMIters;
00298 
00299     SmallPtrSet<const MachineBasicBlock*, 8> NextBBSet;
00300 
00301     for (const MachineBasicBlock *BB : BasicBlockNumbering) {
00302       if (!BBSet.count(BB)) continue;
00303 
00304       // Use an iterator to avoid repeated lookups.
00305       LivenessMap::iterator BI = BlockLiveness.find(BB);
00306       assert(BI != BlockLiveness.end() && "Block not found");
00307       BlockLifetimeInfo &BlockInfo = BI->second;
00308 
00309       BitVector LocalLiveIn;
00310       BitVector LocalLiveOut;
00311 
00312       // Forward propagation from begins to ends.
00313       for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
00314            PE = BB->pred_end(); PI != PE; ++PI) {
00315         LivenessMap::const_iterator I = BlockLiveness.find(*PI);
00316         assert(I != BlockLiveness.end() && "Predecessor not found");
00317         LocalLiveIn |= I->second.LiveOut;
00318       }
00319       LocalLiveIn |= BlockInfo.End;
00320       LocalLiveIn.reset(BlockInfo.Begin);
00321 
00322       // Reverse propagation from ends to begins.
00323       for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
00324            SE = BB->succ_end(); SI != SE; ++SI) {
00325         LivenessMap::const_iterator I = BlockLiveness.find(*SI);
00326         assert(I != BlockLiveness.end() && "Successor not found");
00327         LocalLiveOut |= I->second.LiveIn;
00328       }
00329       LocalLiveOut |= BlockInfo.Begin;
00330       LocalLiveOut.reset(BlockInfo.End);
00331 
00332       LocalLiveIn |= LocalLiveOut;
00333       LocalLiveOut |= LocalLiveIn;
00334 
00335       // After adopting the live bits, we need to turn-off the bits which
00336       // are de-activated in this block.
00337       LocalLiveOut.reset(BlockInfo.End);
00338       LocalLiveIn.reset(BlockInfo.Begin);
00339 
00340       // If we have both BEGIN and END markers in the same basic block then
00341       // we know that the BEGIN marker comes after the END, because we already
00342       // handle the case where the BEGIN comes before the END when collecting
00343       // the markers (and building the BEGIN/END vectore).
00344       // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
00345       // BEGIN and END because it means that the value lives before and after
00346       // this basic block.
00347       BitVector LocalEndBegin = BlockInfo.End;
00348       LocalEndBegin &= BlockInfo.Begin;
00349       LocalLiveIn |= LocalEndBegin;
00350       LocalLiveOut |= LocalEndBegin;
00351 
00352       if (LocalLiveIn.test(BlockInfo.LiveIn)) {
00353         changed = true;
00354         BlockInfo.LiveIn |= LocalLiveIn;
00355 
00356         NextBBSet.insert(BB->pred_begin(), BB->pred_end());
00357       }
00358 
00359       if (LocalLiveOut.test(BlockInfo.LiveOut)) {
00360         changed = true;
00361         BlockInfo.LiveOut |= LocalLiveOut;
00362 
00363         NextBBSet.insert(BB->succ_begin(), BB->succ_end());
00364       }
00365     }
00366 
00367     BBSet = NextBBSet;
00368   }// while changed.
00369 }
00370 
00371 void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
00372   SmallVector<SlotIndex, 16> Starts;
00373   SmallVector<SlotIndex, 16> Finishes;
00374 
00375   // For each block, find which slots are active within this block
00376   // and update the live intervals.
00377   for (const MachineBasicBlock &MBB : *MF) {
00378     Starts.clear();
00379     Starts.resize(NumSlots);
00380     Finishes.clear();
00381     Finishes.resize(NumSlots);
00382 
00383     // Create the interval for the basic blocks with lifetime markers in them.
00384     for (const MachineInstr *MI : Markers) {
00385       if (MI->getParent() != &MBB)
00386         continue;
00387 
00388       assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
00389               MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
00390              "Invalid Lifetime marker");
00391 
00392       bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
00393       const MachineOperand &Mo = MI->getOperand(0);
00394       int Slot = Mo.getIndex();
00395       assert(Slot >= 0 && "Invalid slot");
00396 
00397       SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
00398 
00399       if (IsStart) {
00400         if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
00401           Starts[Slot] = ThisIndex;
00402       } else {
00403         if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
00404           Finishes[Slot] = ThisIndex;
00405       }
00406     }
00407 
00408     // Create the interval of the blocks that we previously found to be 'alive'.
00409     BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB];
00410     for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1;
00411          pos = MBBLiveness.LiveIn.find_next(pos)) {
00412       Starts[pos] = Indexes->getMBBStartIdx(&MBB);
00413     }
00414     for (int pos = MBBLiveness.LiveOut.find_first(); pos != -1;
00415          pos = MBBLiveness.LiveOut.find_next(pos)) {
00416       Finishes[pos] = Indexes->getMBBEndIdx(&MBB);
00417     }
00418 
00419     for (unsigned i = 0; i < NumSlots; ++i) {
00420       assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
00421       if (!Starts[i].isValid())
00422         continue;
00423 
00424       assert(Starts[i] && Finishes[i] && "Invalid interval");
00425       VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
00426       SlotIndex S = Starts[i];
00427       SlotIndex F = Finishes[i];
00428       if (S < F) {
00429         // We have a single consecutive region.
00430         Intervals[i]->addSegment(LiveInterval::Segment(S, F, ValNum));
00431       } else {
00432         // We have two non-consecutive regions. This happens when
00433         // LIFETIME_START appears after the LIFETIME_END marker.
00434         SlotIndex NewStart = Indexes->getMBBStartIdx(&MBB);
00435         SlotIndex NewFin = Indexes->getMBBEndIdx(&MBB);
00436         Intervals[i]->addSegment(LiveInterval::Segment(NewStart, F, ValNum));
00437         Intervals[i]->addSegment(LiveInterval::Segment(S, NewFin, ValNum));
00438       }
00439     }
00440   }
00441 }
00442 
00443 bool StackColoring::removeAllMarkers() {
00444   unsigned Count = 0;
00445   for (MachineInstr *MI : Markers) {
00446     MI->eraseFromParent();
00447     Count++;
00448   }
00449   Markers.clear();
00450 
00451   DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
00452   return Count;
00453 }
00454 
00455 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
00456   unsigned FixedInstr = 0;
00457   unsigned FixedMemOp = 0;
00458   unsigned FixedDbg = 0;
00459   MachineModuleInfo *MMI = &MF->getMMI();
00460 
00461   // Remap debug information that refers to stack slots.
00462   for (auto &VI : MMI->getVariableDbgInfo()) {
00463     if (!VI.Var)
00464       continue;
00465     if (SlotRemap.count(VI.Slot)) {
00466       DEBUG(dbgs()<<"Remapping debug info for ["<<VI.Var->getName()<<"].\n");
00467       VI.Slot = SlotRemap[VI.Slot];
00468       FixedDbg++;
00469     }
00470   }
00471 
00472   // Keep a list of *allocas* which need to be remapped.
00473   DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
00474   for (const std::pair<int, int> &SI : SlotRemap) {
00475     const AllocaInst *From = MFI->getObjectAllocation(SI.first);
00476     const AllocaInst *To = MFI->getObjectAllocation(SI.second);
00477     assert(To && From && "Invalid allocation object");
00478     Allocas[From] = To;
00479 
00480     // AA might be used later for instruction scheduling, and we need it to be
00481     // able to deduce the correct aliasing releationships between pointers
00482     // derived from the alloca being remapped and the target of that remapping.
00483     // The only safe way, without directly informing AA about the remapping
00484     // somehow, is to directly update the IR to reflect the change being made
00485     // here.
00486     Instruction *Inst = const_cast<AllocaInst *>(To);
00487     if (From->getType() != To->getType()) {
00488       BitCastInst *Cast = new BitCastInst(Inst, From->getType());
00489       Cast->insertAfter(Inst);
00490       Inst = Cast;
00491     }
00492 
00493     // Allow the stack protector to adjust its value map to account for the
00494     // upcoming replacement.
00495     SP->adjustForColoring(From, To);
00496 
00497     // Note that this will not replace uses in MMOs (which we'll update below),
00498     // or anywhere else (which is why we won't delete the original
00499     // instruction).
00500     const_cast<AllocaInst *>(From)->replaceAllUsesWith(Inst);
00501   }
00502 
00503   // Remap all instructions to the new stack slots.
00504   for (MachineBasicBlock &BB : *MF)
00505     for (MachineInstr &I : BB) {
00506       // Skip lifetime markers. We'll remove them soon.
00507       if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
00508           I.getOpcode() == TargetOpcode::LIFETIME_END)
00509         continue;
00510 
00511       // Update the MachineMemOperand to use the new alloca.
00512       for (MachineMemOperand *MMO : I.memoperands()) {
00513         // FIXME: In order to enable the use of TBAA when using AA in CodeGen,
00514         // we'll also need to update the TBAA nodes in MMOs with values
00515         // derived from the merged allocas. When doing this, we'll need to use
00516         // the same variant of GetUnderlyingObjects that is used by the
00517         // instruction scheduler (that can look through ptrtoint/inttoptr
00518         // pairs).
00519 
00520         // We've replaced IR-level uses of the remapped allocas, so we only
00521         // need to replace direct uses here.
00522         const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue());
00523         if (!AI)
00524           continue;
00525 
00526         if (!Allocas.count(AI))
00527           continue;
00528 
00529         MMO->setValue(Allocas[AI]);
00530         FixedMemOp++;
00531       }
00532 
00533       // Update all of the machine instruction operands.
00534       for (MachineOperand &MO : I.operands()) {
00535         if (!MO.isFI())
00536           continue;
00537         int FromSlot = MO.getIndex();
00538 
00539         // Don't touch arguments.
00540         if (FromSlot<0)
00541           continue;
00542 
00543         // Only look at mapped slots.
00544         if (!SlotRemap.count(FromSlot))
00545           continue;
00546 
00547         // In a debug build, check that the instruction that we are modifying is
00548         // inside the expected live range. If the instruction is not inside
00549         // the calculated range then it means that the alloca usage moved
00550         // outside of the lifetime markers, or that the user has a bug.
00551         // NOTE: Alloca address calculations which happen outside the lifetime
00552         // zone are are okay, despite the fact that we don't have a good way
00553         // for validating all of the usages of the calculation.
00554 #ifndef NDEBUG
00555         bool TouchesMemory = I.mayLoad() || I.mayStore();
00556         // If we *don't* protect the user from escaped allocas, don't bother
00557         // validating the instructions.
00558         if (!I.isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) {
00559           SlotIndex Index = Indexes->getInstructionIndex(&I);
00560           const LiveInterval *Interval = &*Intervals[FromSlot];
00561           assert(Interval->find(Index) != Interval->end() &&
00562                  "Found instruction usage outside of live range.");
00563         }
00564 #endif
00565 
00566         // Fix the machine instructions.
00567         int ToSlot = SlotRemap[FromSlot];
00568         MO.setIndex(ToSlot);
00569         FixedInstr++;
00570       }
00571     }
00572 
00573   DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
00574   DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
00575   DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
00576 }
00577 
00578 void StackColoring::removeInvalidSlotRanges() {
00579   for (MachineBasicBlock &BB : *MF)
00580     for (MachineInstr &I : BB) {
00581       if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
00582           I.getOpcode() == TargetOpcode::LIFETIME_END || I.isDebugValue())
00583         continue;
00584 
00585       // Some intervals are suspicious! In some cases we find address
00586       // calculations outside of the lifetime zone, but not actual memory
00587       // read or write. Memory accesses outside of the lifetime zone are a clear
00588       // violation, but address calculations are okay. This can happen when
00589       // GEPs are hoisted outside of the lifetime zone.
00590       // So, in here we only check instructions which can read or write memory.
00591       if (!I.mayLoad() && !I.mayStore())
00592         continue;
00593 
00594       // Check all of the machine operands.
00595       for (const MachineOperand &MO : I.operands()) {
00596         if (!MO.isFI())
00597           continue;
00598 
00599         int Slot = MO.getIndex();
00600 
00601         if (Slot<0)
00602           continue;
00603 
00604         if (Intervals[Slot]->empty())
00605           continue;
00606 
00607         // Check that the used slot is inside the calculated lifetime range.
00608         // If it is not, warn about it and invalidate the range.
00609         LiveInterval *Interval = &*Intervals[Slot];
00610         SlotIndex Index = Indexes->getInstructionIndex(&I);
00611         if (Interval->find(Index) == Interval->end()) {
00612           Interval->clear();
00613           DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
00614           EscapedAllocas++;
00615         }
00616       }
00617     }
00618 }
00619 
00620 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
00621                                    unsigned NumSlots) {
00622   // Expunge slot remap map.
00623   for (unsigned i=0; i < NumSlots; ++i) {
00624     // If we are remapping i
00625     if (SlotRemap.count(i)) {
00626       int Target = SlotRemap[i];
00627       // As long as our target is mapped to something else, follow it.
00628       while (SlotRemap.count(Target)) {
00629         Target = SlotRemap[Target];
00630         SlotRemap[i] = Target;
00631       }
00632     }
00633   }
00634 }
00635 
00636 bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
00637   if (skipOptnoneFunction(*Func.getFunction()))
00638     return false;
00639 
00640   DEBUG(dbgs() << "********** Stack Coloring **********\n"
00641                << "********** Function: "
00642                << ((const Value*)Func.getFunction())->getName() << '\n');
00643   MF = &Func;
00644   MFI = MF->getFrameInfo();
00645   Indexes = &getAnalysis<SlotIndexes>();
00646   SP = &getAnalysis<StackProtector>();
00647   BlockLiveness.clear();
00648   BasicBlocks.clear();
00649   BasicBlockNumbering.clear();
00650   Markers.clear();
00651   Intervals.clear();
00652   VNInfoAllocator.Reset();
00653 
00654   unsigned NumSlots = MFI->getObjectIndexEnd();
00655 
00656   // If there are no stack slots then there are no markers to remove.
00657   if (!NumSlots)
00658     return false;
00659 
00660   SmallVector<int, 8> SortedSlots;
00661 
00662   SortedSlots.reserve(NumSlots);
00663   Intervals.reserve(NumSlots);
00664 
00665   unsigned NumMarkers = collectMarkers(NumSlots);
00666 
00667   unsigned TotalSize = 0;
00668   DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
00669   DEBUG(dbgs()<<"Slot structure:\n");
00670 
00671   for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
00672     DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
00673     TotalSize += MFI->getObjectSize(i);
00674   }
00675 
00676   DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
00677 
00678   // Don't continue because there are not enough lifetime markers, or the
00679   // stack is too small, or we are told not to optimize the slots.
00680   if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
00681     DEBUG(dbgs()<<"Will not try to merge slots.\n");
00682     return removeAllMarkers();
00683   }
00684 
00685   for (unsigned i=0; i < NumSlots; ++i) {
00686     std::unique_ptr<LiveInterval> LI(new LiveInterval(i, 0));
00687     LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
00688     Intervals.push_back(std::move(LI));
00689     SortedSlots.push_back(i);
00690   }
00691 
00692   // Calculate the liveness of each block.
00693   calculateLocalLiveness();
00694 
00695   // Propagate the liveness information.
00696   calculateLiveIntervals(NumSlots);
00697 
00698   // Search for allocas which are used outside of the declared lifetime
00699   // markers.
00700   if (ProtectFromEscapedAllocas)
00701     removeInvalidSlotRanges();
00702 
00703   // Maps old slots to new slots.
00704   DenseMap<int, int> SlotRemap;
00705   unsigned RemovedSlots = 0;
00706   unsigned ReducedSize = 0;
00707 
00708   // Do not bother looking at empty intervals.
00709   for (unsigned I = 0; I < NumSlots; ++I) {
00710     if (Intervals[SortedSlots[I]]->empty())
00711       SortedSlots[I] = -1;
00712   }
00713 
00714   // This is a simple greedy algorithm for merging allocas. First, sort the
00715   // slots, placing the largest slots first. Next, perform an n^2 scan and look
00716   // for disjoint slots. When you find disjoint slots, merge the samller one
00717   // into the bigger one and update the live interval. Remove the small alloca
00718   // and continue.
00719 
00720   // Sort the slots according to their size. Place unused slots at the end.
00721   // Use stable sort to guarantee deterministic code generation.
00722   std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
00723                    [this](int LHS, int RHS) {
00724     // We use -1 to denote a uninteresting slot. Place these slots at the end.
00725     if (LHS == -1) return false;
00726     if (RHS == -1) return true;
00727     // Sort according to size.
00728     return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
00729   });
00730 
00731   bool Changed = true;
00732   while (Changed) {
00733     Changed = false;
00734     for (unsigned I = 0; I < NumSlots; ++I) {
00735       if (SortedSlots[I] == -1)
00736         continue;
00737 
00738       for (unsigned J=I+1; J < NumSlots; ++J) {
00739         if (SortedSlots[J] == -1)
00740           continue;
00741 
00742         int FirstSlot = SortedSlots[I];
00743         int SecondSlot = SortedSlots[J];
00744         LiveInterval *First = &*Intervals[FirstSlot];
00745         LiveInterval *Second = &*Intervals[SecondSlot];
00746         assert (!First->empty() && !Second->empty() && "Found an empty range");
00747 
00748         // Merge disjoint slots.
00749         if (!First->overlaps(*Second)) {
00750           Changed = true;
00751           First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0));
00752           SlotRemap[SecondSlot] = FirstSlot;
00753           SortedSlots[J] = -1;
00754           DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
00755                 SecondSlot<<" together.\n");
00756           unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
00757                                            MFI->getObjectAlignment(SecondSlot));
00758 
00759           assert(MFI->getObjectSize(FirstSlot) >=
00760                  MFI->getObjectSize(SecondSlot) &&
00761                  "Merging a small object into a larger one");
00762 
00763           RemovedSlots+=1;
00764           ReducedSize += MFI->getObjectSize(SecondSlot);
00765           MFI->setObjectAlignment(FirstSlot, MaxAlignment);
00766           MFI->RemoveStackObject(SecondSlot);
00767         }
00768       }
00769     }
00770   }// While changed.
00771 
00772   // Record statistics.
00773   StackSpaceSaved += ReducedSize;
00774   StackSlotMerged += RemovedSlots;
00775   DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
00776         ReducedSize<<" bytes\n");
00777 
00778   // Scan the entire function and update all machine operands that use frame
00779   // indices to use the remapped frame index.
00780   expungeSlotMap(SlotRemap, NumSlots);
00781   remapInstructions(SlotRemap);
00782 
00783   return removeAllMarkers();
00784 }