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   typedef std::multimap<const Comdat *, GlobalValue *> ComdatGVPairsTy;
00082   ComdatGVPairsTy ComdatGVPairs;
00083 
00084   // Loop over the module, adding globals which are obviously necessary.
00085   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00086     Changed |= RemoveUnusedGlobalValue(*I);
00087     // Functions with external linkage are needed if they have a body
00088     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
00089       if (!I->isDiscardableIfUnused())
00090         GlobalIsNeeded(I);
00091       else if (const Comdat *C = I->getComdat())
00092         ComdatGVPairs.insert(std::make_pair(C, I));
00093     }
00094   }
00095 
00096   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00097        I != E; ++I) {
00098     Changed |= RemoveUnusedGlobalValue(*I);
00099     // Externally visible & appending globals are needed, if they have an
00100     // initializer.
00101     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
00102       if (!I->isDiscardableIfUnused())
00103         GlobalIsNeeded(I);
00104       else if (const Comdat *C = I->getComdat())
00105         ComdatGVPairs.insert(std::make_pair(C, I));
00106     }
00107   }
00108 
00109   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
00110        I != E; ++I) {
00111     Changed |= RemoveUnusedGlobalValue(*I);
00112     // Externally visible aliases are needed.
00113     if (!I->isDiscardableIfUnused()) {
00114       GlobalIsNeeded(I);
00115     } else if (const Comdat *C = I->getComdat()) {
00116       ComdatGVPairs.insert(std::make_pair(C, I));
00117     }
00118   }
00119 
00120   for (ComdatGVPairsTy::iterator I = ComdatGVPairs.begin(),
00121                                  E = ComdatGVPairs.end();
00122        I != E;) {
00123     ComdatGVPairsTy::iterator UB = ComdatGVPairs.upper_bound(I->first);
00124     bool CanDiscard = std::all_of(I, UB, [](ComdatGVPairsTy::value_type Pair) {
00125       return Pair.second->isDiscardableIfUnused();
00126     });
00127     if (!CanDiscard) {
00128       std::for_each(I, UB, [this](ComdatGVPairsTy::value_type Pair) {
00129         GlobalIsNeeded(Pair.second);
00130       });
00131     }
00132     I = UB;
00133   }
00134 
00135   // Now that all globals which are needed are in the AliveGlobals set, we loop
00136   // through the program, deleting those which are not alive.
00137   //
00138 
00139   // The first pass is to drop initializers of global variables which are dead.
00140   std::vector<GlobalVariable*> DeadGlobalVars;   // Keep track of dead globals
00141   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00142        I != E; ++I)
00143     if (!AliveGlobals.count(I)) {
00144       DeadGlobalVars.push_back(I);         // Keep track of dead globals
00145       if (I->hasInitializer()) {
00146         Constant *Init = I->getInitializer();
00147         I->setInitializer(nullptr);
00148         if (isSafeToDestroyConstant(Init))
00149           Init->destroyConstant();
00150       }
00151     }
00152 
00153   // The second pass drops the bodies of functions which are dead...
00154   std::vector<Function*> DeadFunctions;
00155   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
00156     if (!AliveGlobals.count(I)) {
00157       DeadFunctions.push_back(I);         // Keep track of dead globals
00158       if (!I->isDeclaration())
00159         I->deleteBody();
00160     }
00161 
00162   // The third pass drops targets of aliases which are dead...
00163   std::vector<GlobalAlias*> DeadAliases;
00164   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
00165        ++I)
00166     if (!AliveGlobals.count(I)) {
00167       DeadAliases.push_back(I);
00168       I->setAliasee(nullptr);
00169     }
00170 
00171   if (!DeadFunctions.empty()) {
00172     // Now that all interferences have been dropped, delete the actual objects
00173     // themselves.
00174     for (unsigned i = 0, e = DeadFunctions.size(); i != e; ++i) {
00175       RemoveUnusedGlobalValue(*DeadFunctions[i]);
00176       M.getFunctionList().erase(DeadFunctions[i]);
00177     }
00178     NumFunctions += DeadFunctions.size();
00179     Changed = true;
00180   }
00181 
00182   if (!DeadGlobalVars.empty()) {
00183     for (unsigned i = 0, e = DeadGlobalVars.size(); i != e; ++i) {
00184       RemoveUnusedGlobalValue(*DeadGlobalVars[i]);
00185       M.getGlobalList().erase(DeadGlobalVars[i]);
00186     }
00187     NumVariables += DeadGlobalVars.size();
00188     Changed = true;
00189   }
00190 
00191   // Now delete any dead aliases.
00192   if (!DeadAliases.empty()) {
00193     for (unsigned i = 0, e = DeadAliases.size(); i != e; ++i) {
00194       RemoveUnusedGlobalValue(*DeadAliases[i]);
00195       M.getAliasList().erase(DeadAliases[i]);
00196     }
00197     NumAliases += DeadAliases.size();
00198     Changed = true;
00199   }
00200 
00201   // Make sure that all memory is released
00202   AliveGlobals.clear();
00203   SeenConstants.clear();
00204 
00205   return Changed;
00206 }
00207 
00208 /// GlobalIsNeeded - the specific global value as needed, and
00209 /// recursively mark anything that it uses as also needed.
00210 void GlobalDCE::GlobalIsNeeded(GlobalValue *G) {
00211   // If the global is already in the set, no need to reprocess it.
00212   if (!AliveGlobals.insert(G))
00213     return;
00214   
00215   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
00216     // If this is a global variable, we must make sure to add any global values
00217     // referenced by the initializer to the alive set.
00218     if (GV->hasInitializer())
00219       MarkUsedGlobalsAsNeeded(GV->getInitializer());
00220   } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(G)) {
00221     // The target of a global alias is needed.
00222     MarkUsedGlobalsAsNeeded(GA->getAliasee());
00223   } else {
00224     // Otherwise this must be a function object.  We have to scan the body of
00225     // the function looking for constants and global values which are used as
00226     // operands.  Any operands of these types must be processed to ensure that
00227     // any globals used will be marked as needed.
00228     Function *F = cast<Function>(G);
00229 
00230     if (F->hasPrefixData())
00231       MarkUsedGlobalsAsNeeded(F->getPrefixData());
00232 
00233     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00234       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00235         for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U)
00236           if (GlobalValue *GV = dyn_cast<GlobalValue>(*U))
00237             GlobalIsNeeded(GV);
00238           else if (Constant *C = dyn_cast<Constant>(*U))
00239             MarkUsedGlobalsAsNeeded(C);
00240   }
00241 }
00242 
00243 void GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) {
00244   if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
00245     return GlobalIsNeeded(GV);
00246 
00247   // Loop over all of the operands of the constant, adding any globals they
00248   // use to the list of needed globals.
00249   for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I) {
00250     // If we've already processed this constant there's no need to do it again.
00251     Constant *Op = dyn_cast<Constant>(*I);
00252     if (Op && SeenConstants.insert(Op))
00253       MarkUsedGlobalsAsNeeded(Op);
00254   }
00255 }
00256 
00257 // RemoveUnusedGlobalValue - Loop over all of the uses of the specified
00258 // GlobalValue, looking for the constant pointer ref that may be pointing to it.
00259 // If found, check to see if the constant pointer ref is safe to destroy, and if
00260 // so, nuke it.  This will reduce the reference count on the global value, which
00261 // might make it deader.
00262 //
00263 bool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) {
00264   if (GV.use_empty()) return false;
00265   GV.removeDeadConstantUsers();
00266   return GV.use_empty();
00267 }