LLVM API Documentation

GlobalDCE.cpp
Go to the documentation of this file.
00001 //===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
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 transform is designed to eliminate unreachable internal globals from the
00011 // program.  It uses an aggressive algorithm, searching out globals that are
00012 // known to be alive.  After it finds all of the globals which are needed, it
00013 // deletes whatever is left over.  This allows it to delete recursive chunks of
00014 // the program which are unreachable.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #include "llvm/Transforms/IPO.h"
00019 #include "llvm/ADT/SmallPtrSet.h"
00020 #include "llvm/ADT/Statistic.h"
00021 #include "llvm/IR/Constants.h"
00022 #include "llvm/IR/Instructions.h"
00023 #include "llvm/IR/Module.h"
00024 #include "llvm/Transforms/Utils/CtorUtils.h"
00025 #include "llvm/Transforms/Utils/GlobalStatus.h"
00026 #include "llvm/Pass.h"
00027 using namespace llvm;
00028 
00029 #define DEBUG_TYPE "globaldce"
00030 
00031 STATISTIC(NumAliases  , "Number of global aliases removed");
00032 STATISTIC(NumFunctions, "Number of functions removed");
00033 STATISTIC(NumVariables, "Number of global variables removed");
00034 
00035 namespace {
00036   struct GlobalDCE : public ModulePass {
00037     static char ID; // Pass identification, replacement for typeid
00038     GlobalDCE() : ModulePass(ID) {
00039       initializeGlobalDCEPass(*PassRegistry::getPassRegistry());
00040     }
00041 
00042     // run - Do the GlobalDCE pass on the specified module, optionally updating
00043     // the specified callgraph to reflect the changes.
00044     //
00045     bool runOnModule(Module &M) override;
00046 
00047   private:
00048     SmallPtrSet<GlobalValue*, 32> AliveGlobals;
00049     SmallPtrSet<Constant *, 8> SeenConstants;
00050 
00051     /// GlobalIsNeeded - mark the specific global value as needed, and
00052     /// recursively mark anything that it uses as also needed.
00053     void GlobalIsNeeded(GlobalValue *GV);
00054     void MarkUsedGlobalsAsNeeded(Constant *C);
00055 
00056     bool RemoveUnusedGlobalValue(GlobalValue &GV);
00057   };
00058 }
00059 
00060 /// Returns true if F contains only a single "ret" instruction.
00061 static bool isEmptyFunction(Function *F) {
00062   BasicBlock &Entry = F->getEntryBlock();
00063   if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front()))
00064     return false;
00065   ReturnInst &RI = cast<ReturnInst>(Entry.front());
00066   return RI.getReturnValue() == nullptr;
00067 }
00068 
00069 char GlobalDCE::ID = 0;
00070 INITIALIZE_PASS(GlobalDCE, "globaldce",
00071                 "Dead Global Elimination", false, false)
00072 
00073 ModulePass *llvm::createGlobalDCEPass() { return new GlobalDCE(); }
00074 
00075 bool GlobalDCE::runOnModule(Module &M) {
00076   bool Changed = false;
00077 
00078   // Remove empty functions from the global ctors list.
00079   Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
00080 
00081   // Loop over the module, adding globals which are obviously necessary.
00082   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00083     Changed |= RemoveUnusedGlobalValue(*I);
00084     // Functions with external linkage are needed if they have a body
00085     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
00086       if (!I->isDiscardableIfUnused())
00087         GlobalIsNeeded(I);
00088     }
00089   }
00090 
00091   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00092        I != E; ++I) {
00093     Changed |= RemoveUnusedGlobalValue(*I);
00094     // Externally visible & appending globals are needed, if they have an
00095     // initializer.
00096     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
00097       if (!I->isDiscardableIfUnused())
00098         GlobalIsNeeded(I);
00099     }
00100   }
00101 
00102   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
00103        I != E; ++I) {
00104     Changed |= RemoveUnusedGlobalValue(*I);
00105     // Externally visible aliases are needed.
00106     if (!I->isDiscardableIfUnused()) {
00107       GlobalIsNeeded(I);
00108     }
00109   }
00110 
00111   // Now that all globals which are needed are in the AliveGlobals set, we loop
00112   // through the program, deleting those which are not alive.
00113   //
00114 
00115   // The first pass is to drop initializers of global variables which are dead.
00116   std::vector<GlobalVariable*> DeadGlobalVars;   // Keep track of dead globals
00117   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00118        I != E; ++I)
00119     if (!AliveGlobals.count(I)) {
00120       DeadGlobalVars.push_back(I);         // Keep track of dead globals
00121       if (I->hasInitializer()) {
00122         Constant *Init = I->getInitializer();
00123         I->setInitializer(nullptr);
00124         if (isSafeToDestroyConstant(Init))
00125           Init->destroyConstant();
00126       }
00127     }
00128 
00129   // The second pass drops the bodies of functions which are dead...
00130   std::vector<Function*> DeadFunctions;
00131   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
00132     if (!AliveGlobals.count(I)) {
00133       DeadFunctions.push_back(I);         // Keep track of dead globals
00134       if (!I->isDeclaration())
00135         I->deleteBody();
00136     }
00137 
00138   // The third pass drops targets of aliases which are dead...
00139   std::vector<GlobalAlias*> DeadAliases;
00140   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
00141        ++I)
00142     if (!AliveGlobals.count(I)) {
00143       DeadAliases.push_back(I);
00144       I->setAliasee(nullptr);
00145     }
00146 
00147   if (!DeadFunctions.empty()) {
00148     // Now that all interferences have been dropped, delete the actual objects
00149     // themselves.
00150     for (unsigned i = 0, e = DeadFunctions.size(); i != e; ++i) {
00151       RemoveUnusedGlobalValue(*DeadFunctions[i]);
00152       M.getFunctionList().erase(DeadFunctions[i]);
00153     }
00154     NumFunctions += DeadFunctions.size();
00155     Changed = true;
00156   }
00157 
00158   if (!DeadGlobalVars.empty()) {
00159     for (unsigned i = 0, e = DeadGlobalVars.size(); i != e; ++i) {
00160       RemoveUnusedGlobalValue(*DeadGlobalVars[i]);
00161       M.getGlobalList().erase(DeadGlobalVars[i]);
00162     }
00163     NumVariables += DeadGlobalVars.size();
00164     Changed = true;
00165   }
00166 
00167   // Now delete any dead aliases.
00168   if (!DeadAliases.empty()) {
00169     for (unsigned i = 0, e = DeadAliases.size(); i != e; ++i) {
00170       RemoveUnusedGlobalValue(*DeadAliases[i]);
00171       M.getAliasList().erase(DeadAliases[i]);
00172     }
00173     NumAliases += DeadAliases.size();
00174     Changed = true;
00175   }
00176 
00177   // Make sure that all memory is released
00178   AliveGlobals.clear();
00179   SeenConstants.clear();
00180 
00181   return Changed;
00182 }
00183 
00184 /// GlobalIsNeeded - the specific global value as needed, and
00185 /// recursively mark anything that it uses as also needed.
00186 void GlobalDCE::GlobalIsNeeded(GlobalValue *G) {
00187   // If the global is already in the set, no need to reprocess it.
00188   if (!AliveGlobals.insert(G).second)
00189     return;
00190 
00191   Module *M = G->getParent();
00192   if (Comdat *C = G->getComdat()) {
00193     for (Function &F : *M)
00194       if (F.getComdat() == C)
00195         GlobalIsNeeded(&F);
00196     for (GlobalVariable &GV : M->globals())
00197       if (GV.getComdat() == C)
00198         GlobalIsNeeded(&GV);
00199     for (GlobalAlias &GA : M->aliases())
00200       if (GA.getComdat() == C)
00201         GlobalIsNeeded(&GA);
00202   }
00203 
00204   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
00205     // If this is a global variable, we must make sure to add any global values
00206     // referenced by the initializer to the alive set.
00207     if (GV->hasInitializer())
00208       MarkUsedGlobalsAsNeeded(GV->getInitializer());
00209   } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(G)) {
00210     // The target of a global alias is needed.
00211     MarkUsedGlobalsAsNeeded(GA->getAliasee());
00212   } else {
00213     // Otherwise this must be a function object.  We have to scan the body of
00214     // the function looking for constants and global values which are used as
00215     // operands.  Any operands of these types must be processed to ensure that
00216     // any globals used will be marked as needed.
00217     Function *F = cast<Function>(G);
00218 
00219     if (F->hasPrefixData())
00220       MarkUsedGlobalsAsNeeded(F->getPrefixData());
00221 
00222     if (F->hasPrologueData())
00223       MarkUsedGlobalsAsNeeded(F->getPrologueData());
00224 
00225     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00226       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00227         for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U)
00228           if (GlobalValue *GV = dyn_cast<GlobalValue>(*U))
00229             GlobalIsNeeded(GV);
00230           else if (Constant *C = dyn_cast<Constant>(*U))
00231             MarkUsedGlobalsAsNeeded(C);
00232   }
00233 }
00234 
00235 void GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) {
00236   if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
00237     return GlobalIsNeeded(GV);
00238 
00239   // Loop over all of the operands of the constant, adding any globals they
00240   // use to the list of needed globals.
00241   for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I) {
00242     // If we've already processed this constant there's no need to do it again.
00243     Constant *Op = dyn_cast<Constant>(*I);
00244     if (Op && SeenConstants.insert(Op).second)
00245       MarkUsedGlobalsAsNeeded(Op);
00246   }
00247 }
00248 
00249 // RemoveUnusedGlobalValue - Loop over all of the uses of the specified
00250 // GlobalValue, looking for the constant pointer ref that may be pointing to it.
00251 // If found, check to see if the constant pointer ref is safe to destroy, and if
00252 // so, nuke it.  This will reduce the reference count on the global value, which
00253 // might make it deader.
00254 //
00255 bool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) {
00256   if (GV.use_empty()) return false;
00257   GV.removeDeadConstantUsers();
00258   return GV.use_empty();
00259 }