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