blob: e50cdb7358cf8aed23454d892b9bd2cbed408ae3 [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
Chris Lattner99a53f62002-07-24 17:12:05 +000018#include "llvm/Transforms/IPO.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"
Nico Weber4b2acde2014-05-02 18:35:25 +000024#include "llvm/Transforms/Utils/CtorUtils.h"
Bruno Cardoso Lopese2a1fa32014-08-25 17:51:14 +000025#include "llvm/Transforms/Utils/GlobalStatus.h"
Chris Lattnerec6d7a62003-09-16 19:27:31 +000026#include "llvm/Pass.h"
Chris Lattnerf52e03c2003-11-21 21:54:22 +000027using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000028
Chandler Carruth964daaa2014-04-22 02:55:47 +000029#define DEBUG_TYPE "globaldce"
30
Duncan Sands821d13c2009-01-05 20:39:50 +000031STATISTIC(NumAliases , "Number of global aliases removed");
Chris Lattner1631bcb2006-12-19 22:09:18 +000032STATISTIC(NumFunctions, "Number of functions removed");
33STATISTIC(NumVariables, "Number of global variables removed");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000034
Chris Lattner1631bcb2006-12-19 22:09:18 +000035namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000036 struct GlobalDCE : public ModulePass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000037 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000038 GlobalDCE() : ModulePass(ID) {
39 initializeGlobalDCEPass(*PassRegistry::getPassRegistry());
40 }
Duncan Sandsf5dbbae2009-01-05 20:37:33 +000041
Chris Lattner04805fa2002-02-26 21:46:54 +000042 // run - Do the GlobalDCE pass on the specified module, optionally updating
43 // the specified callgraph to reflect the changes.
44 //
Craig Topper3e4c6972014-03-05 09:10:37 +000045 bool runOnModule(Module &M) override;
Chris Lattner8f3acc62002-08-18 01:28:30 +000046
47 private:
Pete Cooper91e4ba22014-07-08 17:06:03 +000048 SmallPtrSet<GlobalValue*, 32> AliveGlobals;
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +000049 SmallPtrSet<Constant *, 8> SeenConstants;
Chris Lattner8f3acc62002-08-18 01:28:30 +000050
Duncan Sandsf5dbbae2009-01-05 20:37:33 +000051 /// GlobalIsNeeded - mark the specific global value as needed, and
Chris Lattnerec6d7a62003-09-16 19:27:31 +000052 /// recursively mark anything that it uses as also needed.
53 void GlobalIsNeeded(GlobalValue *GV);
54 void MarkUsedGlobalsAsNeeded(Constant *C);
Chris Lattner8f3acc62002-08-18 01:28:30 +000055
Reid Spencer5f681592004-07-18 00:25:04 +000056 bool RemoveUnusedGlobalValue(GlobalValue &GV);
Chris Lattner04805fa2002-02-26 21:46:54 +000057 };
Richard Smithc167d652014-05-06 01:44:26 +000058}
Nico Weber4b2acde2014-05-02 18:35:25 +000059
60/// Returns true if F contains only a single "ret" instruction.
Richard Smithc167d652014-05-06 01:44:26 +000061static bool isEmptyFunction(Function *F) {
Nico Weber4b2acde2014-05-02 18:35:25 +000062 BasicBlock &Entry = F->getEntryBlock();
63 if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front()))
64 return false;
65 ReturnInst &RI = cast<ReturnInst>(Entry.front());
Craig Topper66f09ad2014-06-08 22:29:17 +000066 return RI.getReturnValue() == nullptr;
Nico Weber4b2acde2014-05-02 18:35:25 +000067}
Chris Lattnerd5d56782002-01-31 00:45:11 +000068
Dan Gohmand78c4002008-05-13 00:00:25 +000069char GlobalDCE::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +000070INITIALIZE_PASS(GlobalDCE, "globaldce",
Owen Andersondf7a4f22010-10-07 22:25:06 +000071 "Dead Global Elimination", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000072
Chris Lattner4f2cf032004-09-20 04:48:05 +000073ModulePass *llvm::createGlobalDCEPass() { return new GlobalDCE(); }
Chris Lattner8f3acc62002-08-18 01:28:30 +000074
Chris Lattner4f2cf032004-09-20 04:48:05 +000075bool GlobalDCE::runOnModule(Module &M) {
Chris Lattner8f3acc62002-08-18 01:28:30 +000076 bool Changed = false;
Nico Weber4b2acde2014-05-02 18:35:25 +000077
78 // Remove empty functions from the global ctors list.
Richard Smithc167d652014-05-06 01:44:26 +000079 Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
Nico Weber4b2acde2014-05-02 18:35:25 +000080
David Majnemerdad0a642014-06-27 18:19:56 +000081 typedef std::multimap<const Comdat *, GlobalValue *> ComdatGVPairsTy;
82 ComdatGVPairsTy ComdatGVPairs;
83
Chris Lattnerec6d7a62003-09-16 19:27:31 +000084 // Loop over the module, adding globals which are obviously necessary.
Chris Lattner8f3acc62002-08-18 01:28:30 +000085 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Reid Spencer5f681592004-07-18 00:25:04 +000086 Changed |= RemoveUnusedGlobalValue(*I);
Chris Lattnerec6d7a62003-09-16 19:27:31 +000087 // Functions with external linkage are needed if they have a body
David Majnemerdad0a642014-06-27 18:19:56 +000088 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
89 if (!I->isDiscardableIfUnused())
90 GlobalIsNeeded(I);
91 else if (const Comdat *C = I->getComdat())
92 ComdatGVPairs.insert(std::make_pair(C, I));
93 }
Chris Lattner8f3acc62002-08-18 01:28:30 +000094 }
Chris Lattnerec6d7a62003-09-16 19:27:31 +000095
Anton Korobeynikova97b6942007-04-25 14:27:10 +000096 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
97 I != E; ++I) {
Reid Spencer5f681592004-07-18 00:25:04 +000098 Changed |= RemoveUnusedGlobalValue(*I);
Chris Lattnerc8dfbbb2003-09-20 19:00:50 +000099 // Externally visible & appending globals are needed, if they have an
100 // initializer.
David Majnemerdad0a642014-06-27 18:19:56 +0000101 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
102 if (!I->isDiscardableIfUnused())
103 GlobalIsNeeded(I);
104 else if (const Comdat *C = I->getComdat())
105 ComdatGVPairs.insert(std::make_pair(C, I));
106 }
Chris Lattner8f3acc62002-08-18 01:28:30 +0000107 }
108
Anton Korobeynikova97b6942007-04-25 14:27:10 +0000109 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
110 I != E; ++I) {
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000111 Changed |= RemoveUnusedGlobalValue(*I);
112 // Externally visible aliases are needed.
David Majnemerdad0a642014-06-27 18:19:56 +0000113 if (!I->isDiscardableIfUnused()) {
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000114 GlobalIsNeeded(I);
David Majnemerdad0a642014-06-27 18:19:56 +0000115 } else if (const Comdat *C = I->getComdat()) {
116 ComdatGVPairs.insert(std::make_pair(C, I));
117 }
118 }
119
120 for (ComdatGVPairsTy::iterator I = ComdatGVPairs.begin(),
121 E = ComdatGVPairs.end();
122 I != E;) {
123 ComdatGVPairsTy::iterator UB = ComdatGVPairs.upper_bound(I->first);
124 bool CanDiscard = std::all_of(I, UB, [](ComdatGVPairsTy::value_type Pair) {
125 return Pair.second->isDiscardableIfUnused();
126 });
127 if (!CanDiscard) {
128 std::for_each(I, UB, [this](ComdatGVPairsTy::value_type Pair) {
129 GlobalIsNeeded(Pair.second);
130 });
131 }
132 I = UB;
Anton Korobeynikova97b6942007-04-25 14:27:10 +0000133 }
134
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000135 // Now that all globals which are needed are in the AliveGlobals set, we loop
136 // through the program, deleting those which are not alive.
Chris Lattner8f3acc62002-08-18 01:28:30 +0000137 //
Chris Lattner8f3acc62002-08-18 01:28:30 +0000138
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000139 // The first pass is to drop initializers of global variables which are dead.
140 std::vector<GlobalVariable*> DeadGlobalVars; // Keep track of dead globals
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +0000141 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
142 I != E; ++I)
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000143 if (!AliveGlobals.count(I)) {
144 DeadGlobalVars.push_back(I); // Keep track of dead globals
Bruno Cardoso Lopese2a1fa32014-08-25 17:51:14 +0000145 if (I->hasInitializer()) {
146 Constant *Init = I->getInitializer();
147 I->setInitializer(nullptr);
148 if (isSafeToDestroyConstant(Init))
149 Init->destroyConstant();
150 }
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000151 }
152
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000153 // The second pass drops the bodies of functions which are dead...
154 std::vector<Function*> DeadFunctions;
155 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
156 if (!AliveGlobals.count(I)) {
157 DeadFunctions.push_back(I); // Keep track of dead globals
Reid Spencer5301e7c2007-01-30 20:08:39 +0000158 if (!I->isDeclaration())
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000159 I->deleteBody();
160 }
161
Duncan Sandsbf3ba5a2009-02-17 23:05:26 +0000162 // The third pass drops targets of aliases which are dead...
163 std::vector<GlobalAlias*> DeadAliases;
164 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
165 ++I)
166 if (!AliveGlobals.count(I)) {
167 DeadAliases.push_back(I);
Craig Topperf40110f2014-04-25 05:29:35 +0000168 I->setAliasee(nullptr);
Duncan Sandsbf3ba5a2009-02-17 23:05:26 +0000169 }
170
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000171 if (!DeadFunctions.empty()) {
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000172 // Now that all interferences have been dropped, delete the actual objects
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000173 // themselves.
174 for (unsigned i = 0, e = DeadFunctions.size(); i != e; ++i) {
Reid Spencer5f681592004-07-18 00:25:04 +0000175 RemoveUnusedGlobalValue(*DeadFunctions[i]);
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000176 M.getFunctionList().erase(DeadFunctions[i]);
177 }
178 NumFunctions += DeadFunctions.size();
179 Changed = true;
Chris Lattner8f3acc62002-08-18 01:28:30 +0000180 }
181
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000182 if (!DeadGlobalVars.empty()) {
183 for (unsigned i = 0, e = DeadGlobalVars.size(); i != e; ++i) {
Reid Spencer5f681592004-07-18 00:25:04 +0000184 RemoveUnusedGlobalValue(*DeadGlobalVars[i]);
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000185 M.getGlobalList().erase(DeadGlobalVars[i]);
186 }
187 NumVariables += DeadGlobalVars.size();
188 Changed = true;
189 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000190
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000191 // Now delete any dead aliases.
Duncan Sandsbf3ba5a2009-02-17 23:05:26 +0000192 if (!DeadAliases.empty()) {
193 for (unsigned i = 0, e = DeadAliases.size(); i != e; ++i) {
194 RemoveUnusedGlobalValue(*DeadAliases[i]);
195 M.getAliasList().erase(DeadAliases[i]);
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000196 }
Duncan Sandsbf3ba5a2009-02-17 23:05:26 +0000197 NumAliases += DeadAliases.size();
198 Changed = true;
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000199 }
200
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000201 // Make sure that all memory is released
202 AliveGlobals.clear();
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000203 SeenConstants.clear();
Devang Patelc5aa8c62009-08-11 06:31:57 +0000204
Chris Lattner8f3acc62002-08-18 01:28:30 +0000205 return Changed;
206}
207
Devang Patel95b18122008-11-11 19:16:41 +0000208/// GlobalIsNeeded - the specific global value as needed, and
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000209/// recursively mark anything that it uses as also needed.
210void GlobalDCE::GlobalIsNeeded(GlobalValue *G) {
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000211 // If the global is already in the set, no need to reprocess it.
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +0000212 if (!AliveGlobals.insert(G))
213 return;
214
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000215 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
216 // If this is a global variable, we must make sure to add any global values
217 // referenced by the initializer to the alive set.
Pete Cooper91e4ba22014-07-08 17:06:03 +0000218 if (GV->hasInitializer())
219 MarkUsedGlobalsAsNeeded(GV->getInitializer());
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000220 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(G)) {
221 // The target of a global alias is needed.
Duncan Sands187c5712009-01-07 18:45:53 +0000222 MarkUsedGlobalsAsNeeded(GA->getAliasee());
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000223 } else {
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000224 // Otherwise this must be a function object. We have to scan the body of
225 // the function looking for constants and global values which are used as
226 // operands. Any operands of these types must be processed to ensure that
227 // any globals used will be marked as needed.
228 Function *F = cast<Function>(G);
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +0000229
Peter Collingbourne3fa50f92013-09-16 01:08:15 +0000230 if (F->hasPrefixData())
231 MarkUsedGlobalsAsNeeded(F->getPrefixData());
232
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000233 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000234 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000235 for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U)
236 if (GlobalValue *GV = dyn_cast<GlobalValue>(*U))
237 GlobalIsNeeded(GV);
238 else if (Constant *C = dyn_cast<Constant>(*U))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000239 MarkUsedGlobalsAsNeeded(C);
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000240 }
241}
242
243void GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) {
Reid Spencer5f681592004-07-18 00:25:04 +0000244 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattneree8b9512009-10-29 01:21:20 +0000245 return GlobalIsNeeded(GV);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000246
Chris Lattneree8b9512009-10-29 01:21:20 +0000247 // Loop over all of the operands of the constant, adding any globals they
248 // use to the list of needed globals.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000249 for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I) {
250 // If we've already processed this constant there's no need to do it again.
Benjamin Krameradc17272013-04-13 16:11:14 +0000251 Constant *Op = dyn_cast<Constant>(*I);
252 if (Op && SeenConstants.insert(Op))
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000253 MarkUsedGlobalsAsNeeded(Op);
254 }
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000255}
Chris Lattner8f3acc62002-08-18 01:28:30 +0000256
Reid Spencer5f681592004-07-18 00:25:04 +0000257// RemoveUnusedGlobalValue - Loop over all of the uses of the specified
Chris Lattner8f3acc62002-08-18 01:28:30 +0000258// GlobalValue, looking for the constant pointer ref that may be pointing to it.
259// If found, check to see if the constant pointer ref is safe to destroy, and if
260// so, nuke it. This will reduce the reference count on the global value, which
261// might make it deader.
262//
Reid Spencer5f681592004-07-18 00:25:04 +0000263bool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) {
Chris Lattner9238d782004-07-18 07:22:58 +0000264 if (GV.use_empty()) return false;
265 GV.removeDeadConstantUsers();
266 return GV.use_empty();
267}