GlobalDCE.cpp 9.9 KB

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