GlobalDCE.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. //===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This transform is designed to eliminate unreachable internal globals from the
  10. // program. It uses an aggressive algorithm, searching out globals that are
  11. // known to be alive. After it finds all of the globals which are needed, it
  12. // deletes whatever is left over. This allows it to delete recursive chunks of
  13. // the program which are unreachable.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Transforms/IPO/GlobalDCE.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/TypeMetadataUtils.h"
  20. #include "llvm/IR/Instructions.h"
  21. #include "llvm/IR/IntrinsicInst.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/InitializePasses.h"
  24. #include "llvm/Pass.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Transforms/IPO.h"
  27. #include "llvm/Transforms/Utils/CtorUtils.h"
  28. #include "llvm/Transforms/Utils/GlobalStatus.h"
  29. using namespace llvm;
  30. #define DEBUG_TYPE "globaldce"
  31. static cl::opt<bool>
  32. ClEnableVFE("enable-vfe", cl::Hidden, cl::init(true),
  33. cl::desc("Enable virtual function elimination"));
  34. STATISTIC(NumAliases , "Number of global aliases removed");
  35. STATISTIC(NumFunctions, "Number of functions removed");
  36. STATISTIC(NumIFuncs, "Number of indirect functions removed");
  37. STATISTIC(NumVariables, "Number of global variables removed");
  38. STATISTIC(NumVFuncs, "Number of virtual functions removed");
  39. namespace {
  40. class GlobalDCELegacyPass : public ModulePass {
  41. public:
  42. static char ID; // Pass identification, replacement for typeid
  43. GlobalDCELegacyPass() : ModulePass(ID) {
  44. initializeGlobalDCELegacyPassPass(*PassRegistry::getPassRegistry());
  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. // We need a minimally functional dummy module analysis manager. It needs
  53. // to at least know about the possibility of proxying a function analysis
  54. // manager.
  55. FunctionAnalysisManager DummyFAM;
  56. ModuleAnalysisManager DummyMAM;
  57. DummyMAM.registerPass(
  58. [&] { return FunctionAnalysisManagerModuleProxy(DummyFAM); });
  59. auto PA = Impl.run(M, DummyMAM);
  60. return !PA.areAllPreserved();
  61. }
  62. private:
  63. GlobalDCEPass Impl;
  64. };
  65. }
  66. char GlobalDCELegacyPass::ID = 0;
  67. INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce",
  68. "Dead Global Elimination", false, false)
  69. // Public interface to the GlobalDCEPass.
  70. ModulePass *llvm::createGlobalDCEPass() {
  71. return new GlobalDCELegacyPass();
  72. }
  73. /// Returns true if F is effectively empty.
  74. static bool isEmptyFunction(Function *F) {
  75. // Skip external functions.
  76. if (F->isDeclaration())
  77. return false;
  78. BasicBlock &Entry = F->getEntryBlock();
  79. for (auto &I : Entry) {
  80. if (I.isDebugOrPseudoInst())
  81. continue;
  82. if (auto *RI = dyn_cast<ReturnInst>(&I))
  83. return !RI->getReturnValue();
  84. break;
  85. }
  86. return false;
  87. }
  88. /// Compute the set of GlobalValue that depends from V.
  89. /// The recursion stops as soon as a GlobalValue is met.
  90. void GlobalDCEPass::ComputeDependencies(Value *V,
  91. SmallPtrSetImpl<GlobalValue *> &Deps) {
  92. if (auto *I = dyn_cast<Instruction>(V)) {
  93. Function *Parent = I->getParent()->getParent();
  94. Deps.insert(Parent);
  95. } else if (auto *GV = dyn_cast<GlobalValue>(V)) {
  96. Deps.insert(GV);
  97. } else if (auto *CE = dyn_cast<Constant>(V)) {
  98. // Avoid walking the whole tree of a big ConstantExprs multiple times.
  99. auto Where = ConstantDependenciesCache.find(CE);
  100. if (Where != ConstantDependenciesCache.end()) {
  101. auto const &K = Where->second;
  102. Deps.insert(K.begin(), K.end());
  103. } else {
  104. SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE];
  105. for (User *CEUser : CE->users())
  106. ComputeDependencies(CEUser, LocalDeps);
  107. Deps.insert(LocalDeps.begin(), LocalDeps.end());
  108. }
  109. }
  110. }
  111. void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) {
  112. SmallPtrSet<GlobalValue *, 8> Deps;
  113. for (User *User : GV.users())
  114. ComputeDependencies(User, Deps);
  115. Deps.erase(&GV); // Remove self-reference.
  116. for (GlobalValue *GVU : Deps) {
  117. // If this is a dep from a vtable to a virtual function, and we have
  118. // complete information about all virtual call sites which could call
  119. // though this vtable, then skip it, because the call site information will
  120. // be more precise.
  121. if (VFESafeVTables.count(GVU) && isa<Function>(&GV)) {
  122. LLVM_DEBUG(dbgs() << "Ignoring dep " << GVU->getName() << " -> "
  123. << GV.getName() << "\n");
  124. continue;
  125. }
  126. GVDependencies[GVU].insert(&GV);
  127. }
  128. }
  129. /// Mark Global value as Live
  130. void GlobalDCEPass::MarkLive(GlobalValue &GV,
  131. SmallVectorImpl<GlobalValue *> *Updates) {
  132. auto const Ret = AliveGlobals.insert(&GV);
  133. if (!Ret.second)
  134. return;
  135. if (Updates)
  136. Updates->push_back(&GV);
  137. if (Comdat *C = GV.getComdat()) {
  138. for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
  139. MarkLive(*CM.second, Updates); // Recursion depth is only two because only
  140. // globals in the same comdat are visited.
  141. }
  142. }
  143. }
  144. void GlobalDCEPass::ScanVTables(Module &M) {
  145. SmallVector<MDNode *, 2> Types;
  146. LLVM_DEBUG(dbgs() << "Building type info -> vtable map\n");
  147. auto *LTOPostLinkMD =
  148. cast_or_null<ConstantAsMetadata>(M.getModuleFlag("LTOPostLink"));
  149. bool LTOPostLink =
  150. LTOPostLinkMD &&
  151. (cast<ConstantInt>(LTOPostLinkMD->getValue())->getZExtValue() != 0);
  152. for (GlobalVariable &GV : M.globals()) {
  153. Types.clear();
  154. GV.getMetadata(LLVMContext::MD_type, Types);
  155. if (GV.isDeclaration() || Types.empty())
  156. continue;
  157. // Use the typeid metadata on the vtable to build a mapping from typeids to
  158. // the list of (GV, offset) pairs which are the possible vtables for that
  159. // typeid.
  160. for (MDNode *Type : Types) {
  161. Metadata *TypeID = Type->getOperand(1).get();
  162. uint64_t Offset =
  163. cast<ConstantInt>(
  164. cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
  165. ->getZExtValue();
  166. TypeIdMap[TypeID].insert(std::make_pair(&GV, Offset));
  167. }
  168. // If the type corresponding to the vtable is private to this translation
  169. // unit, we know that we can see all virtual functions which might use it,
  170. // so VFE is safe.
  171. if (auto GO = dyn_cast<GlobalObject>(&GV)) {
  172. GlobalObject::VCallVisibility TypeVis = GO->getVCallVisibility();
  173. if (TypeVis == GlobalObject::VCallVisibilityTranslationUnit ||
  174. (LTOPostLink &&
  175. TypeVis == GlobalObject::VCallVisibilityLinkageUnit)) {
  176. LLVM_DEBUG(dbgs() << GV.getName() << " is safe for VFE\n");
  177. VFESafeVTables.insert(&GV);
  178. }
  179. }
  180. }
  181. }
  182. void GlobalDCEPass::ScanVTableLoad(Function *Caller, Metadata *TypeId,
  183. uint64_t CallOffset) {
  184. for (const auto &VTableInfo : TypeIdMap[TypeId]) {
  185. GlobalVariable *VTable = VTableInfo.first;
  186. uint64_t VTableOffset = VTableInfo.second;
  187. Constant *Ptr =
  188. getPointerAtOffset(VTable->getInitializer(), VTableOffset + CallOffset,
  189. *Caller->getParent(), VTable);
  190. if (!Ptr) {
  191. LLVM_DEBUG(dbgs() << "can't find pointer in vtable!\n");
  192. VFESafeVTables.erase(VTable);
  193. continue;
  194. }
  195. auto Callee = dyn_cast<Function>(Ptr->stripPointerCasts());
  196. if (!Callee) {
  197. LLVM_DEBUG(dbgs() << "vtable entry is not function pointer!\n");
  198. VFESafeVTables.erase(VTable);
  199. continue;
  200. }
  201. LLVM_DEBUG(dbgs() << "vfunc dep " << Caller->getName() << " -> "
  202. << Callee->getName() << "\n");
  203. GVDependencies[Caller].insert(Callee);
  204. }
  205. }
  206. void GlobalDCEPass::ScanTypeCheckedLoadIntrinsics(Module &M) {
  207. LLVM_DEBUG(dbgs() << "Scanning type.checked.load intrinsics\n");
  208. Function *TypeCheckedLoadFunc =
  209. M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
  210. if (!TypeCheckedLoadFunc)
  211. return;
  212. for (auto *U : TypeCheckedLoadFunc->users()) {
  213. auto CI = dyn_cast<CallInst>(U);
  214. if (!CI)
  215. continue;
  216. auto *Offset = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  217. Value *TypeIdValue = CI->getArgOperand(2);
  218. auto *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
  219. if (Offset) {
  220. ScanVTableLoad(CI->getFunction(), TypeId, Offset->getZExtValue());
  221. } else {
  222. // type.checked.load with a non-constant offset, so assume every entry in
  223. // every matching vtable is used.
  224. for (const auto &VTableInfo : TypeIdMap[TypeId]) {
  225. VFESafeVTables.erase(VTableInfo.first);
  226. }
  227. }
  228. }
  229. }
  230. void GlobalDCEPass::AddVirtualFunctionDependencies(Module &M) {
  231. if (!ClEnableVFE)
  232. return;
  233. // If the Virtual Function Elim module flag is present and set to zero, then
  234. // the vcall_visibility metadata was inserted for another optimization (WPD)
  235. // and we may not have type checked loads on all accesses to the vtable.
  236. // Don't attempt VFE in that case.
  237. auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
  238. M.getModuleFlag("Virtual Function Elim"));
  239. if (!Val || Val->getZExtValue() == 0)
  240. return;
  241. ScanVTables(M);
  242. if (VFESafeVTables.empty())
  243. return;
  244. ScanTypeCheckedLoadIntrinsics(M);
  245. LLVM_DEBUG(
  246. dbgs() << "VFE safe vtables:\n";
  247. for (auto *VTable : VFESafeVTables)
  248. dbgs() << " " << VTable->getName() << "\n";
  249. );
  250. }
  251. PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) {
  252. bool Changed = false;
  253. // The algorithm first computes the set L of global variables that are
  254. // trivially live. Then it walks the initialization of these variables to
  255. // compute the globals used to initialize them, which effectively builds a
  256. // directed graph where nodes are global variables, and an edge from A to B
  257. // means B is used to initialize A. Finally, it propagates the liveness
  258. // information through the graph starting from the nodes in L. Nodes note
  259. // marked as alive are discarded.
  260. // Remove empty functions from the global ctors list.
  261. Changed |= optimizeGlobalCtorsList(
  262. M, [](uint32_t, Function *F) { return isEmptyFunction(F); });
  263. // Collect the set of members for each comdat.
  264. for (Function &F : M)
  265. if (Comdat *C = F.getComdat())
  266. ComdatMembers.insert(std::make_pair(C, &F));
  267. for (GlobalVariable &GV : M.globals())
  268. if (Comdat *C = GV.getComdat())
  269. ComdatMembers.insert(std::make_pair(C, &GV));
  270. for (GlobalAlias &GA : M.aliases())
  271. if (Comdat *C = GA.getComdat())
  272. ComdatMembers.insert(std::make_pair(C, &GA));
  273. // Add dependencies between virtual call sites and the virtual functions they
  274. // might call, if we have that information.
  275. AddVirtualFunctionDependencies(M);
  276. // Loop over the module, adding globals which are obviously necessary.
  277. for (GlobalObject &GO : M.global_objects()) {
  278. GO.removeDeadConstantUsers();
  279. // Functions with external linkage are needed if they have a body.
  280. // Externally visible & appending globals are needed, if they have an
  281. // initializer.
  282. if (!GO.isDeclaration())
  283. if (!GO.isDiscardableIfUnused())
  284. MarkLive(GO);
  285. UpdateGVDependencies(GO);
  286. }
  287. // Compute direct dependencies of aliases.
  288. for (GlobalAlias &GA : M.aliases()) {
  289. GA.removeDeadConstantUsers();
  290. // Externally visible aliases are needed.
  291. if (!GA.isDiscardableIfUnused())
  292. MarkLive(GA);
  293. UpdateGVDependencies(GA);
  294. }
  295. // Compute direct dependencies of ifuncs.
  296. for (GlobalIFunc &GIF : M.ifuncs()) {
  297. GIF.removeDeadConstantUsers();
  298. // Externally visible ifuncs are needed.
  299. if (!GIF.isDiscardableIfUnused())
  300. MarkLive(GIF);
  301. UpdateGVDependencies(GIF);
  302. }
  303. // Propagate liveness from collected Global Values through the computed
  304. // dependencies.
  305. SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(),
  306. AliveGlobals.end()};
  307. while (!NewLiveGVs.empty()) {
  308. GlobalValue *LGV = NewLiveGVs.pop_back_val();
  309. for (auto *GVD : GVDependencies[LGV])
  310. MarkLive(*GVD, &NewLiveGVs);
  311. }
  312. // Now that all globals which are needed are in the AliveGlobals set, we loop
  313. // through the program, deleting those which are not alive.
  314. //
  315. // The first pass is to drop initializers of global variables which are dead.
  316. std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
  317. for (GlobalVariable &GV : M.globals())
  318. if (!AliveGlobals.count(&GV)) {
  319. DeadGlobalVars.push_back(&GV); // Keep track of dead globals
  320. if (GV.hasInitializer()) {
  321. Constant *Init = GV.getInitializer();
  322. GV.setInitializer(nullptr);
  323. if (isSafeToDestroyConstant(Init))
  324. Init->destroyConstant();
  325. }
  326. }
  327. // The second pass drops the bodies of functions which are dead...
  328. std::vector<Function *> DeadFunctions;
  329. for (Function &F : M)
  330. if (!AliveGlobals.count(&F)) {
  331. DeadFunctions.push_back(&F); // Keep track of dead globals
  332. if (!F.isDeclaration())
  333. F.deleteBody();
  334. }
  335. // The third pass drops targets of aliases which are dead...
  336. std::vector<GlobalAlias*> DeadAliases;
  337. for (GlobalAlias &GA : M.aliases())
  338. if (!AliveGlobals.count(&GA)) {
  339. DeadAliases.push_back(&GA);
  340. GA.setAliasee(nullptr);
  341. }
  342. // The fourth pass drops targets of ifuncs which are dead...
  343. std::vector<GlobalIFunc*> DeadIFuncs;
  344. for (GlobalIFunc &GIF : M.ifuncs())
  345. if (!AliveGlobals.count(&GIF)) {
  346. DeadIFuncs.push_back(&GIF);
  347. GIF.setResolver(nullptr);
  348. }
  349. // Now that all interferences have been dropped, delete the actual objects
  350. // themselves.
  351. auto EraseUnusedGlobalValue = [&](GlobalValue *GV) {
  352. GV->removeDeadConstantUsers();
  353. GV->eraseFromParent();
  354. Changed = true;
  355. };
  356. NumFunctions += DeadFunctions.size();
  357. for (Function *F : DeadFunctions) {
  358. if (!F->use_empty()) {
  359. // Virtual functions might still be referenced by one or more vtables,
  360. // but if we've proven them to be unused then it's safe to replace the
  361. // virtual function pointers with null, allowing us to remove the
  362. // function itself.
  363. ++NumVFuncs;
  364. // Detect vfuncs that are referenced as "relative pointers" which are used
  365. // in Swift vtables, i.e. entries in the form of:
  366. //
  367. // i32 trunc (i64 sub (i64 ptrtoint @f, i64 ptrtoint ...)) to i32)
  368. //
  369. // In this case, replace the whole "sub" expression with constant 0 to
  370. // avoid leaving a weird sub(0, symbol) expression behind.
  371. replaceRelativePointerUsersWithZero(F);
  372. F->replaceNonMetadataUsesWith(ConstantPointerNull::get(F->getType()));
  373. }
  374. EraseUnusedGlobalValue(F);
  375. }
  376. NumVariables += DeadGlobalVars.size();
  377. for (GlobalVariable *GV : DeadGlobalVars)
  378. EraseUnusedGlobalValue(GV);
  379. NumAliases += DeadAliases.size();
  380. for (GlobalAlias *GA : DeadAliases)
  381. EraseUnusedGlobalValue(GA);
  382. NumIFuncs += DeadIFuncs.size();
  383. for (GlobalIFunc *GIF : DeadIFuncs)
  384. EraseUnusedGlobalValue(GIF);
  385. // Make sure that all memory is released
  386. AliveGlobals.clear();
  387. ConstantDependenciesCache.clear();
  388. GVDependencies.clear();
  389. ComdatMembers.clear();
  390. TypeIdMap.clear();
  391. VFESafeVTables.clear();
  392. if (Changed)
  393. return PreservedAnalyses::none();
  394. return PreservedAnalyses::all();
  395. }