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.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/Transforms/Utils/CtorUtils.h" 25#include "llvm/Pass.h" 26using namespace llvm; 27 28#define DEBUG_TYPE "globaldce" 29 30STATISTIC(NumAliases , "Number of global aliases removed"); 31STATISTIC(NumFunctions, "Number of functions removed"); 32STATISTIC(NumVariables, "Number of global variables removed"); 33 34namespace { 35 struct GlobalDCE : public ModulePass { 36 static char ID; // Pass identification, replacement for typeid 37 GlobalDCE() : ModulePass(ID) { 38 initializeGlobalDCEPass(*PassRegistry::getPassRegistry()); 39 } 40 41 // run - Do the GlobalDCE pass on the specified module, optionally updating 42 // the specified callgraph to reflect the changes. 43 // 44 bool runOnModule(Module &M) override; 45 46 private: 47 SmallPtrSet<GlobalValue*, 32> AliveGlobals; 48 SmallPtrSet<Constant *, 8> SeenConstants; 49 50 /// GlobalIsNeeded - mark the specific global value as needed, and 51 /// recursively mark anything that it uses as also needed. 52 void GlobalIsNeeded(GlobalValue *GV); 53 void MarkUsedGlobalsAsNeeded(Constant *C); 54 55 bool RemoveUnusedGlobalValue(GlobalValue &GV); 56 }; 57} 58 59/// Returns true if F contains only a single "ret" instruction. 60static bool isEmptyFunction(Function *F) { 61 BasicBlock &Entry = F->getEntryBlock(); 62 if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front())) 63 return false; 64 ReturnInst &RI = cast<ReturnInst>(Entry.front()); 65 return RI.getReturnValue() == nullptr; 66} 67 68char GlobalDCE::ID = 0; 69INITIALIZE_PASS(GlobalDCE, "globaldce", 70 "Dead Global Elimination", false, false) 71 72ModulePass *llvm::createGlobalDCEPass() { return new GlobalDCE(); } 73 74bool GlobalDCE::runOnModule(Module &M) { 75 bool Changed = false; 76 77 // Remove empty functions from the global ctors list. 78 Changed |= optimizeGlobalCtorsList(M, isEmptyFunction); 79 80 typedef std::multimap<const Comdat *, GlobalValue *> ComdatGVPairsTy; 81 ComdatGVPairsTy ComdatGVPairs; 82 83 // Loop over the module, adding globals which are obviously necessary. 84 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { 85 Changed |= RemoveUnusedGlobalValue(*I); 86 // Functions with external linkage are needed if they have a body 87 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) { 88 if (!I->isDiscardableIfUnused()) 89 GlobalIsNeeded(I); 90 else if (const Comdat *C = I->getComdat()) 91 ComdatGVPairs.insert(std::make_pair(C, I)); 92 } 93 } 94 95 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 96 I != E; ++I) { 97 Changed |= RemoveUnusedGlobalValue(*I); 98 // Externally visible & appending globals are needed, if they have an 99 // initializer. 100 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) { 101 if (!I->isDiscardableIfUnused()) 102 GlobalIsNeeded(I); 103 else if (const Comdat *C = I->getComdat()) 104 ComdatGVPairs.insert(std::make_pair(C, I)); 105 } 106 } 107 108 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 109 I != E; ++I) { 110 Changed |= RemoveUnusedGlobalValue(*I); 111 // Externally visible aliases are needed. 112 if (!I->isDiscardableIfUnused()) { 113 GlobalIsNeeded(I); 114 } else if (const Comdat *C = I->getComdat()) { 115 ComdatGVPairs.insert(std::make_pair(C, I)); 116 } 117 } 118 119 for (ComdatGVPairsTy::iterator I = ComdatGVPairs.begin(), 120 E = ComdatGVPairs.end(); 121 I != E;) { 122 ComdatGVPairsTy::iterator UB = ComdatGVPairs.upper_bound(I->first); 123 bool CanDiscard = std::all_of(I, UB, [](ComdatGVPairsTy::value_type Pair) { 124 return Pair.second->isDiscardableIfUnused(); 125 }); 126 if (!CanDiscard) { 127 std::for_each(I, UB, [this](ComdatGVPairsTy::value_type Pair) { 128 GlobalIsNeeded(Pair.second); 129 }); 130 } 131 I = UB; 132 } 133 134 // Now that all globals which are needed are in the AliveGlobals set, we loop 135 // through the program, deleting those which are not alive. 136 // 137 138 // The first pass is to drop initializers of global variables which are dead. 139 std::vector<GlobalVariable*> DeadGlobalVars; // Keep track of dead globals 140 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 141 I != E; ++I) 142 if (!AliveGlobals.count(I)) { 143 DeadGlobalVars.push_back(I); // Keep track of dead globals 144 I->setInitializer(nullptr); 145 } 146 147 // The second pass drops the bodies of functions which are dead... 148 std::vector<Function*> DeadFunctions; 149 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 150 if (!AliveGlobals.count(I)) { 151 DeadFunctions.push_back(I); // Keep track of dead globals 152 if (!I->isDeclaration()) 153 I->deleteBody(); 154 } 155 156 // The third pass drops targets of aliases which are dead... 157 std::vector<GlobalAlias*> DeadAliases; 158 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E; 159 ++I) 160 if (!AliveGlobals.count(I)) { 161 DeadAliases.push_back(I); 162 I->setAliasee(nullptr); 163 } 164 165 if (!DeadFunctions.empty()) { 166 // Now that all interferences have been dropped, delete the actual objects 167 // themselves. 168 for (unsigned i = 0, e = DeadFunctions.size(); i != e; ++i) { 169 RemoveUnusedGlobalValue(*DeadFunctions[i]); 170 M.getFunctionList().erase(DeadFunctions[i]); 171 } 172 NumFunctions += DeadFunctions.size(); 173 Changed = true; 174 } 175 176 if (!DeadGlobalVars.empty()) { 177 for (unsigned i = 0, e = DeadGlobalVars.size(); i != e; ++i) { 178 RemoveUnusedGlobalValue(*DeadGlobalVars[i]); 179 M.getGlobalList().erase(DeadGlobalVars[i]); 180 } 181 NumVariables += DeadGlobalVars.size(); 182 Changed = true; 183 } 184 185 // Now delete any dead aliases. 186 if (!DeadAliases.empty()) { 187 for (unsigned i = 0, e = DeadAliases.size(); i != e; ++i) { 188 RemoveUnusedGlobalValue(*DeadAliases[i]); 189 M.getAliasList().erase(DeadAliases[i]); 190 } 191 NumAliases += DeadAliases.size(); 192 Changed = true; 193 } 194 195 // Make sure that all memory is released 196 AliveGlobals.clear(); 197 SeenConstants.clear(); 198 199 return Changed; 200} 201 202/// GlobalIsNeeded - the specific global value as needed, and 203/// recursively mark anything that it uses as also needed. 204void GlobalDCE::GlobalIsNeeded(GlobalValue *G) { 205 // If the global is already in the set, no need to reprocess it. 206 if (!AliveGlobals.insert(G)) 207 return; 208 209 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) { 210 // If this is a global variable, we must make sure to add any global values 211 // referenced by the initializer to the alive set. 212 if (GV->hasInitializer()) 213 MarkUsedGlobalsAsNeeded(GV->getInitializer()); 214 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(G)) { 215 // The target of a global alias is needed. 216 MarkUsedGlobalsAsNeeded(GA->getAliasee()); 217 } else { 218 // Otherwise this must be a function object. We have to scan the body of 219 // the function looking for constants and global values which are used as 220 // operands. Any operands of these types must be processed to ensure that 221 // any globals used will be marked as needed. 222 Function *F = cast<Function>(G); 223 224 if (F->hasPrefixData()) 225 MarkUsedGlobalsAsNeeded(F->getPrefixData()); 226 227 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) 228 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 229 for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U) 230 if (GlobalValue *GV = dyn_cast<GlobalValue>(*U)) 231 GlobalIsNeeded(GV); 232 else if (Constant *C = dyn_cast<Constant>(*U)) 233 MarkUsedGlobalsAsNeeded(C); 234 } 235} 236 237void GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) { 238 if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) 239 return GlobalIsNeeded(GV); 240 241 // Loop over all of the operands of the constant, adding any globals they 242 // use to the list of needed globals. 243 for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I) { 244 // If we've already processed this constant there's no need to do it again. 245 Constant *Op = dyn_cast<Constant>(*I); 246 if (Op && SeenConstants.insert(Op)) 247 MarkUsedGlobalsAsNeeded(Op); 248 } 249} 250 251// RemoveUnusedGlobalValue - Loop over all of the uses of the specified 252// GlobalValue, looking for the constant pointer ref that may be pointing to it. 253// If found, check to see if the constant pointer ref is safe to destroy, and if 254// so, nuke it. This will reduce the reference count on the global value, which 255// might make it deader. 256// 257bool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) { 258 if (GV.use_empty()) return false; 259 GV.removeDeadConstantUsers(); 260 return GV.use_empty(); 261} 262