GlobalDCE.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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/HLSL/DxilModule.h" // HLSL Change
  29. #include "dxc/HLSL/DxilOperations.h" // HLSL Change
  30. #include "dxc/HLSL/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. // HLSL Change Starts - remove resource metadata
  132. hlsl::HLModule *HLM = M.HasHLModule() ? &M.GetHLModule() : nullptr;
  133. if (!DeadGlobalVars.empty() && HLM != nullptr) {
  134. HLM->RemoveResources(DeadGlobalVars.data(), DeadGlobalVars.size());
  135. }
  136. // HLSL Change Ends
  137. // The second pass drops the bodies of functions which are dead...
  138. std::vector<Function*> DeadFunctions;
  139. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
  140. if (!AliveGlobals.count(I)) {
  141. DeadFunctions.push_back(I); // Keep track of dead globals
  142. if (!I->isDeclaration())
  143. I->deleteBody();
  144. }
  145. // The third pass drops targets of aliases which are dead...
  146. std::vector<GlobalAlias*> DeadAliases;
  147. for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
  148. ++I)
  149. if (!AliveGlobals.count(I)) {
  150. DeadAliases.push_back(I);
  151. I->setAliasee(nullptr);
  152. }
  153. if (!DeadFunctions.empty()) {
  154. // Now that all interferences have been dropped, delete the actual objects
  155. // themselves.
  156. for (unsigned i = 0, e = DeadFunctions.size(); i != e; ++i) {
  157. RemoveUnusedGlobalValue(*DeadFunctions[i]);
  158. if (HLM != nullptr) HLM->RemoveFunction(DeadFunctions[i]); // HLSL Change
  159. M.getFunctionList().erase(DeadFunctions[i]);
  160. }
  161. NumFunctions += DeadFunctions.size();
  162. Changed = true;
  163. }
  164. if (!DeadGlobalVars.empty()) {
  165. for (unsigned i = 0, e = DeadGlobalVars.size(); i != e; ++i) {
  166. RemoveUnusedGlobalValue(*DeadGlobalVars[i]);
  167. if (HLM != nullptr) HLM->RemoveGlobal(DeadGlobalVars[i]); // HLSL Change
  168. M.getGlobalList().erase(DeadGlobalVars[i]);
  169. }
  170. NumVariables += DeadGlobalVars.size();
  171. Changed = true;
  172. }
  173. // Now delete any dead aliases.
  174. if (!DeadAliases.empty()) {
  175. for (unsigned i = 0, e = DeadAliases.size(); i != e; ++i) {
  176. RemoveUnusedGlobalValue(*DeadAliases[i]);
  177. M.getAliasList().erase(DeadAliases[i]);
  178. }
  179. NumAliases += DeadAliases.size();
  180. Changed = true;
  181. }
  182. // Make sure that all memory is released
  183. AliveGlobals.clear();
  184. SeenConstants.clear();
  185. ComdatMembers.clear();
  186. return Changed;
  187. }
  188. /// GlobalIsNeeded - the specific global value as needed, and
  189. /// recursively mark anything that it uses as also needed.
  190. void GlobalDCE::GlobalIsNeeded(GlobalValue *G) {
  191. // If the global is already in the set, no need to reprocess it.
  192. if (!AliveGlobals.insert(G).second)
  193. return;
  194. if (Comdat *C = G->getComdat()) {
  195. for (auto &&CM : make_range(ComdatMembers.equal_range(C)))
  196. GlobalIsNeeded(CM.second);
  197. }
  198. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
  199. // If this is a global variable, we must make sure to add any global values
  200. // referenced by the initializer to the alive set.
  201. if (GV->hasInitializer())
  202. MarkUsedGlobalsAsNeeded(GV->getInitializer());
  203. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(G)) {
  204. // The target of a global alias is needed.
  205. MarkUsedGlobalsAsNeeded(GA->getAliasee());
  206. } else {
  207. // Otherwise this must be a function object. We have to scan the body of
  208. // the function looking for constants and global values which are used as
  209. // operands. Any operands of these types must be processed to ensure that
  210. // any globals used will be marked as needed.
  211. Function *F = cast<Function>(G);
  212. if (F->hasPrefixData())
  213. MarkUsedGlobalsAsNeeded(F->getPrefixData());
  214. if (F->hasPrologueData())
  215. MarkUsedGlobalsAsNeeded(F->getPrologueData());
  216. if (F->hasPersonalityFn())
  217. MarkUsedGlobalsAsNeeded(F->getPersonalityFn());
  218. for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
  219. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  220. for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U)
  221. if (GlobalValue *GV = dyn_cast<GlobalValue>(*U))
  222. GlobalIsNeeded(GV);
  223. else if (Constant *C = dyn_cast<Constant>(*U))
  224. MarkUsedGlobalsAsNeeded(C);
  225. }
  226. }
  227. void GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) {
  228. if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
  229. return GlobalIsNeeded(GV);
  230. // Loop over all of the operands of the constant, adding any globals they
  231. // use to the list of needed globals.
  232. for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I) {
  233. // If we've already processed this constant there's no need to do it again.
  234. Constant *Op = dyn_cast<Constant>(*I);
  235. if (Op && SeenConstants.insert(Op).second)
  236. MarkUsedGlobalsAsNeeded(Op);
  237. }
  238. }
  239. // RemoveUnusedGlobalValue - Loop over all of the uses of the specified
  240. // GlobalValue, looking for the constant pointer ref that may be pointing to it.
  241. // If found, check to see if the constant pointer ref is safe to destroy, and if
  242. // so, nuke it. This will reduce the reference count on the global value, which
  243. // might make it deader.
  244. //
  245. bool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) {
  246. if (GV.use_empty()) return false;
  247. GV.removeDeadConstantUsers();
  248. return GV.use_empty();
  249. }