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