CallGraph.cpp revision 196b8cfe9cfcc452eb2f83aa4ad330c2324f8c7d
1//== CallGraph.cpp - AST-based Call graph  ----------------------*- C++ -*--==//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the AST-based CallGraph.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Analysis/CallGraph.h"
14
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/StmtVisitor.h"
18
19#include "llvm/Support/GraphWriter.h"
20
21using namespace clang;
22
23/// Determine if a declaration should be included in the graph.
24static bool includeInGraph(const Decl *D) {
25  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
26    // We skip function template definitions, as their semantics is
27    // only determined when they are instantiated.
28    if (!FD->isThisDeclarationADefinition() ||
29        FD->isDependentContext())
30      return false;
31
32    IdentifierInfo *II = FD->getIdentifier();
33    if (II && II->getName().startswith("__inline"))
34      return false;
35  }
36
37  if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
38    if (!ID->isThisDeclarationADefinition())
39      return false;
40  }
41
42  return true;
43}
44
45namespace {
46/// A helper class, which walks the AST and locates all the call sites in the
47/// given function body.
48class CGBuilder : public StmtVisitor<CGBuilder> {
49  CallGraph *G;
50  const Decl *FD;
51  CallGraphNode *CallerNode;
52
53public:
54  CGBuilder(CallGraph *g, const Decl *D, CallGraphNode *N)
55    : G(g), FD(D), CallerNode(N) {}
56
57  void VisitStmt(Stmt *S) { VisitChildren(S); }
58
59  void VisitCallExpr(CallExpr *CE) {
60    // TODO: We need to handle ObjC method calls as well.
61    if (FunctionDecl *CalleeDecl = CE->getDirectCallee())
62      if (includeInGraph(CalleeDecl)) {
63        CallGraphNode *CalleeNode = G->getOrInsertFunction(CalleeDecl);
64        CallerNode->addCallee(CalleeNode, G);
65      }
66  };
67
68  void VisitChildren(Stmt *S) {
69    for (Stmt::child_range I = S->children(); I; ++I)
70      if (*I)
71        static_cast<CGBuilder*>(this)->Visit(*I);
72  }
73};
74} // end anonymous namespace
75
76CallGraph::CallGraph() {
77  Root = getOrInsertFunction(0);
78}
79
80CallGraph::~CallGraph() {
81  if (!FunctionMap.empty()) {
82    for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
83        I != E; ++I)
84      delete I->second;
85    FunctionMap.clear();
86  }
87}
88
89void CallGraph::addToCallGraph(Decl* D, bool IsGlobal) {
90  CallGraphNode *Node = getOrInsertFunction(D);
91
92  if (IsGlobal)
93    Root->addCallee(Node, this);
94
95  // Process all the calls by this function as well.
96  CGBuilder builder(this, D, Node);
97  builder.Visit(D->getBody());
98}
99
100void CallGraph::addToCallGraph(DeclContext *DC) {
101  for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
102       I != E; ++I) {
103    Decl *D = *I;
104    switch (D->getKind()) {
105    case Decl::CXXConstructor:
106    case Decl::CXXDestructor:
107    case Decl::CXXConversion:
108    case Decl::CXXMethod:
109    case Decl::Function: {
110      FunctionDecl *FD = cast<FunctionDecl>(D);
111      // We skip function template definitions, as their semantics is
112      // only determined when they are instantiated.
113      if (includeInGraph(FD))
114        // If this function has external linkage, anything could call it.
115        // Note, we are not precise here. For example, the function could have
116        // its address taken.
117        addToCallGraph(FD, FD->isGlobal());
118      break;
119    }
120
121    case Decl::ObjCCategoryImpl:
122    case Decl::ObjCImplementation: {
123      ObjCImplDecl *ID = cast<ObjCImplDecl>(D);
124      for (ObjCContainerDecl::method_iterator MI = ID->meth_begin(),
125          ME = ID->meth_end(); MI != ME; ++MI) {
126        if (includeInGraph(*MI))
127          addToCallGraph(*MI, true);
128      }
129      break;
130    }
131
132    default:
133      break;
134    }
135  }
136}
137
138CallGraphNode *CallGraph::getOrInsertFunction(Decl *F) {
139  CallGraphNode *&Node = FunctionMap[F];
140  if (Node)
141    return Node;
142
143  Node = new CallGraphNode(F);
144  ParentlessNodes.insert(Node);
145  return Node;
146}
147
148void CallGraph::print(raw_ostream &OS) const {
149  OS << " --- Call graph Dump --- \n";
150  for (const_iterator I = begin(), E = end(); I != E; ++I) {
151    OS << "  Function: ";
152    if (I->second == Root)
153      OS << "< root >";
154    else
155      I->second->print(OS);
156    OS << " calls: ";
157    for (CallGraphNode::iterator CI = I->second->begin(),
158        CE = I->second->end(); CI != CE; ++CI) {
159      assert(*CI != Root && "No one can call the root node.");
160      (*CI)->print(OS);
161      OS << " ";
162    }
163    OS << '\n';
164  }
165  OS.flush();
166}
167
168void CallGraph::dump() const {
169  print(llvm::errs());
170}
171
172void CallGraph::viewGraph() const {
173  llvm::ViewGraph(this, "CallGraph");
174}
175
176StringRef CallGraphNode::getName() const {
177  if (const FunctionDecl *D = dyn_cast_or_null<FunctionDecl>(FD))
178    if (const IdentifierInfo *II = D->getIdentifier())
179      return II->getName();
180    return "< >";
181}
182
183void CallGraphNode::print(raw_ostream &os) const {
184  os << getName();
185}
186
187void CallGraphNode::dump() const {
188  print(llvm::errs());
189}
190
191namespace llvm {
192
193template <>
194struct DOTGraphTraits<const CallGraph*> : public DefaultDOTGraphTraits {
195
196  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
197
198  static std::string getNodeLabel(const CallGraphNode *Node,
199                                  const CallGraph *CG) {
200    if (CG->getRoot() == Node) {
201      return "< root >";
202    }
203    return Node->getName();
204  }
205
206};
207}
208