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