LLVM API Documentation

StackSlotColoring.cpp
Go to the documentation of this file.
00001 //===-- StackSlotColoring.cpp - Stack slot coloring pass. -----------------===//
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 file implements the stack slot coloring pass.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/Passes.h"
00015 #include "llvm/ADT/BitVector.h"
00016 #include "llvm/ADT/SmallVector.h"
00017 #include "llvm/ADT/Statistic.h"
00018 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00019 #include "llvm/CodeGen/LiveStackAnalysis.h"
00020 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
00021 #include "llvm/CodeGen/MachineFrameInfo.h"
00022 #include "llvm/CodeGen/MachineInstrBuilder.h"
00023 #include "llvm/CodeGen/MachineMemOperand.h"
00024 #include "llvm/CodeGen/MachineRegisterInfo.h"
00025 #include "llvm/CodeGen/PseudoSourceValue.h"
00026 #include "llvm/IR/Module.h"
00027 #include "llvm/Support/CommandLine.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 #include "llvm/Target/TargetInstrInfo.h"
00031 #include "llvm/Target/TargetMachine.h"
00032 #include "llvm/Target/TargetSubtargetInfo.h"
00033 #include <vector>
00034 using namespace llvm;
00035 
00036 #define DEBUG_TYPE "stackslotcoloring"
00037 
00038 static cl::opt<bool>
00039 DisableSharing("no-stack-slot-sharing",
00040              cl::init(false), cl::Hidden,
00041              cl::desc("Suppress slot sharing during stack coloring"));
00042 
00043 static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
00044 
00045 STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
00046 STATISTIC(NumDead,       "Number of trivially dead stack accesses eliminated");
00047 
00048 namespace {
00049   class StackSlotColoring : public MachineFunctionPass {
00050     LiveStacks* LS;
00051     MachineFrameInfo *MFI;
00052     const TargetInstrInfo  *TII;
00053     const MachineBlockFrequencyInfo *MBFI;
00054 
00055     // SSIntervals - Spill slot intervals.
00056     std::vector<LiveInterval*> SSIntervals;
00057 
00058     // SSRefs - Keep a list of MachineMemOperands for each spill slot.
00059     // MachineMemOperands can be shared between instructions, so we need
00060     // to be careful that renames like [FI0, FI1] -> [FI1, FI2] do not
00061     // become FI0 -> FI1 -> FI2.
00062     SmallVector<SmallVector<MachineMemOperand *, 8>, 16> SSRefs;
00063 
00064     // OrigAlignments - Alignments of stack objects before coloring.
00065     SmallVector<unsigned, 16> OrigAlignments;
00066 
00067     // OrigSizes - Sizess of stack objects before coloring.
00068     SmallVector<unsigned, 16> OrigSizes;
00069 
00070     // AllColors - If index is set, it's a spill slot, i.e. color.
00071     // FIXME: This assumes PEI locate spill slot with smaller indices
00072     // closest to stack pointer / frame pointer. Therefore, smaller
00073     // index == better color.
00074     BitVector AllColors;
00075 
00076     // NextColor - Next "color" that's not yet used.
00077     int NextColor;
00078 
00079     // UsedColors - "Colors" that have been assigned.
00080     BitVector UsedColors;
00081 
00082     // Assignments - Color to intervals mapping.
00083     SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
00084 
00085   public:
00086     static char ID; // Pass identification
00087     StackSlotColoring() :
00088       MachineFunctionPass(ID), NextColor(-1) {
00089         initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
00090       }
00091 
00092     void getAnalysisUsage(AnalysisUsage &AU) const override {
00093       AU.setPreservesCFG();
00094       AU.addRequired<SlotIndexes>();
00095       AU.addPreserved<SlotIndexes>();
00096       AU.addRequired<LiveStacks>();
00097       AU.addRequired<MachineBlockFrequencyInfo>();
00098       AU.addPreserved<MachineBlockFrequencyInfo>();
00099       AU.addPreservedID(MachineDominatorsID);
00100       MachineFunctionPass::getAnalysisUsage(AU);
00101     }
00102 
00103     bool runOnMachineFunction(MachineFunction &MF) override;
00104 
00105   private:
00106     void InitializeSlots();
00107     void ScanForSpillSlotRefs(MachineFunction &MF);
00108     bool OverlapWithAssignments(LiveInterval *li, int Color) const;
00109     int ColorSlot(LiveInterval *li);
00110     bool ColorSlots(MachineFunction &MF);
00111     void RewriteInstruction(MachineInstr *MI, SmallVectorImpl<int> &SlotMapping,
00112                             MachineFunction &MF);
00113     bool RemoveDeadStores(MachineBasicBlock* MBB);
00114   };
00115 } // end anonymous namespace
00116 
00117 char StackSlotColoring::ID = 0;
00118 char &llvm::StackSlotColoringID = StackSlotColoring::ID;
00119 
00120 INITIALIZE_PASS_BEGIN(StackSlotColoring, "stack-slot-coloring",
00121                 "Stack Slot Coloring", false, false)
00122 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
00123 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
00124 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
00125 INITIALIZE_PASS_END(StackSlotColoring, "stack-slot-coloring",
00126                 "Stack Slot Coloring", false, false)
00127 
00128 namespace {
00129   // IntervalSorter - Comparison predicate that sort live intervals by
00130   // their weight.
00131   struct IntervalSorter {
00132     bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
00133       return LHS->weight > RHS->weight;
00134     }
00135   };
00136 }
00137 
00138 /// ScanForSpillSlotRefs - Scan all the machine instructions for spill slot
00139 /// references and update spill slot weights.
00140 void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) {
00141   SSRefs.resize(MFI->getObjectIndexEnd());
00142 
00143   // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
00144   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
00145        MBBI != E; ++MBBI) {
00146     MachineBasicBlock *MBB = &*MBBI;
00147     for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
00148          MII != EE; ++MII) {
00149       MachineInstr *MI = &*MII;
00150       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00151         MachineOperand &MO = MI->getOperand(i);
00152         if (!MO.isFI())
00153           continue;
00154         int FI = MO.getIndex();
00155         if (FI < 0)
00156           continue;
00157         if (!LS->hasInterval(FI))
00158           continue;
00159         LiveInterval &li = LS->getInterval(FI);
00160         if (!MI->isDebugValue())
00161           li.weight += LiveIntervals::getSpillWeight(false, true, MBFI, MI);
00162       }
00163       for (MachineInstr::mmo_iterator MMOI = MI->memoperands_begin(),
00164            EE = MI->memoperands_end(); MMOI != EE; ++MMOI) {
00165         MachineMemOperand *MMO = *MMOI;
00166         if (const FixedStackPseudoSourceValue *FSV =
00167             dyn_cast_or_null<FixedStackPseudoSourceValue>(
00168                 MMO->getPseudoValue())) {
00169           int FI = FSV->getFrameIndex();
00170           if (FI >= 0)
00171             SSRefs[FI].push_back(MMO);
00172         }
00173       }
00174     }
00175   }
00176 }
00177 
00178 /// InitializeSlots - Process all spill stack slot liveintervals and add them
00179 /// to a sorted (by weight) list.
00180 void StackSlotColoring::InitializeSlots() {
00181   int LastFI = MFI->getObjectIndexEnd();
00182   OrigAlignments.resize(LastFI);
00183   OrigSizes.resize(LastFI);
00184   AllColors.resize(LastFI);
00185   UsedColors.resize(LastFI);
00186   Assignments.resize(LastFI);
00187 
00188   // Gather all spill slots into a list.
00189   DEBUG(dbgs() << "Spill slot intervals:\n");
00190   for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
00191     LiveInterval &li = i->second;
00192     DEBUG(li.dump());
00193     int FI = TargetRegisterInfo::stackSlot2Index(li.reg);
00194     if (MFI->isDeadObjectIndex(FI))
00195       continue;
00196     SSIntervals.push_back(&li);
00197     OrigAlignments[FI] = MFI->getObjectAlignment(FI);
00198     OrigSizes[FI]      = MFI->getObjectSize(FI);
00199     AllColors.set(FI);
00200   }
00201   DEBUG(dbgs() << '\n');
00202 
00203   // Sort them by weight.
00204   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
00205 
00206   // Get first "color".
00207   NextColor = AllColors.find_first();
00208 }
00209 
00210 /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
00211 /// LiveIntervals that have already been assigned to the specified color.
00212 bool
00213 StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
00214   const SmallVectorImpl<LiveInterval *> &OtherLIs = Assignments[Color];
00215   for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
00216     LiveInterval *OtherLI = OtherLIs[i];
00217     if (OtherLI->overlaps(*li))
00218       return true;
00219   }
00220   return false;
00221 }
00222 
00223 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
00224 ///
00225 int StackSlotColoring::ColorSlot(LiveInterval *li) {
00226   int Color = -1;
00227   bool Share = false;
00228   if (!DisableSharing) {
00229     // Check if it's possible to reuse any of the used colors.
00230     Color = UsedColors.find_first();
00231     while (Color != -1) {
00232       if (!OverlapWithAssignments(li, Color)) {
00233         Share = true;
00234         ++NumEliminated;
00235         break;
00236       }
00237       Color = UsedColors.find_next(Color);
00238     }
00239   }
00240 
00241   // Assign it to the first available color (assumed to be the best) if it's
00242   // not possible to share a used color with other objects.
00243   if (!Share) {
00244     assert(NextColor != -1 && "No more spill slots?");
00245     Color = NextColor;
00246     UsedColors.set(Color);
00247     NextColor = AllColors.find_next(NextColor);
00248   }
00249 
00250   // Record the assignment.
00251   Assignments[Color].push_back(li);
00252   int FI = TargetRegisterInfo::stackSlot2Index(li->reg);
00253   DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n");
00254 
00255   // Change size and alignment of the allocated slot. If there are multiple
00256   // objects sharing the same slot, then make sure the size and alignment
00257   // are large enough for all.
00258   unsigned Align = OrigAlignments[FI];
00259   if (!Share || Align > MFI->getObjectAlignment(Color))
00260     MFI->setObjectAlignment(Color, Align);
00261   int64_t Size = OrigSizes[FI];
00262   if (!Share || Size > MFI->getObjectSize(Color))
00263     MFI->setObjectSize(Color, Size);
00264   return Color;
00265 }
00266 
00267 /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
00268 /// operands in the function.
00269 bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
00270   unsigned NumObjs = MFI->getObjectIndexEnd();
00271   SmallVector<int, 16> SlotMapping(NumObjs, -1);
00272   SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
00273   SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
00274   BitVector UsedColors(NumObjs);
00275 
00276   DEBUG(dbgs() << "Color spill slot intervals:\n");
00277   bool Changed = false;
00278   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
00279     LiveInterval *li = SSIntervals[i];
00280     int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
00281     int NewSS = ColorSlot(li);
00282     assert(NewSS >= 0 && "Stack coloring failed?");
00283     SlotMapping[SS] = NewSS;
00284     RevMap[NewSS].push_back(SS);
00285     SlotWeights[NewSS] += li->weight;
00286     UsedColors.set(NewSS);
00287     Changed |= (SS != NewSS);
00288   }
00289 
00290   DEBUG(dbgs() << "\nSpill slots after coloring:\n");
00291   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
00292     LiveInterval *li = SSIntervals[i];
00293     int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
00294     li->weight = SlotWeights[SS];
00295   }
00296   // Sort them by new weight.
00297   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
00298 
00299 #ifndef NDEBUG
00300   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
00301     DEBUG(SSIntervals[i]->dump());
00302   DEBUG(dbgs() << '\n');
00303 #endif
00304 
00305   if (!Changed)
00306     return false;
00307 
00308   // Rewrite all MachineMemOperands.
00309   for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
00310     int NewFI = SlotMapping[SS];
00311     if (NewFI == -1 || (NewFI == (int)SS))
00312       continue;
00313 
00314     const PseudoSourceValue *NewSV = PseudoSourceValue::getFixedStack(NewFI);
00315     SmallVectorImpl<MachineMemOperand *> &RefMMOs = SSRefs[SS];
00316     for (unsigned i = 0, e = RefMMOs.size(); i != e; ++i)
00317       RefMMOs[i]->setValue(NewSV);
00318   }
00319 
00320   // Rewrite all MO_FrameIndex operands.  Look for dead stores.
00321   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
00322        MBBI != E; ++MBBI) {
00323     MachineBasicBlock *MBB = &*MBBI;
00324     for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
00325          MII != EE; ++MII)
00326       RewriteInstruction(MII, SlotMapping, MF);
00327     RemoveDeadStores(MBB);
00328   }
00329 
00330   // Delete unused stack slots.
00331   while (NextColor != -1) {
00332     DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n");
00333     MFI->RemoveStackObject(NextColor);
00334     NextColor = AllColors.find_next(NextColor);
00335   }
00336 
00337   return true;
00338 }
00339 
00340 /// RewriteInstruction - Rewrite specified instruction by replacing references
00341 /// to old frame index with new one.
00342 void StackSlotColoring::RewriteInstruction(MachineInstr *MI,
00343                                            SmallVectorImpl<int> &SlotMapping,
00344                                            MachineFunction &MF) {
00345   // Update the operands.
00346   for (unsigned i = 0, ee = MI->getNumOperands(); i != ee; ++i) {
00347     MachineOperand &MO = MI->getOperand(i);
00348     if (!MO.isFI())
00349       continue;
00350     int OldFI = MO.getIndex();
00351     if (OldFI < 0)
00352       continue;
00353     int NewFI = SlotMapping[OldFI];
00354     if (NewFI == -1 || NewFI == OldFI)
00355       continue;
00356     MO.setIndex(NewFI);
00357   }
00358 
00359   // The MachineMemOperands have already been updated.
00360 }
00361 
00362 
00363 /// RemoveDeadStores - Scan through a basic block and look for loads followed
00364 /// by stores.  If they're both using the same stack slot, then the store is
00365 /// definitely dead.  This could obviously be much more aggressive (consider
00366 /// pairs with instructions between them), but such extensions might have a
00367 /// considerable compile time impact.
00368 bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
00369   // FIXME: This could be much more aggressive, but we need to investigate
00370   // the compile time impact of doing so.
00371   bool changed = false;
00372 
00373   SmallVector<MachineInstr*, 4> toErase;
00374 
00375   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
00376        I != E; ++I) {
00377     if (DCELimit != -1 && (int)NumDead >= DCELimit)
00378       break;
00379 
00380     int FirstSS, SecondSS;
00381     if (TII->isStackSlotCopy(I, FirstSS, SecondSS) &&
00382         FirstSS == SecondSS &&
00383         FirstSS != -1) {
00384       ++NumDead;
00385       changed = true;
00386       toErase.push_back(I);
00387       continue;
00388     }
00389 
00390     MachineBasicBlock::iterator NextMI = std::next(I);
00391     if (NextMI == MBB->end()) continue;
00392 
00393     unsigned LoadReg = 0;
00394     unsigned StoreReg = 0;
00395     if (!(LoadReg = TII->isLoadFromStackSlot(I, FirstSS))) continue;
00396     if (!(StoreReg = TII->isStoreToStackSlot(NextMI, SecondSS))) continue;
00397     if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1) continue;
00398 
00399     ++NumDead;
00400     changed = true;
00401 
00402     if (NextMI->findRegisterUseOperandIdx(LoadReg, true, nullptr) != -1) {
00403       ++NumDead;
00404       toErase.push_back(I);
00405     }
00406 
00407     toErase.push_back(NextMI);
00408     ++I;
00409   }
00410 
00411   for (SmallVectorImpl<MachineInstr *>::iterator I = toErase.begin(),
00412        E = toErase.end(); I != E; ++I)
00413     (*I)->eraseFromParent();
00414 
00415   return changed;
00416 }
00417 
00418 
00419 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
00420   DEBUG({
00421       dbgs() << "********** Stack Slot Coloring **********\n"
00422              << "********** Function: " << MF.getName() << '\n';
00423     });
00424 
00425   MFI = MF.getFrameInfo();
00426   TII = MF.getSubtarget().getInstrInfo();
00427   LS = &getAnalysis<LiveStacks>();
00428   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
00429 
00430   bool Changed = false;
00431 
00432   unsigned NumSlots = LS->getNumIntervals();
00433   if (NumSlots == 0)
00434     // Nothing to do!
00435     return false;
00436 
00437   // If there are calls to setjmp or sigsetjmp, don't perform stack slot
00438   // coloring. The stack could be modified before the longjmp is executed,
00439   // resulting in the wrong value being used afterwards. (See
00440   // <rdar://problem/8007500>.)
00441   if (MF.exposesReturnsTwice())
00442     return false;
00443 
00444   // Gather spill slot references
00445   ScanForSpillSlotRefs(MF);
00446   InitializeSlots();
00447   Changed = ColorSlots(MF);
00448 
00449   NextColor = -1;
00450   SSIntervals.clear();
00451   for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
00452     SSRefs[i].clear();
00453   SSRefs.clear();
00454   OrigAlignments.clear();
00455   OrigSizes.clear();
00456   AllColors.clear();
00457   UsedColors.clear();
00458   for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
00459     Assignments[i].clear();
00460   Assignments.clear();
00461 
00462   return Changed;
00463 }