- Made GlobalDCE worklist driven, making it more successful. Now can handle
[oota-llvm.git] / lib / Transforms / IPO / GlobalDCE.cpp
1 //===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
2 //
3 // This transform is designed to eliminate unreachable internal globals
4 // FIXME: GlobalDCE should update the callgraph, not destroy it!
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Transforms/IPO.h"
9 #include "llvm/Module.h"
10 #include "llvm/Constants.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/GlobalVariable.h"
13 #include "llvm/Analysis/CallGraph.h"
14 #include "Support/DepthFirstIterator.h"
15 #include "Support/StatisticReporter.h"
16 #include <algorithm>
17
18 static Statistic<> NumFunctions("globaldce\t- Number of functions removed");
19 static Statistic<> NumVariables("globaldce\t- Number of global variables removed");
20 static Statistic<> NumCPRs("globaldce\t- Number of const pointer refs removed");
21 static Statistic<> NumConsts("globaldce\t- Number of init constants removed");
22
23 static bool RemoveUnreachableFunctions(Module &M, CallGraph &CallGraph) {
24   // Calculate which functions are reachable from the external functions in the
25   // 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 deleted.
32   // 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
59 namespace {
60   struct GlobalDCE : public Pass {
61     // run - Do the GlobalDCE pass on the specified module, optionally updating
62     // the specified callgraph to reflect the changes.
63     //
64     bool run(Module &M) {
65       return RemoveUnreachableFunctions(M, getAnalysis<CallGraph>()) |
66              RemoveUnreachableGlobalVariables(M);
67     }
68
69     // getAnalysisUsage - This function works on the call graph of a module.
70     // It is capable of updating the call graph to reflect the new state of the
71     // module.
72     //
73     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74       AU.addRequired<CallGraph>();
75     }
76
77   private:
78     std::vector<GlobalValue*> WorkList;
79
80     inline bool RemoveIfDead(GlobalValue *GV);
81     void DestroyInitializer(Constant *C);
82
83     bool RemoveUnreachableGlobalVariables(Module &M);
84     bool RemoveUnusedConstantPointerRef(GlobalValue &GV);
85     bool SafeToDestroyConstant(Constant *C);
86   };
87   RegisterOpt<GlobalDCE> X("globaldce", "Dead Global Elimination");
88 }
89
90 Pass *createGlobalDCEPass() { return new GlobalDCE(); }
91
92
93 // RemoveIfDead - If this global value is dead, remove it from the current
94 // module and return true.
95 //
96 bool GlobalDCE::RemoveIfDead(GlobalValue *GV) {
97   // If there is only one use of the global value, it might be a
98   // ConstantPointerRef... which means that this global might actually be
99   // dead.
100   if (GV->use_size() == 1)
101     RemoveUnusedConstantPointerRef(*GV);
102
103   if (!GV->use_empty()) return false;
104
105   if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
106     // Eliminate all global variables that are unused, and that are internal, or
107     // do not have an initializer.
108     //
109     if (!GVar->hasExternalLinkage() || !GVar->hasInitializer()) {
110       Constant *Init = GVar->hasInitializer() ? GVar->getInitializer() : 0;
111       GV->getParent()->getGlobalList().erase(GVar);
112       ++NumVariables;
113
114       // If there was an initializer for the global variable, try to destroy it
115       // now.
116       if (Init) DestroyInitializer(Init);
117
118       // If the global variable is still on the worklist, remove it now.
119       std::vector<GlobalValue*>::iterator I = std::find(WorkList.begin(),
120                                                         WorkList.end(), GV);
121       while (I != WorkList.end())
122         I = std::find(WorkList.erase(I), WorkList.end(), GV);
123
124       return true;
125     }
126   } else {
127     Function *F = cast<Function>(GV);
128     // FIXME: TODO
129
130   }
131   return false;
132 }
133
134 // DestroyInitializer - A global variable was just destroyed and C is its
135 // initializer. If we can, destroy C and all of the constants it refers to.
136 //
137 void GlobalDCE::DestroyInitializer(Constant *C) {
138   // Cannot destroy constants still being used, and cannot destroy primitive
139   // types.
140   if (!C->use_empty() || C->getType()->isPrimitiveType()) return;
141
142   // If this is a CPR, the global value referred to may be dead now!  Add it to
143   // the worklist.
144   //
145   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
146     WorkList.push_back(CPR->getValue());
147     C->destroyConstant();
148     ++NumCPRs;
149   } else {
150     bool DestroyContents = true;
151
152     // As an optimization to the GlobalDCE algorithm, do attempt to destroy the
153     // contents of an array of primitive types, because we know that this will
154     // never succeed, and there could be a lot of them.
155     //
156     if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
157       if (CA->getType()->getElementType()->isPrimitiveType())
158         DestroyContents = false;    // Nothing we can do with the subcontents
159
160     // All other constants refer to other constants.  Destroy them if possible
161     // as well.
162     //
163     std::vector<Value*> SubConstants;
164     if (DestroyContents) SubConstants.insert(SubConstants.end(),
165                                              C->op_begin(), C->op_end());
166
167     // Destroy the actual constant...
168     C->destroyConstant();
169     ++NumConsts;
170
171     if (DestroyContents) {
172       // Remove duplicates from SubConstants, so that we do not call
173       // DestroyInitializer on the same constant twice (the first call might
174       // delete it, so this would be bad)
175       //
176       std::sort(SubConstants.begin(), SubConstants.end());
177       SubConstants.erase(std::unique(SubConstants.begin(), SubConstants.end()),
178                          SubConstants.end());
179
180       // Loop over the subconstants, destroying them as well.
181       for (unsigned i = 0, e = SubConstants.size(); i != e; ++i)
182         DestroyInitializer(cast<Constant>(SubConstants[i]));
183     }
184   }
185 }
186
187 bool GlobalDCE::RemoveUnreachableGlobalVariables(Module &M) {
188   bool Changed = false;
189   WorkList.reserve(M.gsize());
190
191   // Insert all of the globals into the WorkList, making sure to run
192   // RemoveUnusedConstantPointerRef at least once on all globals...
193   //
194   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
195     Changed |= RemoveUnusedConstantPointerRef(*I);
196     WorkList.push_back(I);
197   }
198   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
199     Changed |= RemoveUnusedConstantPointerRef(*I);
200     WorkList.push_back(I);
201   }
202
203   // Loop over the worklist, deleting global objects that we can.  Whenever we
204   // delete something that might make something else dead, it gets added to the
205   // worklist.
206   //
207   while (!WorkList.empty()) {
208     GlobalValue *GV = WorkList.back();
209     WorkList.pop_back();
210
211     Changed |= RemoveIfDead(GV);
212   }
213
214   // Make sure that all memory is free'd from the worklist...
215   std::vector<GlobalValue*>().swap(WorkList);
216   return Changed;
217 }
218
219
220 // RemoveUnusedConstantPointerRef - Loop over all of the uses of the specified
221 // GlobalValue, looking for the constant pointer ref that may be pointing to it.
222 // If found, check to see if the constant pointer ref is safe to destroy, and if
223 // so, nuke it.  This will reduce the reference count on the global value, which
224 // might make it deader.
225 //
226 bool GlobalDCE::RemoveUnusedConstantPointerRef(GlobalValue &GV) {
227   for (Value::use_iterator I = GV.use_begin(), E = GV.use_end(); I != E; ++I)
228     if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(*I))
229       if (SafeToDestroyConstant(CPR)) {  // Only if unreferenced...
230         CPR->destroyConstant();
231         ++NumCPRs;
232         return true;
233       }
234
235   return false;
236 }
237
238 // SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
239 // by constants itself.  Note that constants cannot be cyclic, so this test is
240 // pretty easy to implement recursively.
241 //
242 bool GlobalDCE::SafeToDestroyConstant(Constant *C) {
243   for (Value::use_iterator I = C->use_begin(), E = C->use_end(); I != E; ++I)
244     if (Constant *User = dyn_cast<Constant>(*I)) {
245       if (!SafeToDestroyConstant(User)) return false;
246     } else {
247       return false;
248     }
249
250   return true;
251 }