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 // 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 PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) { 89 bool Changed = false; 90 91 // Remove empty functions from the global ctors list. 92 Changed |= optimizeGlobalCtorsList(M, isEmptyFunction); 93 94 // Collect the set of members for each comdat. 95 for (Function &F : M) 96 if (Comdat *C = F.getComdat()) 97 ComdatMembers.insert(std::make_pair(C, &F)); 98 for (GlobalVariable &GV : M.globals()) 99 if (Comdat *C = GV.getComdat()) 100 ComdatMembers.insert(std::make_pair(C, &GV)); 101 for (GlobalAlias &GA : M.aliases()) 102 if (Comdat *C = GA.getComdat()) 103 ComdatMembers.insert(std::make_pair(C, &GA)); 104 105 // Loop over the module, adding globals which are obviously necessary. 106 for (GlobalObject &GO : M.global_objects()) { 107 Changed |= RemoveUnusedGlobalValue(GO); 108 // Functions with external linkage are needed if they have a body. 109 // Externally visible & appending globals are needed, if they have an 110 // initializer. 111 if (!GO.isDeclaration() && !GO.hasAvailableExternallyLinkage()) 112 if (!GO.isDiscardableIfUnused()) 113 GlobalIsNeeded(&GO); 114 } 115 116 for (GlobalAlias &GA : M.aliases()) { 117 Changed |= RemoveUnusedGlobalValue(GA); 118 // Externally visible aliases are needed. 119 if (!GA.isDiscardableIfUnused()) 120 GlobalIsNeeded(&GA); 121 } 122 123 for (GlobalIFunc &GIF : M.ifuncs()) { 124 Changed |= RemoveUnusedGlobalValue(GIF); 125 // Externally visible ifuncs are needed. 126 if (!GIF.isDiscardableIfUnused()) 127 GlobalIsNeeded(&GIF); 128 } 129 130 // Now that all globals which are needed are in the AliveGlobals set, we loop 131 // through the program, deleting those which are not alive. 132 // 133 134 // The first pass is to drop initializers of global variables which are dead. 135 std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals 136 for (GlobalVariable &GV : M.globals()) 137 if (!AliveGlobals.count(&GV)) { 138 DeadGlobalVars.push_back(&GV); // Keep track of dead globals 139 if (GV.hasInitializer()) { 140 Constant *Init = GV.getInitializer(); 141 GV.setInitializer(nullptr); 142 if (isSafeToDestroyConstant(Init)) 143 Init->destroyConstant(); 144 } 145 } 146 147 // The second pass drops the bodies of functions which are dead... 148 std::vector<Function *> DeadFunctions; 149 for (Function &F : M) 150 if (!AliveGlobals.count(&F)) { 151 DeadFunctions.push_back(&F); // Keep track of dead globals 152 if (!F.isDeclaration()) 153 F.deleteBody(); 154 } 155 156 // The third pass drops targets of aliases which are dead... 157 std::vector<GlobalAlias*> DeadAliases; 158 for (GlobalAlias &GA : M.aliases()) 159 if (!AliveGlobals.count(&GA)) { 160 DeadAliases.push_back(&GA); 161 GA.setAliasee(nullptr); 162 } 163 164 // The third pass drops targets of ifuncs which are dead... 165 std::vector<GlobalIFunc*> DeadIFuncs; 166 for (GlobalIFunc &GIF : M.ifuncs()) 167 if (!AliveGlobals.count(&GIF)) { 168 DeadIFuncs.push_back(&GIF); 169 GIF.setResolver(nullptr); 170 } 171 172 // Now that all interferences have been dropped, delete the actual objects 173 // themselves. 174 auto EraseUnusedGlobalValue = [&](GlobalValue *GV) { 175 RemoveUnusedGlobalValue(*GV); 176 GV->eraseFromParent(); 177 Changed = true; 178 }; 179 180 NumFunctions += DeadFunctions.size(); 181 for (Function *F : DeadFunctions) 182 EraseUnusedGlobalValue(F); 183 184 NumVariables += DeadGlobalVars.size(); 185 for (GlobalVariable *GV : DeadGlobalVars) 186 EraseUnusedGlobalValue(GV); 187 188 NumAliases += DeadAliases.size(); 189 for (GlobalAlias *GA : DeadAliases) 190 EraseUnusedGlobalValue(GA); 191 192 NumIFuncs += DeadIFuncs.size(); 193 for (GlobalIFunc *GIF : DeadIFuncs) 194 EraseUnusedGlobalValue(GIF); 195 196 // Make sure that all memory is released 197 AliveGlobals.clear(); 198 SeenConstants.clear(); 199 ComdatMembers.clear(); 200 201 if (Changed) 202 return PreservedAnalyses::none(); 203 return PreservedAnalyses::all(); 204 } 205 206 /// GlobalIsNeeded - the specific global value as needed, and 207 /// recursively mark anything that it uses as also needed. 208 void GlobalDCEPass::GlobalIsNeeded(GlobalValue *G) { 209 // If the global is already in the set, no need to reprocess it. 210 if (!AliveGlobals.insert(G).second) 211 return; 212 213 if (Comdat *C = G->getComdat()) { 214 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) 215 GlobalIsNeeded(CM.second); 216 } 217 218 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) { 219 // If this is a global variable, we must make sure to add any global values 220 // referenced by the initializer to the alive set. 221 if (GV->hasInitializer()) 222 MarkUsedGlobalsAsNeeded(GV->getInitializer()); 223 } else if (GlobalIndirectSymbol *GIS = dyn_cast<GlobalIndirectSymbol>(G)) { 224 // The target of a global alias or ifunc is needed. 225 MarkUsedGlobalsAsNeeded(GIS->getIndirectSymbol()); 226 } else { 227 // Otherwise this must be a function object. We have to scan the body of 228 // the function looking for constants and global values which are used as 229 // operands. Any operands of these types must be processed to ensure that 230 // any globals used will be marked as needed. 231 Function *F = cast<Function>(G); 232 233 for (Use &U : F->operands()) 234 MarkUsedGlobalsAsNeeded(cast<Constant>(U.get())); 235 236 for (BasicBlock &BB : *F) 237 for (Instruction &I : BB) 238 for (Use &U : I.operands()) 239 if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) 240 GlobalIsNeeded(GV); 241 else if (Constant *C = dyn_cast<Constant>(U)) 242 MarkUsedGlobalsAsNeeded(C); 243 } 244 } 245 246 void GlobalDCEPass::MarkUsedGlobalsAsNeeded(Constant *C) { 247 if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) 248 return GlobalIsNeeded(GV); 249 250 // Loop over all of the operands of the constant, adding any globals they 251 // use to the list of needed globals. 252 for (Use &U : C->operands()) { 253 // If we've already processed this constant there's no need to do it again. 254 Constant *Op = dyn_cast<Constant>(U); 255 if (Op && SeenConstants.insert(Op).second) 256 MarkUsedGlobalsAsNeeded(Op); 257 } 258 } 259 260 // RemoveUnusedGlobalValue - Loop over all of the uses of the specified 261 // GlobalValue, looking for the constant pointer ref that may be pointing to it. 262 // If found, check to see if the constant pointer ref is safe to destroy, and if 263 // so, nuke it. This will reduce the reference count on the global value, which 264 // might make it deader. 265 // 266 bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) { 267 if (GV.use_empty()) 268 return false; 269 GV.removeDeadConstantUsers(); 270 return GV.use_empty(); 271 } 272