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