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 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 // We need a minimally functional dummy module analysis manager. It needs 54 // to at least know about the possibility of proxying a function analysis 55 // manager. 56 FunctionAnalysisManager DummyFAM; 57 ModuleAnalysisManager DummyMAM; 58 DummyMAM.registerPass( 59 [&] { return FunctionAnalysisManagerModuleProxy(DummyFAM); }); 60 61 auto PA = Impl.run(M, DummyMAM); 62 return !PA.areAllPreserved(); 63 } 64 65 private: 66 GlobalDCEPass Impl; 67 }; 68 } 69 70 char GlobalDCELegacyPass::ID = 0; 71 INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce", 72 "Dead Global Elimination", false, false) 73 74 // Public interface to the GlobalDCEPass. 75 ModulePass *llvm::createGlobalDCEPass() { 76 return new GlobalDCELegacyPass(); 77 } 78 79 /// Returns true if F contains only a single "ret" instruction. 80 static bool isEmptyFunction(Function *F) { 81 BasicBlock &Entry = F->getEntryBlock(); 82 if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front())) 83 return false; 84 ReturnInst &RI = cast<ReturnInst>(Entry.front()); 85 return RI.getReturnValue() == nullptr; 86 } 87 88 /// Compute the set of GlobalValue that depends from V. 89 /// The recursion stops as soon as a GlobalValue is met. 90 void GlobalDCEPass::ComputeDependencies(Value *V, 91 SmallPtrSetImpl<GlobalValue *> &Deps) { 92 if (auto *I = dyn_cast<Instruction>(V)) { 93 Function *Parent = I->getParent()->getParent(); 94 Deps.insert(Parent); 95 } else if (auto *GV = dyn_cast<GlobalValue>(V)) { 96 Deps.insert(GV); 97 } else if (auto *CE = dyn_cast<Constant>(V)) { 98 // Avoid walking the whole tree of a big ConstantExprs multiple times. 99 auto Where = ConstantDependenciesCache.find(CE); 100 if (Where != ConstantDependenciesCache.end()) { 101 auto const &K = Where->second; 102 Deps.insert(K.begin(), K.end()); 103 } else { 104 SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE]; 105 for (User *CEUser : CE->users()) 106 ComputeDependencies(CEUser, LocalDeps); 107 Deps.insert(LocalDeps.begin(), LocalDeps.end()); 108 } 109 } 110 } 111 112 void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) { 113 SmallPtrSet<GlobalValue *, 8> Deps; 114 for (User *User : GV.users()) 115 ComputeDependencies(User, Deps); 116 Deps.erase(&GV); // Remove self-reference. 117 for (GlobalValue *GVU : Deps) { 118 GVDependencies.insert(std::make_pair(GVU, &GV)); 119 } 120 } 121 122 /// Mark Global value as Live 123 void GlobalDCEPass::MarkLive(GlobalValue &GV, 124 SmallVectorImpl<GlobalValue *> *Updates) { 125 auto const Ret = AliveGlobals.insert(&GV); 126 if (!Ret.second) 127 return; 128 129 if (Updates) 130 Updates->push_back(&GV); 131 if (Comdat *C = GV.getComdat()) { 132 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) 133 MarkLive(*CM.second, Updates); // Recursion depth is only two because only 134 // globals in the same comdat are visited. 135 } 136 } 137 138 PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) { 139 bool Changed = false; 140 141 // The algorithm first computes the set L of global variables that are 142 // trivially live. Then it walks the initialization of these variables to 143 // compute the globals used to initialize them, which effectively builds a 144 // directed graph where nodes are global variables, and an edge from A to B 145 // means B is used to initialize A. Finally, it propagates the liveness 146 // information through the graph starting from the nodes in L. Nodes note 147 // marked as alive are discarded. 148 149 // Remove empty functions from the global ctors list. 150 Changed |= optimizeGlobalCtorsList(M, isEmptyFunction); 151 152 // Collect the set of members for each comdat. 153 for (Function &F : M) 154 if (Comdat *C = F.getComdat()) 155 ComdatMembers.insert(std::make_pair(C, &F)); 156 for (GlobalVariable &GV : M.globals()) 157 if (Comdat *C = GV.getComdat()) 158 ComdatMembers.insert(std::make_pair(C, &GV)); 159 for (GlobalAlias &GA : M.aliases()) 160 if (Comdat *C = GA.getComdat()) 161 ComdatMembers.insert(std::make_pair(C, &GA)); 162 163 // Loop over the module, adding globals which are obviously necessary. 164 for (GlobalObject &GO : M.global_objects()) { 165 Changed |= RemoveUnusedGlobalValue(GO); 166 // Functions with external linkage are needed if they have a body. 167 // Externally visible & appending globals are needed, if they have an 168 // initializer. 169 if (!GO.isDeclaration() && !GO.hasAvailableExternallyLinkage()) 170 if (!GO.isDiscardableIfUnused()) 171 MarkLive(GO); 172 173 UpdateGVDependencies(GO); 174 } 175 176 // Compute direct dependencies of aliases. 177 for (GlobalAlias &GA : M.aliases()) { 178 Changed |= RemoveUnusedGlobalValue(GA); 179 // Externally visible aliases are needed. 180 if (!GA.isDiscardableIfUnused()) 181 MarkLive(GA); 182 183 UpdateGVDependencies(GA); 184 } 185 186 // Compute direct dependencies of ifuncs. 187 for (GlobalIFunc &GIF : M.ifuncs()) { 188 Changed |= RemoveUnusedGlobalValue(GIF); 189 // Externally visible ifuncs are needed. 190 if (!GIF.isDiscardableIfUnused()) 191 MarkLive(GIF); 192 193 UpdateGVDependencies(GIF); 194 } 195 196 // Propagate liveness from collected Global Values through the computed 197 // dependencies. 198 SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(), 199 AliveGlobals.end()}; 200 while (!NewLiveGVs.empty()) { 201 GlobalValue *LGV = NewLiveGVs.pop_back_val(); 202 for (auto &&GVD : make_range(GVDependencies.equal_range(LGV))) 203 MarkLive(*GVD.second, &NewLiveGVs); 204 } 205 206 // Now that all globals which are needed are in the AliveGlobals set, we loop 207 // through the program, deleting those which are not alive. 208 // 209 210 // The first pass is to drop initializers of global variables which are dead. 211 std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals 212 for (GlobalVariable &GV : M.globals()) 213 if (!AliveGlobals.count(&GV)) { 214 DeadGlobalVars.push_back(&GV); // Keep track of dead globals 215 if (GV.hasInitializer()) { 216 Constant *Init = GV.getInitializer(); 217 GV.setInitializer(nullptr); 218 if (isSafeToDestroyConstant(Init)) 219 Init->destroyConstant(); 220 } 221 } 222 223 // The second pass drops the bodies of functions which are dead... 224 std::vector<Function *> DeadFunctions; 225 for (Function &F : M) 226 if (!AliveGlobals.count(&F)) { 227 DeadFunctions.push_back(&F); // Keep track of dead globals 228 if (!F.isDeclaration()) 229 F.deleteBody(); 230 } 231 232 // The third pass drops targets of aliases which are dead... 233 std::vector<GlobalAlias*> DeadAliases; 234 for (GlobalAlias &GA : M.aliases()) 235 if (!AliveGlobals.count(&GA)) { 236 DeadAliases.push_back(&GA); 237 GA.setAliasee(nullptr); 238 } 239 240 // The fourth pass drops targets of ifuncs which are dead... 241 std::vector<GlobalIFunc*> DeadIFuncs; 242 for (GlobalIFunc &GIF : M.ifuncs()) 243 if (!AliveGlobals.count(&GIF)) { 244 DeadIFuncs.push_back(&GIF); 245 GIF.setResolver(nullptr); 246 } 247 248 // Now that all interferences have been dropped, delete the actual objects 249 // themselves. 250 auto EraseUnusedGlobalValue = [&](GlobalValue *GV) { 251 RemoveUnusedGlobalValue(*GV); 252 GV->eraseFromParent(); 253 Changed = true; 254 }; 255 256 NumFunctions += DeadFunctions.size(); 257 for (Function *F : DeadFunctions) 258 EraseUnusedGlobalValue(F); 259 260 NumVariables += DeadGlobalVars.size(); 261 for (GlobalVariable *GV : DeadGlobalVars) 262 EraseUnusedGlobalValue(GV); 263 264 NumAliases += DeadAliases.size(); 265 for (GlobalAlias *GA : DeadAliases) 266 EraseUnusedGlobalValue(GA); 267 268 NumIFuncs += DeadIFuncs.size(); 269 for (GlobalIFunc *GIF : DeadIFuncs) 270 EraseUnusedGlobalValue(GIF); 271 272 // Make sure that all memory is released 273 AliveGlobals.clear(); 274 ConstantDependenciesCache.clear(); 275 GVDependencies.clear(); 276 ComdatMembers.clear(); 277 278 if (Changed) 279 return PreservedAnalyses::none(); 280 return PreservedAnalyses::all(); 281 } 282 283 // RemoveUnusedGlobalValue - Loop over all of the uses of the specified 284 // GlobalValue, looking for the constant pointer ref that may be pointing to it. 285 // If found, check to see if the constant pointer ref is safe to destroy, and if 286 // so, nuke it. This will reduce the reference count on the global value, which 287 // might make it deader. 288 // 289 bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) { 290 if (GV.use_empty()) 291 return false; 292 GV.removeDeadConstantUsers(); 293 return GV.use_empty(); 294 } 295