blob: 7a04de3d12dbfc589f3422d6be873eea464062cf [file] [log] [blame]
Chris Lattner62b7fd12002-04-07 20:49:59 +00001//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbd422e62001-11-26 18:42:17 +00009//
Chris Lattnerec6d7a62003-09-16 19:27:31 +000010// 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.
Chris Lattnerbd422e62001-11-26 18:42:17 +000015//
16//===----------------------------------------------------------------------===//
17
Davide Italiano66228c42016-05-03 19:39:15 +000018#include "llvm/Transforms/IPO/GlobalDCE.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
Nico Weber4b2acde2014-05-02 18:35:25 +000022#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Module.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000024#include "llvm/Pass.h"
25#include "llvm/Transforms/IPO.h"
Nico Weber4b2acde2014-05-02 18:35:25 +000026#include "llvm/Transforms/Utils/CtorUtils.h"
Bruno Cardoso Lopese2a1fa32014-08-25 17:51:14 +000027#include "llvm/Transforms/Utils/GlobalStatus.h"
Peter Collingbourne0dbc7082015-03-19 18:23:29 +000028#include <unordered_map>
Chris Lattnerf52e03c2003-11-21 21:54:22 +000029using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000030
Chandler Carruth964daaa2014-04-22 02:55:47 +000031#define DEBUG_TYPE "globaldce"
32
Duncan Sands821d13c2009-01-05 20:39:50 +000033STATISTIC(NumAliases , "Number of global aliases removed");
Chris Lattner1631bcb2006-12-19 22:09:18 +000034STATISTIC(NumFunctions, "Number of functions removed");
David Majnemer95549492016-05-04 00:20:48 +000035STATISTIC(NumIFuncs, "Number of indirect functions removed");
Chris Lattner1631bcb2006-12-19 22:09:18 +000036STATISTIC(NumVariables, "Number of global variables removed");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000037
Chris Lattner1631bcb2006-12-19 22:09:18 +000038namespace {
Davide Italiano66228c42016-05-03 19:39:15 +000039 class GlobalDCELegacyPass : public ModulePass {
40 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000041 static char ID; // Pass identification, replacement for typeid
Davide Italiano66228c42016-05-03 19:39:15 +000042 GlobalDCELegacyPass() : ModulePass(ID) {
43 initializeGlobalDCELegacyPassPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000044 }
Duncan Sandsf5dbbae2009-01-05 20:37:33 +000045
Chris Lattner04805fa2002-02-26 21:46:54 +000046 // run - Do the GlobalDCE pass on the specified module, optionally updating
47 // the specified callgraph to reflect the changes.
48 //
Davide Italiano66228c42016-05-03 19:39:15 +000049 bool runOnModule(Module &M) override {
50 if (skipModule(M))
51 return false;
52
Chandler Carruth164a2aa62016-06-17 00:11:01 +000053 ModuleAnalysisManager DummyMAM;
54 auto PA = Impl.run(M, DummyMAM);
Davide Italiano66228c42016-05-03 19:39:15 +000055 return !PA.areAllPreserved();
56 }
Chris Lattner8f3acc62002-08-18 01:28:30 +000057
58 private:
Davide Italiano66228c42016-05-03 19:39:15 +000059 GlobalDCEPass Impl;
Chris Lattner04805fa2002-02-26 21:46:54 +000060 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000061}
Nico Weber4b2acde2014-05-02 18:35:25 +000062
Davide Italiano66228c42016-05-03 19:39:15 +000063char GlobalDCELegacyPass::ID = 0;
64INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce",
65 "Dead Global Elimination", false, false)
66
67// Public interface to the GlobalDCEPass.
68ModulePass *llvm::createGlobalDCEPass() {
69 return new GlobalDCELegacyPass();
70}
71
Nico Weber4b2acde2014-05-02 18:35:25 +000072/// Returns true if F contains only a single "ret" instruction.
Richard Smithc167d652014-05-06 01:44:26 +000073static bool isEmptyFunction(Function *F) {
Nico Weber4b2acde2014-05-02 18:35:25 +000074 BasicBlock &Entry = F->getEntryBlock();
75 if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front()))
76 return false;
77 ReturnInst &RI = cast<ReturnInst>(Entry.front());
Craig Topper66f09ad2014-06-08 22:29:17 +000078 return RI.getReturnValue() == nullptr;
Nico Weber4b2acde2014-05-02 18:35:25 +000079}
Chris Lattnerd5d56782002-01-31 00:45:11 +000080
Chandler Carruth164a2aa62016-06-17 00:11:01 +000081PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &) {
Chris Lattner8f3acc62002-08-18 01:28:30 +000082 bool Changed = false;
Nico Weber4b2acde2014-05-02 18:35:25 +000083
84 // Remove empty functions from the global ctors list.
Richard Smithc167d652014-05-06 01:44:26 +000085 Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
Nico Weber4b2acde2014-05-02 18:35:25 +000086
Peter Collingbourne0dbc7082015-03-19 18:23:29 +000087 // Collect the set of members for each comdat.
88 for (Function &F : M)
89 if (Comdat *C = F.getComdat())
90 ComdatMembers.insert(std::make_pair(C, &F));
91 for (GlobalVariable &GV : M.globals())
92 if (Comdat *C = GV.getComdat())
93 ComdatMembers.insert(std::make_pair(C, &GV));
94 for (GlobalAlias &GA : M.aliases())
95 if (Comdat *C = GA.getComdat())
96 ComdatMembers.insert(std::make_pair(C, &GA));
97
Chris Lattnerec6d7a62003-09-16 19:27:31 +000098 // Loop over the module, adding globals which are obviously necessary.
Peter Collingbourne6d88fde2016-06-22 20:29:42 +000099 for (GlobalObject &GO : M.global_objects()) {
100 Changed |= RemoveUnusedGlobalValue(GO);
101 // Functions with external linkage are needed if they have a body.
Chris Lattnerc8dfbbb2003-09-20 19:00:50 +0000102 // Externally visible & appending globals are needed, if they have an
103 // initializer.
Peter Collingbourne6d88fde2016-06-22 20:29:42 +0000104 if (!GO.isDeclaration() && !GO.hasAvailableExternallyLinkage())
105 if (!GO.isDiscardableIfUnused())
106 GlobalIsNeeded(&GO);
Chris Lattner8f3acc62002-08-18 01:28:30 +0000107 }
108
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000109 for (GlobalAlias &GA : M.aliases()) {
110 Changed |= RemoveUnusedGlobalValue(GA);
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000111 // Externally visible aliases are needed.
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000112 if (!GA.isDiscardableIfUnused())
113 GlobalIsNeeded(&GA);
David Majnemerdad0a642014-06-27 18:19:56 +0000114 }
115
David Majnemer95549492016-05-04 00:20:48 +0000116 for (GlobalIFunc &GIF : M.ifuncs()) {
117 Changed |= RemoveUnusedGlobalValue(GIF);
118 // Externally visible ifuncs are needed.
119 if (!GIF.isDiscardableIfUnused())
120 GlobalIsNeeded(&GIF);
121 }
122
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000123 // Now that all globals which are needed are in the AliveGlobals set, we loop
124 // through the program, deleting those which are not alive.
Chris Lattner8f3acc62002-08-18 01:28:30 +0000125 //
Chris Lattner8f3acc62002-08-18 01:28:30 +0000126
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000127 // The first pass is to drop initializers of global variables which are dead.
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000128 std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
129 for (GlobalVariable &GV : M.globals())
130 if (!AliveGlobals.count(&GV)) {
131 DeadGlobalVars.push_back(&GV); // Keep track of dead globals
132 if (GV.hasInitializer()) {
133 Constant *Init = GV.getInitializer();
134 GV.setInitializer(nullptr);
Bruno Cardoso Lopese2a1fa32014-08-25 17:51:14 +0000135 if (isSafeToDestroyConstant(Init))
136 Init->destroyConstant();
137 }
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000138 }
139
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000140 // The second pass drops the bodies of functions which are dead...
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000141 std::vector<Function *> DeadFunctions;
142 for (Function &F : M)
143 if (!AliveGlobals.count(&F)) {
144 DeadFunctions.push_back(&F); // Keep track of dead globals
145 if (!F.isDeclaration())
146 F.deleteBody();
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000147 }
148
Duncan Sandsbf3ba5a2009-02-17 23:05:26 +0000149 // The third pass drops targets of aliases which are dead...
150 std::vector<GlobalAlias*> DeadAliases;
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000151 for (GlobalAlias &GA : M.aliases())
152 if (!AliveGlobals.count(&GA)) {
153 DeadAliases.push_back(&GA);
154 GA.setAliasee(nullptr);
Duncan Sandsbf3ba5a2009-02-17 23:05:26 +0000155 }
156
David Majnemer95549492016-05-04 00:20:48 +0000157 // The third pass drops targets of ifuncs which are dead...
158 std::vector<GlobalIFunc*> DeadIFuncs;
159 for (GlobalIFunc &GIF : M.ifuncs())
160 if (!AliveGlobals.count(&GIF)) {
161 DeadIFuncs.push_back(&GIF);
162 GIF.setResolver(nullptr);
163 }
164
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000165 // Now that all interferences have been dropped, delete the actual objects
166 // themselves.
167 auto EraseUnusedGlobalValue = [&](GlobalValue *GV) {
168 RemoveUnusedGlobalValue(*GV);
169 GV->eraseFromParent();
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000170 Changed = true;
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000171 };
Chris Lattner8f3acc62002-08-18 01:28:30 +0000172
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000173 NumFunctions += DeadFunctions.size();
174 for (Function *F : DeadFunctions)
175 EraseUnusedGlobalValue(F);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000176
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000177 NumVariables += DeadGlobalVars.size();
178 for (GlobalVariable *GV : DeadGlobalVars)
179 EraseUnusedGlobalValue(GV);
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000180
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000181 NumAliases += DeadAliases.size();
182 for (GlobalAlias *GA : DeadAliases)
183 EraseUnusedGlobalValue(GA);
184
Peter Collingbourne4f3b2df2016-10-25 02:57:27 +0000185 NumIFuncs += DeadIFuncs.size();
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000186 for (GlobalIFunc *GIF : DeadIFuncs)
187 EraseUnusedGlobalValue(GIF);
David Majnemer95549492016-05-04 00:20:48 +0000188
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000189 // Make sure that all memory is released
190 AliveGlobals.clear();
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000191 SeenConstants.clear();
Peter Collingbourne0dbc7082015-03-19 18:23:29 +0000192 ComdatMembers.clear();
Devang Patelc5aa8c62009-08-11 06:31:57 +0000193
Davide Italiano66228c42016-05-03 19:39:15 +0000194 if (Changed)
195 return PreservedAnalyses::none();
196 return PreservedAnalyses::all();
Chris Lattner8f3acc62002-08-18 01:28:30 +0000197}
198
Devang Patel95b18122008-11-11 19:16:41 +0000199/// GlobalIsNeeded - the specific global value as needed, and
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000200/// recursively mark anything that it uses as also needed.
Davide Italiano66228c42016-05-03 19:39:15 +0000201void GlobalDCEPass::GlobalIsNeeded(GlobalValue *G) {
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000202 // If the global is already in the set, no need to reprocess it.
David Blaikie70573dc2014-11-19 07:49:26 +0000203 if (!AliveGlobals.insert(G).second)
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +0000204 return;
David Majnemere0253212014-10-07 07:07:19 +0000205
David Majnemere0253212014-10-07 07:07:19 +0000206 if (Comdat *C = G->getComdat()) {
Peter Collingbourne0dbc7082015-03-19 18:23:29 +0000207 for (auto &&CM : make_range(ComdatMembers.equal_range(C)))
208 GlobalIsNeeded(CM.second);
David Majnemere0253212014-10-07 07:07:19 +0000209 }
210
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000211 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
212 // If this is a global variable, we must make sure to add any global values
213 // referenced by the initializer to the alive set.
Pete Cooper91e4ba22014-07-08 17:06:03 +0000214 if (GV->hasInitializer())
215 MarkUsedGlobalsAsNeeded(GV->getInitializer());
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000216 } else if (GlobalIndirectSymbol *GIS = dyn_cast<GlobalIndirectSymbol>(G)) {
217 // The target of a global alias or ifunc is needed.
218 MarkUsedGlobalsAsNeeded(GIS->getIndirectSymbol());
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000219 } else {
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000220 // Otherwise this must be a function object. We have to scan the body of
221 // the function looking for constants and global values which are used as
222 // operands. Any operands of these types must be processed to ensure that
223 // any globals used will be marked as needed.
224 Function *F = cast<Function>(G);
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +0000225
Vedant Kumar3a63fb32015-12-19 08:52:49 +0000226 for (Use &U : F->operands())
227 MarkUsedGlobalsAsNeeded(cast<Constant>(U.get()));
David Majnemer7fddecc2015-06-17 20:52:32 +0000228
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000229 for (BasicBlock &BB : *F)
230 for (Instruction &I : BB)
231 for (Use &U : I.operands())
232 if (GlobalValue *GV = dyn_cast<GlobalValue>(U))
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000233 GlobalIsNeeded(GV);
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000234 else if (Constant *C = dyn_cast<Constant>(U))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000235 MarkUsedGlobalsAsNeeded(C);
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000236 }
237}
238
Davide Italiano66228c42016-05-03 19:39:15 +0000239void GlobalDCEPass::MarkUsedGlobalsAsNeeded(Constant *C) {
Reid Spencer5f681592004-07-18 00:25:04 +0000240 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattneree8b9512009-10-29 01:21:20 +0000241 return GlobalIsNeeded(GV);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000242
Chris Lattneree8b9512009-10-29 01:21:20 +0000243 // Loop over all of the operands of the constant, adding any globals they
244 // use to the list of needed globals.
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000245 for (Use &U : C->operands()) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000246 // If we've already processed this constant there's no need to do it again.
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000247 Constant *Op = dyn_cast<Constant>(U);
David Blaikie70573dc2014-11-19 07:49:26 +0000248 if (Op && SeenConstants.insert(Op).second)
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000249 MarkUsedGlobalsAsNeeded(Op);
250 }
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000251}
Chris Lattner8f3acc62002-08-18 01:28:30 +0000252
Reid Spencer5f681592004-07-18 00:25:04 +0000253// RemoveUnusedGlobalValue - Loop over all of the uses of the specified
Chris Lattner8f3acc62002-08-18 01:28:30 +0000254// GlobalValue, looking for the constant pointer ref that may be pointing to it.
255// If found, check to see if the constant pointer ref is safe to destroy, and if
256// so, nuke it. This will reduce the reference count on the global value, which
257// might make it deader.
258//
Davide Italiano66228c42016-05-03 19:39:15 +0000259bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) {
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000260 if (GV.use_empty())
261 return false;
Chris Lattner9238d782004-07-18 07:22:58 +0000262 GV.removeDeadConstantUsers();
263 return GV.use_empty();
264}