GlobalDCE.cpp 10 KB

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