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