blob: 7c81f180bb34eeb3a8d938bc7d5f597acda0c231 [file] [log] [blame]
Chris Lattner62b7fd12002-04-07 20:49:59 +00001//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
Chris Lattnerbd422e62001-11-26 18:42:17 +00002//
3// This transform is designed to eliminate unreachable internal globals
Chris Lattnerc8e66542002-04-27 06:56:12 +00004// FIXME: GlobalDCE should update the callgraph, not destroy it!
Chris Lattnerbd422e62001-11-26 18:42:17 +00005//
6//===----------------------------------------------------------------------===//
7
Chris Lattner99a53f62002-07-24 17:12:05 +00008#include "llvm/Transforms/IPO.h"
Chris Lattnerbd422e62001-11-26 18:42:17 +00009#include "llvm/Module.h"
Chris Lattner8f3acc62002-08-18 01:28:30 +000010#include "llvm/Constants.h"
11#include "llvm/DerivedTypes.h"
Chris Lattnerb4de02d2002-04-29 18:13:11 +000012#include "llvm/Analysis/CallGraph.h"
Chris Lattner5de22042001-11-27 00:03:19 +000013#include "Support/DepthFirstIterator.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000014#include "Support/Statistic.h"
Chris Lattner8f3acc62002-08-18 01:28:30 +000015#include <algorithm>
Chris Lattner0b18c1d2002-05-10 15:38:35 +000016
Chris Lattner04805fa2002-02-26 21:46:54 +000017namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000018 Statistic<> NumFunctions("globaldce","Number of functions removed");
19 Statistic<> NumVariables("globaldce","Number of global variables removed");
20 Statistic<> NumCPRs("globaldce", "Number of const pointer refs removed");
21 Statistic<> NumConsts("globaldce", "Number of init constants removed");
22
23 bool RemoveUnreachableFunctions(Module &M, CallGraph &CallGraph) {
24 // Calculate which functions are reachable from the external functions in
25 // the call graph.
26 //
27 std::set<CallGraphNode*> ReachableNodes(df_begin(&CallGraph),
28 df_end(&CallGraph));
29
30 // Loop over the functions in the module twice. The first time is used to
31 // drop references that functions have to each other before they are
32 // deleted. The second pass removes the functions that need to be removed.
33 //
34 std::vector<CallGraphNode*> FunctionsToDelete; // Track unused functions
35 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
36 CallGraphNode *N = CallGraph[I];
37
38 if (!ReachableNodes.count(N)) { // Not reachable??
39 I->dropAllReferences();
40 N->removeAllCalledFunctions();
41 FunctionsToDelete.push_back(N);
42 ++NumFunctions;
43 }
44 }
45
46 // Nothing to do if no unreachable functions have been found...
47 if (FunctionsToDelete.empty()) return false;
48
49 // Unreachables functions have been found and should have no references to
50 // them, delete them now.
51 //
52 for (std::vector<CallGraphNode*>::iterator I = FunctionsToDelete.begin(),
53 E = FunctionsToDelete.end(); I != E; ++I)
54 delete CallGraph.removeFunctionFromModule(*I);
55
56 return true;
57 }
58
Chris Lattner04805fa2002-02-26 21:46:54 +000059 struct GlobalDCE : public Pass {
60 // run - Do the GlobalDCE pass on the specified module, optionally updating
61 // the specified callgraph to reflect the changes.
62 //
Chris Lattner7076ff22002-06-25 16:13:21 +000063 bool run(Module &M) {
Chris Lattnerb4de02d2002-04-29 18:13:11 +000064 return RemoveUnreachableFunctions(M, getAnalysis<CallGraph>()) |
65 RemoveUnreachableGlobalVariables(M);
Chris Lattner04805fa2002-02-26 21:46:54 +000066 }
67
Chris Lattnerc8e66542002-04-27 06:56:12 +000068 // getAnalysisUsage - This function works on the call graph of a module.
Chris Lattner04805fa2002-02-26 21:46:54 +000069 // It is capable of updating the call graph to reflect the new state of the
70 // module.
71 //
Chris Lattnerc8e66542002-04-27 06:56:12 +000072 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf0ed55d2002-08-08 19:01:30 +000073 AU.addRequired<CallGraph>();
Chris Lattner04805fa2002-02-26 21:46:54 +000074 }
Chris Lattner8f3acc62002-08-18 01:28:30 +000075
76 private:
77 std::vector<GlobalValue*> WorkList;
78
79 inline bool RemoveIfDead(GlobalValue *GV);
80 void DestroyInitializer(Constant *C);
81
82 bool RemoveUnreachableGlobalVariables(Module &M);
83 bool RemoveUnusedConstantPointerRef(GlobalValue &GV);
84 bool SafeToDestroyConstant(Constant *C);
Chris Lattner04805fa2002-02-26 21:46:54 +000085 };
Chris Lattnera2c09852002-07-26 21:12:44 +000086 RegisterOpt<GlobalDCE> X("globaldce", "Dead Global Elimination");
Chris Lattnerd5d56782002-01-31 00:45:11 +000087}
88
Chris Lattner04805fa2002-02-26 21:46:54 +000089Pass *createGlobalDCEPass() { return new GlobalDCE(); }
Chris Lattner8f3acc62002-08-18 01:28:30 +000090
91
92// RemoveIfDead - If this global value is dead, remove it from the current
93// module and return true.
94//
95bool GlobalDCE::RemoveIfDead(GlobalValue *GV) {
96 // If there is only one use of the global value, it might be a
97 // ConstantPointerRef... which means that this global might actually be
98 // dead.
99 if (GV->use_size() == 1)
100 RemoveUnusedConstantPointerRef(*GV);
101
102 if (!GV->use_empty()) return false;
103
104 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
105 // Eliminate all global variables that are unused, and that are internal, or
106 // do not have an initializer.
107 //
108 if (!GVar->hasExternalLinkage() || !GVar->hasInitializer()) {
109 Constant *Init = GVar->hasInitializer() ? GVar->getInitializer() : 0;
110 GV->getParent()->getGlobalList().erase(GVar);
111 ++NumVariables;
112
113 // If there was an initializer for the global variable, try to destroy it
114 // now.
115 if (Init) DestroyInitializer(Init);
116
117 // If the global variable is still on the worklist, remove it now.
118 std::vector<GlobalValue*>::iterator I = std::find(WorkList.begin(),
119 WorkList.end(), GV);
120 while (I != WorkList.end())
121 I = std::find(WorkList.erase(I), WorkList.end(), GV);
122
123 return true;
124 }
125 } else {
126 Function *F = cast<Function>(GV);
127 // FIXME: TODO
128
129 }
130 return false;
131}
132
133// DestroyInitializer - A global variable was just destroyed and C is its
134// initializer. If we can, destroy C and all of the constants it refers to.
135//
136void GlobalDCE::DestroyInitializer(Constant *C) {
137 // Cannot destroy constants still being used, and cannot destroy primitive
138 // types.
139 if (!C->use_empty() || C->getType()->isPrimitiveType()) return;
140
141 // If this is a CPR, the global value referred to may be dead now! Add it to
142 // the worklist.
143 //
144 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
145 WorkList.push_back(CPR->getValue());
146 C->destroyConstant();
147 ++NumCPRs;
148 } else {
149 bool DestroyContents = true;
150
151 // As an optimization to the GlobalDCE algorithm, do attempt to destroy the
152 // contents of an array of primitive types, because we know that this will
153 // never succeed, and there could be a lot of them.
154 //
155 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
156 if (CA->getType()->getElementType()->isPrimitiveType())
157 DestroyContents = false; // Nothing we can do with the subcontents
158
159 // All other constants refer to other constants. Destroy them if possible
160 // as well.
161 //
162 std::vector<Value*> SubConstants;
163 if (DestroyContents) SubConstants.insert(SubConstants.end(),
164 C->op_begin(), C->op_end());
165
166 // Destroy the actual constant...
167 C->destroyConstant();
168 ++NumConsts;
169
170 if (DestroyContents) {
171 // Remove duplicates from SubConstants, so that we do not call
172 // DestroyInitializer on the same constant twice (the first call might
173 // delete it, so this would be bad)
174 //
175 std::sort(SubConstants.begin(), SubConstants.end());
176 SubConstants.erase(std::unique(SubConstants.begin(), SubConstants.end()),
177 SubConstants.end());
178
179 // Loop over the subconstants, destroying them as well.
180 for (unsigned i = 0, e = SubConstants.size(); i != e; ++i)
181 DestroyInitializer(cast<Constant>(SubConstants[i]));
182 }
183 }
184}
185
186bool GlobalDCE::RemoveUnreachableGlobalVariables(Module &M) {
187 bool Changed = false;
188 WorkList.reserve(M.gsize());
189
190 // Insert all of the globals into the WorkList, making sure to run
191 // RemoveUnusedConstantPointerRef at least once on all globals...
192 //
193 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
194 Changed |= RemoveUnusedConstantPointerRef(*I);
195 WorkList.push_back(I);
196 }
197 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
198 Changed |= RemoveUnusedConstantPointerRef(*I);
199 WorkList.push_back(I);
200 }
201
202 // Loop over the worklist, deleting global objects that we can. Whenever we
203 // delete something that might make something else dead, it gets added to the
204 // worklist.
205 //
206 while (!WorkList.empty()) {
207 GlobalValue *GV = WorkList.back();
208 WorkList.pop_back();
209
210 Changed |= RemoveIfDead(GV);
211 }
212
213 // Make sure that all memory is free'd from the worklist...
214 std::vector<GlobalValue*>().swap(WorkList);
215 return Changed;
216}
217
218
219// RemoveUnusedConstantPointerRef - Loop over all of the uses of the specified
220// GlobalValue, looking for the constant pointer ref that may be pointing to it.
221// If found, check to see if the constant pointer ref is safe to destroy, and if
222// so, nuke it. This will reduce the reference count on the global value, which
223// might make it deader.
224//
225bool GlobalDCE::RemoveUnusedConstantPointerRef(GlobalValue &GV) {
226 for (Value::use_iterator I = GV.use_begin(), E = GV.use_end(); I != E; ++I)
227 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(*I))
228 if (SafeToDestroyConstant(CPR)) { // Only if unreferenced...
229 CPR->destroyConstant();
230 ++NumCPRs;
231 return true;
232 }
233
234 return false;
235}
236
237// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
238// by constants itself. Note that constants cannot be cyclic, so this test is
239// pretty easy to implement recursively.
240//
241bool GlobalDCE::SafeToDestroyConstant(Constant *C) {
242 for (Value::use_iterator I = C->use_begin(), E = C->use_end(); I != E; ++I)
243 if (Constant *User = dyn_cast<Constant>(*I)) {
244 if (!SafeToDestroyConstant(User)) return false;
245 } else {
246 return false;
247 }
248
249 return true;
250}