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