1 //===-- GlobalDCE.cpp - DCE unreachable internal methods ---------*- C++ -*--=//
3 // This transform is designed to eliminate unreachable internal globals
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Transforms/IPO/GlobalDCE.h"
8 #include "llvm/Analysis/CallGraph.h"
9 #include "llvm/Module.h"
10 #include "llvm/Method.h"
11 #include "Support/DepthFirstIterator.h"
14 static bool RemoveUnreachableMethods(Module *M, cfg::CallGraph &CallGraph) {
15 // Calculate which methods are reachable from the external methods in the call
18 std::set<cfg::CallGraphNode*> ReachableNodes(df_begin(&CallGraph),
21 // Loop over the methods in the module twice. The first time is used to drop
22 // references that methods have to each other before they are deleted. The
23 // second pass removes the methods that need to be removed.
25 std::vector<cfg::CallGraphNode*> MethodsToDelete; // Track unused methods
26 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
27 cfg::CallGraphNode *N = CallGraph[*I];
28 if (!ReachableNodes.count(N)) { // Not reachable??
29 (*I)->dropAllReferences();
30 N->removeAllCalledMethods();
31 MethodsToDelete.push_back(N);
35 // Nothing to do if no unreachable methods have been found...
36 if (MethodsToDelete.empty()) return false;
38 // Unreachables methods have been found and should have no references to them,
41 for (std::vector<cfg::CallGraphNode*>::iterator I = MethodsToDelete.begin(),
42 E = MethodsToDelete.end(); I != E; ++I)
43 delete CallGraph.removeMethodFromModule(*I);
48 bool GlobalDCE::run(Module *M) {
49 return RemoveUnreachableMethods(M, getAnalysis<cfg::CallGraph>());
52 // getAnalysisUsageInfo - This function works on the call graph of a module.
53 // It is capable of updating the call graph to reflect the new state of the
56 void GlobalDCE::getAnalysisUsageInfo(Pass::AnalysisSet &Required,
57 Pass::AnalysisSet &Destroyed,
58 Pass::AnalysisSet &Provided) {
59 Required.push_back(cfg::CallGraph::ID);
60 // FIXME: This should update the callgraph, not destroy it!
61 Destroyed.push_back(cfg::CallGraph::ID);