Home | History | Annotate | Download | only in IPO
      1 //===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This transform is designed to eliminate unreachable internal globals from the
     11 // program.  It uses an aggressive algorithm, searching out globals that are
     12 // known to be alive.  After it finds all of the globals which are needed, it
     13 // deletes whatever is left over.  This allows it to delete recursive chunks of
     14 // the program which are unreachable.
     15 //
     16 //===----------------------------------------------------------------------===//
     17 
     18 #include "llvm/Transforms/IPO/GlobalDCE.h"
     19 #include "llvm/ADT/SmallPtrSet.h"
     20 #include "llvm/ADT/Statistic.h"
     21 #include "llvm/IR/Constants.h"
     22 #include "llvm/IR/Instructions.h"
     23 #include "llvm/IR/Module.h"
     24 #include "llvm/Pass.h"
     25 #include "llvm/Transforms/IPO.h"
     26 #include "llvm/Transforms/Utils/CtorUtils.h"
     27 #include "llvm/Transforms/Utils/GlobalStatus.h"
     28 #include <unordered_map>
     29 using namespace llvm;
     30 
     31 #define DEBUG_TYPE "globaldce"
     32 
     33 STATISTIC(NumAliases  , "Number of global aliases removed");
     34 STATISTIC(NumFunctions, "Number of functions removed");
     35 STATISTIC(NumIFuncs,    "Number of indirect functions removed");
     36 STATISTIC(NumVariables, "Number of global variables removed");
     37 
     38 namespace {
     39   class GlobalDCELegacyPass : public ModulePass {
     40   public:
     41     static char ID; // Pass identification, replacement for typeid
     42     GlobalDCELegacyPass() : ModulePass(ID) {
     43       initializeGlobalDCELegacyPassPass(*PassRegistry::getPassRegistry());
     44     }
     45 
     46     // run - Do the GlobalDCE pass on the specified module, optionally updating
     47     // the specified callgraph to reflect the changes.
     48     //
     49     bool runOnModule(Module &M) override {
     50       if (skipModule(M))
     51         return false;
     52 
     53       ModuleAnalysisManager DummyMAM;
     54       auto PA = Impl.run(M, DummyMAM);
     55       return !PA.areAllPreserved();
     56     }
     57 
     58   private:
     59     GlobalDCEPass Impl;
     60   };
     61 }
     62 
     63 char GlobalDCELegacyPass::ID = 0;
     64 INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce",
     65                 "Dead Global Elimination", false, false)
     66 
     67 // Public interface to the GlobalDCEPass.
     68 ModulePass *llvm::createGlobalDCEPass() {
     69   return new GlobalDCELegacyPass();
     70 }
     71 
     72 /// Returns true if F contains only a single "ret" instruction.
     73 static bool isEmptyFunction(Function *F) {
     74   BasicBlock &Entry = F->getEntryBlock();
     75   if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front()))
     76     return false;
     77   ReturnInst &RI = cast<ReturnInst>(Entry.front());
     78   return RI.getReturnValue() == nullptr;
     79 }
     80 
     81 PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &) {
     82   bool Changed = false;
     83 
     84   // Remove empty functions from the global ctors list.
     85   Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
     86 
     87   // Collect the set of members for each comdat.
     88   for (Function &F : M)
     89     if (Comdat *C = F.getComdat())
     90       ComdatMembers.insert(std::make_pair(C, &F));
     91   for (GlobalVariable &GV : M.globals())
     92     if (Comdat *C = GV.getComdat())
     93       ComdatMembers.insert(std::make_pair(C, &GV));
     94   for (GlobalAlias &GA : M.aliases())
     95     if (Comdat *C = GA.getComdat())
     96       ComdatMembers.insert(std::make_pair(C, &GA));
     97 
     98   // Loop over the module, adding globals which are obviously necessary.
     99   for (GlobalObject &GO : M.global_objects()) {
    100     Changed |= RemoveUnusedGlobalValue(GO);
    101     // Functions with external linkage are needed if they have a body.
    102     // Externally visible & appending globals are needed, if they have an
    103     // initializer.
    104     if (!GO.isDeclaration() && !GO.hasAvailableExternallyLinkage())
    105       if (!GO.isDiscardableIfUnused())
    106         GlobalIsNeeded(&GO);
    107   }
    108 
    109   for (GlobalAlias &GA : M.aliases()) {
    110     Changed |= RemoveUnusedGlobalValue(GA);
    111     // Externally visible aliases are needed.
    112     if (!GA.isDiscardableIfUnused())
    113       GlobalIsNeeded(&GA);
    114   }
    115 
    116   for (GlobalIFunc &GIF : M.ifuncs()) {
    117     Changed |= RemoveUnusedGlobalValue(GIF);
    118     // Externally visible ifuncs are needed.
    119     if (!GIF.isDiscardableIfUnused())
    120       GlobalIsNeeded(&GIF);
    121   }
    122 
    123   // Now that all globals which are needed are in the AliveGlobals set, we loop
    124   // through the program, deleting those which are not alive.
    125   //
    126 
    127   // The first pass is to drop initializers of global variables which are dead.
    128   std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
    129   for (GlobalVariable &GV : M.globals())
    130     if (!AliveGlobals.count(&GV)) {
    131       DeadGlobalVars.push_back(&GV);         // Keep track of dead globals
    132       if (GV.hasInitializer()) {
    133         Constant *Init = GV.getInitializer();
    134         GV.setInitializer(nullptr);
    135         if (isSafeToDestroyConstant(Init))
    136           Init->destroyConstant();
    137       }
    138     }
    139 
    140   // The second pass drops the bodies of functions which are dead...
    141   std::vector<Function *> DeadFunctions;
    142   for (Function &F : M)
    143     if (!AliveGlobals.count(&F)) {
    144       DeadFunctions.push_back(&F);         // Keep track of dead globals
    145       if (!F.isDeclaration())
    146         F.deleteBody();
    147     }
    148 
    149   // The third pass drops targets of aliases which are dead...
    150   std::vector<GlobalAlias*> DeadAliases;
    151   for (GlobalAlias &GA : M.aliases())
    152     if (!AliveGlobals.count(&GA)) {
    153       DeadAliases.push_back(&GA);
    154       GA.setAliasee(nullptr);
    155     }
    156 
    157   // The third pass drops targets of ifuncs which are dead...
    158   std::vector<GlobalIFunc*> DeadIFuncs;
    159   for (GlobalIFunc &GIF : M.ifuncs())
    160     if (!AliveGlobals.count(&GIF)) {
    161       DeadIFuncs.push_back(&GIF);
    162       GIF.setResolver(nullptr);
    163     }
    164 
    165   if (!DeadFunctions.empty()) {
    166     // Now that all interferences have been dropped, delete the actual objects
    167     // themselves.
    168     for (Function *F : DeadFunctions) {
    169       RemoveUnusedGlobalValue(*F);
    170       M.getFunctionList().erase(F);
    171     }
    172     NumFunctions += DeadFunctions.size();
    173     Changed = true;
    174   }
    175 
    176   if (!DeadGlobalVars.empty()) {
    177     for (GlobalVariable *GV : DeadGlobalVars) {
    178       RemoveUnusedGlobalValue(*GV);
    179       M.getGlobalList().erase(GV);
    180     }
    181     NumVariables += DeadGlobalVars.size();
    182     Changed = true;
    183   }
    184 
    185   // Now delete any dead aliases.
    186   if (!DeadAliases.empty()) {
    187     for (GlobalAlias *GA : DeadAliases) {
    188       RemoveUnusedGlobalValue(*GA);
    189       M.getAliasList().erase(GA);
    190     }
    191     NumAliases += DeadAliases.size();
    192     Changed = true;
    193   }
    194 
    195   // Now delete any dead aliases.
    196   if (!DeadIFuncs.empty()) {
    197     for (GlobalIFunc *GIF : DeadIFuncs) {
    198       RemoveUnusedGlobalValue(*GIF);
    199       M.getIFuncList().erase(GIF);
    200     }
    201     NumIFuncs += DeadIFuncs.size();
    202     Changed = true;
    203   }
    204 
    205   // Make sure that all memory is released
    206   AliveGlobals.clear();
    207   SeenConstants.clear();
    208   ComdatMembers.clear();
    209 
    210   if (Changed)
    211     return PreservedAnalyses::none();
    212   return PreservedAnalyses::all();
    213 }
    214 
    215 /// GlobalIsNeeded - the specific global value as needed, and
    216 /// recursively mark anything that it uses as also needed.
    217 void GlobalDCEPass::GlobalIsNeeded(GlobalValue *G) {
    218   // If the global is already in the set, no need to reprocess it.
    219   if (!AliveGlobals.insert(G).second)
    220     return;
    221 
    222   if (Comdat *C = G->getComdat()) {
    223     for (auto &&CM : make_range(ComdatMembers.equal_range(C)))
    224       GlobalIsNeeded(CM.second);
    225   }
    226 
    227   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
    228     // If this is a global variable, we must make sure to add any global values
    229     // referenced by the initializer to the alive set.
    230     if (GV->hasInitializer())
    231       MarkUsedGlobalsAsNeeded(GV->getInitializer());
    232   } else if (GlobalIndirectSymbol *GIS = dyn_cast<GlobalIndirectSymbol>(G)) {
    233     // The target of a global alias or ifunc is needed.
    234     MarkUsedGlobalsAsNeeded(GIS->getIndirectSymbol());
    235   } else {
    236     // Otherwise this must be a function object.  We have to scan the body of
    237     // the function looking for constants and global values which are used as
    238     // operands.  Any operands of these types must be processed to ensure that
    239     // any globals used will be marked as needed.
    240     Function *F = cast<Function>(G);
    241 
    242     for (Use &U : F->operands())
    243       MarkUsedGlobalsAsNeeded(cast<Constant>(U.get()));
    244 
    245     for (BasicBlock &BB : *F)
    246       for (Instruction &I : BB)
    247         for (Use &U : I.operands())
    248           if (GlobalValue *GV = dyn_cast<GlobalValue>(U))
    249             GlobalIsNeeded(GV);
    250           else if (Constant *C = dyn_cast<Constant>(U))
    251             MarkUsedGlobalsAsNeeded(C);
    252   }
    253 }
    254 
    255 void GlobalDCEPass::MarkUsedGlobalsAsNeeded(Constant *C) {
    256   if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
    257     return GlobalIsNeeded(GV);
    258 
    259   // Loop over all of the operands of the constant, adding any globals they
    260   // use to the list of needed globals.
    261   for (Use &U : C->operands()) {
    262     // If we've already processed this constant there's no need to do it again.
    263     Constant *Op = dyn_cast<Constant>(U);
    264     if (Op && SeenConstants.insert(Op).second)
    265       MarkUsedGlobalsAsNeeded(Op);
    266   }
    267 }
    268 
    269 // RemoveUnusedGlobalValue - Loop over all of the uses of the specified
    270 // GlobalValue, looking for the constant pointer ref that may be pointing to it.
    271 // If found, check to see if the constant pointer ref is safe to destroy, and if
    272 // so, nuke it.  This will reduce the reference count on the global value, which
    273 // might make it deader.
    274 //
    275 bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) {
    276   if (GV.use_empty())
    277     return false;
    278   GV.removeDeadConstantUsers();
    279   return GV.use_empty();
    280 }
    281