1//===- CallGraph.cpp - AST-based Call graph -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the AST-based CallGraph.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Analysis/CallGraph.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclBase.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/LLVM.h"
23#include "llvm/ADT/PostOrderIterator.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Support/Casting.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/DOTGraphTraits.h"
28#include "llvm/Support/GraphWriter.h"
29#include "llvm/Support/raw_ostream.h"
30#include <cassert>
31#include <memory>
32#include <string>
33
34using namespace clang;
35
36#define DEBUG_TYPE "CallGraph"
37
38STATISTIC(NumObjCCallEdges, "Number of Objective-C method call edges");
39STATISTIC(NumBlockCallEdges, "Number of block call edges");
40
41namespace {
42
43/// A helper class, which walks the AST and locates all the call sites in the
44/// given function body.
45class CGBuilder : public StmtVisitor<CGBuilder> {
46 CallGraph *G;
47 CallGraphNode *CallerNode;
48
49public:
50 CGBuilder(CallGraph *g, CallGraphNode *N) : G(g), CallerNode(N) {}
51
52 void VisitStmt(Stmt *S) { VisitChildren(S); }
53
54 Decl *getDeclFromCall(CallExpr *CE) {
55 if (FunctionDecl *CalleeDecl = CE->getDirectCallee())
56 return CalleeDecl;
57
58 // Simple detection of a call through a block.
59 Expr *CEE = CE->getCallee()->IgnoreParenImpCasts();
60 if (BlockExpr *Block = dyn_cast<BlockExpr>(Val: CEE)) {
61 NumBlockCallEdges++;
62 return Block->getBlockDecl();
63 }
64
65 return nullptr;
66 }
67
68 void addCalledDecl(Decl *D, Expr *CallExpr) {
69 if (G->includeCalleeInGraph(D)) {
70 CallGraphNode *CalleeNode = G->getOrInsertNode(D);
71 CallerNode->addCallee(Call: {CalleeNode, CallExpr});
72 }
73 }
74
75 void VisitCallExpr(CallExpr *CE) {
76 if (Decl *D = getDeclFromCall(CE))
77 addCalledDecl(D, CallExpr: CE);
78 VisitChildren(S: CE);
79 }
80
81 void VisitLambdaExpr(LambdaExpr *LE) {
82 if (FunctionTemplateDecl *FTD = LE->getDependentCallOperator())
83 for (FunctionDecl *FD : FTD->specializations())
84 G->VisitFunctionDecl(FD);
85 else if (CXXMethodDecl *MD = LE->getCallOperator())
86 G->VisitFunctionDecl(FD: MD);
87 }
88
89 void VisitCXXNewExpr(CXXNewExpr *E) {
90 if (FunctionDecl *FD = E->getOperatorNew())
91 addCalledDecl(D: FD, CallExpr: E);
92 VisitChildren(S: E);
93 }
94
95 void VisitCXXConstructExpr(CXXConstructExpr *E) {
96 CXXConstructorDecl *Ctor = E->getConstructor();
97 if (FunctionDecl *Def = Ctor->getDefinition())
98 addCalledDecl(D: Def, CallExpr: E);
99 VisitChildren(S: E);
100 }
101
102 // Include the evaluation of the default argument.
103 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
104 Visit(S: E->getExpr());
105 }
106
107 // Include the evaluation of the default initializers in a class.
108 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
109 Visit(S: E->getExpr());
110 }
111
112 // Adds may-call edges for the ObjC message sends.
113 void VisitObjCMessageExpr(ObjCMessageExpr *ME) {
114 if (ObjCInterfaceDecl *IDecl = ME->getReceiverInterface()) {
115 Selector Sel = ME->getSelector();
116
117 // Find the callee definition within the same translation unit.
118 Decl *D = nullptr;
119 if (ME->isInstanceMessage())
120 D = IDecl->lookupPrivateMethod(Sel);
121 else
122 D = IDecl->lookupPrivateClassMethod(Sel);
123 if (D) {
124 addCalledDecl(D, CallExpr: ME);
125 NumObjCCallEdges++;
126 }
127 }
128 }
129
130 void VisitChildren(Stmt *S) {
131 for (Stmt *SubStmt : S->children())
132 if (SubStmt)
133 this->Visit(S: SubStmt);
134 }
135};
136
137} // namespace
138
139void CallGraph::addNodesForBlocks(DeclContext *D) {
140 if (BlockDecl *BD = dyn_cast<BlockDecl>(Val: D))
141 addNodeForDecl(D: BD, IsGlobal: true);
142
143 for (auto *I : D->decls())
144 if (auto *DC = dyn_cast<DeclContext>(Val: I))
145 addNodesForBlocks(D: DC);
146}
147
148CallGraph::CallGraph() {
149 ShouldWalkTypesOfTypeLocs = false;
150 ShouldVisitTemplateInstantiations = true;
151 ShouldVisitImplicitCode = true;
152 Root = getOrInsertNode(nullptr);
153}
154
155CallGraph::~CallGraph() = default;
156
157bool CallGraph::includeInGraph(const Decl *D) {
158 assert(D);
159 if (!D->hasBody())
160 return false;
161
162 return includeCalleeInGraph(D);
163}
164
165bool CallGraph::includeCalleeInGraph(const Decl *D) {
166 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
167 // We skip function template definitions, as their semantics is
168 // only determined when they are instantiated.
169 if (FD->isDependentContext())
170 return false;
171
172 IdentifierInfo *II = FD->getIdentifier();
173 if (II && II->getName().starts_with(Prefix: "__inline"))
174 return false;
175 }
176
177 return true;
178}
179
180void CallGraph::addNodeForDecl(Decl* D, bool IsGlobal) {
181 assert(D);
182
183 // Allocate a new node, mark it as root, and process its calls.
184 CallGraphNode *Node = getOrInsertNode(D);
185
186 // Process all the calls by this function as well.
187 CGBuilder builder(this, Node);
188 if (Stmt *Body = D->getBody())
189 builder.Visit(S: Body);
190
191 // Include C++ constructor member initializers.
192 if (auto constructor = dyn_cast<CXXConstructorDecl>(Val: D)) {
193 for (CXXCtorInitializer *init : constructor->inits()) {
194 builder.Visit(S: init->getInit());
195 }
196 }
197}
198
199CallGraphNode *CallGraph::getNode(const Decl *F) const {
200 FunctionMapTy::const_iterator I = FunctionMap.find(Val: F);
201 if (I == FunctionMap.end()) return nullptr;
202 return I->second.get();
203}
204
205CallGraphNode *CallGraph::getOrInsertNode(Decl *F) {
206 if (F && !isa<ObjCMethodDecl>(Val: F))
207 F = F->getCanonicalDecl();
208
209 std::unique_ptr<CallGraphNode> &Node = FunctionMap[F];
210 if (Node)
211 return Node.get();
212
213 Node = std::make_unique<CallGraphNode>(args&: F);
214 // Make Root node a parent of all functions to make sure all are reachable.
215 if (F)
216 Root->addCallee(Call: {Node.get(), /*Call=*/nullptr});
217 return Node.get();
218}
219
220void CallGraph::print(raw_ostream &OS) const {
221 OS << " --- Call graph Dump --- \n";
222
223 // We are going to print the graph in reverse post order, partially, to make
224 // sure the output is deterministic.
225 llvm::ReversePostOrderTraversal<const CallGraph *> RPOT(this);
226 for (const CallGraphNode *N : RPOT) {
227 OS << " Function: ";
228 if (N == Root)
229 OS << "< root >";
230 else
231 N->print(os&: OS);
232
233 OS << " calls: ";
234 for (CallGraphNode::const_iterator CI = N->begin(),
235 CE = N->end(); CI != CE; ++CI) {
236 assert(CI->Callee != Root && "No one can call the root node.");
237 CI->Callee->print(os&: OS);
238 OS << " ";
239 }
240 OS << '\n';
241 }
242 OS.flush();
243}
244
245LLVM_DUMP_METHOD void CallGraph::dump() const {
246 print(OS&: llvm::errs());
247}
248
249void CallGraph::viewGraph() const {
250 llvm::ViewGraph(G: this, Name: "CallGraph");
251}
252
253void CallGraphNode::print(raw_ostream &os) const {
254 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: FD))
255 return ND->printQualifiedName(OS&: os);
256 os << "< >";
257}
258
259LLVM_DUMP_METHOD void CallGraphNode::dump() const {
260 print(os&: llvm::errs());
261}
262
263namespace llvm {
264
265template <>
266struct DOTGraphTraits<const CallGraph*> : public DefaultDOTGraphTraits {
267 DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
268
269 static std::string getNodeLabel(const CallGraphNode *Node,
270 const CallGraph *CG) {
271 if (CG->getRoot() == Node) {
272 return "< root >";
273 }
274 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: Node->getDecl()))
275 return ND->getNameAsString();
276 else
277 return "< >";
278 }
279};
280
281} // namespace llvm
282