LLVM 22.0.0git
CallGraph.cpp
Go to the documentation of this file.
1//===- CallGraph.cpp - Build a Module's 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
11#include "llvm/ADT/STLExtras.h"
14#include "llvm/Config/llvm-config.h"
16#include "llvm/IR/Function.h"
17#include "llvm/IR/Module.h"
18#include "llvm/IR/PassManager.h"
20#include "llvm/Pass.h"
22#include "llvm/Support/Debug.h"
24#include <cassert>
25
26using namespace llvm;
27
28//===----------------------------------------------------------------------===//
29// Implementations of the CallGraph class methods.
30//
31
33 : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)),
34 CallsExternalNode(std::make_unique<CallGraphNode>(this, nullptr)) {
35 // Add every interesting function to the call graph.
36 for (Function &F : M)
38}
39
41 : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)),
42 ExternalCallingNode(Arg.ExternalCallingNode),
43 CallsExternalNode(std::move(Arg.CallsExternalNode)) {
44 Arg.FunctionMap.clear();
45 Arg.ExternalCallingNode = nullptr;
46
47 // Update parent CG for all call graph's nodes.
48 CallsExternalNode->CG = this;
49 for (auto &P : FunctionMap)
50 P.second->CG = this;
51}
52
54 // CallsExternalNode is not in the function map, delete it explicitly.
55 if (CallsExternalNode)
56 CallsExternalNode->allReferencesDropped();
57
58// Reset all node's use counts to zero before deleting them to prevent an
59// assertion from firing.
60#ifndef NDEBUG
61 for (auto &I : FunctionMap)
62 I.second->allReferencesDropped();
63#endif
64}
65
67 ModuleAnalysisManager::Invalidator &) {
68 // Check whether the analysis, all analyses on functions, or the function's
69 // CFG have been preserved.
70 auto PAC = PA.getChecker<CallGraphAnalysis>();
71 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>());
72}
73
76
77 // If this function has external linkage or has its address taken and
78 // it is not a callback, then anything could call it.
79 if (!F->hasLocalLinkage() ||
80 F->hasAddressTaken(nullptr, /*IgnoreCallbackUses=*/true,
81 /* IgnoreAssumeLikeCalls */ true,
82 /* IgnoreLLVMUsed */ false))
83 ExternalCallingNode->addCalledFunction(nullptr, Node);
84
86}
87
89 Function *F = Node->getFunction();
90
91 // If this function is not defined in this translation unit, it could call
92 // anything.
93 if (F->isDeclaration() && !F->hasFnAttribute(Attribute::NoCallback))
94 Node->addCalledFunction(nullptr, CallsExternalNode.get());
95
96 // Look for calls by this function.
97 for (BasicBlock &BB : *F)
98 for (Instruction &I : BB) {
99 if (auto *Call = dyn_cast<CallBase>(&I)) {
100 const Function *Callee = Call->getCalledFunction();
101 if (!Callee)
102 Node->addCalledFunction(Call, CallsExternalNode.get());
103 else
104 Node->addCalledFunction(Call, getOrInsertFunction(Callee));
105
106 // Add reference to callback functions.
108 Node->addCalledFunction(nullptr, getOrInsertFunction(CB));
109 });
110 }
111 }
112}
113
115 // Print in a deterministic order by sorting CallGraphNodes by name. We do
116 // this here to avoid slowing down the non-printing fast path.
117
119 Nodes.reserve(FunctionMap.size());
120
121 for (const auto &I : *this)
122 Nodes.push_back(I.second.get());
123
124 llvm::sort(Nodes, [](CallGraphNode *LHS, CallGraphNode *RHS) {
125 if (Function *LF = LHS->getFunction())
126 if (Function *RF = RHS->getFunction())
127 return LF->getName() < RF->getName();
128
129 return RHS->getFunction() != nullptr;
130 });
131
132 for (CallGraphNode *CN : Nodes)
133 CN->print(OS);
134}
135
136#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
138#endif
139
140// removeFunctionFromModule - Unlink the function from this module, returning
141// it. Because this removes the function from the module, the call graph node
142// is destroyed. This is only valid if the function does not call any other
143// functions (ie, there are no edges in it's CGN). The easiest way to do this
144// is to dropAllReferences before calling this.
145//
147 assert(CGN->empty() && "Cannot remove function from call "
148 "graph if it references other functions!");
149 Function *F = CGN->getFunction(); // Get the function for the call graph node
150 FunctionMap.erase(F); // Remove the call graph node from the map
151
152 M.getFunctionList().remove(F);
153 return F;
154}
155
156// getOrInsertFunction - This method is identical to calling operator[], but
157// it will insert a new CallGraphNode for the specified function if one does
158// not already exist.
160 auto &CGN = FunctionMap[F];
161 if (CGN)
162 return CGN.get();
163
164 assert((!F || F->getParent() == &M) && "Function not in current module!");
165 CGN = std::make_unique<CallGraphNode>(this, const_cast<Function *>(F));
166 return CGN.get();
167}
168
169//===----------------------------------------------------------------------===//
170// Implementations of the CallGraphNode class methods.
171//
172
174 if (Function *F = getFunction())
175 OS << "Call graph node for function: '" << F->getName() << "'";
176 else
177 OS << "Call graph node <<null function>>";
178
179 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
180
181 for (const auto &I : *this) {
182 OS << " CS<" << I.first << "> calls ";
183 if (Function *FI = I.second->getFunction())
184 OS << "function '" << FI->getName() <<"'\n";
185 else
186 OS << "external node\n";
187 }
188 OS << '\n';
189}
190
191#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
193#endif
194
195/// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
196/// from this node to the specified callee function.
198 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
199 assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
200 CallRecord &CR = *I;
201 if (CR.second == Callee && !CR.first) {
202 Callee->DropRef();
203 *I = CalledFunctions.back();
204 CalledFunctions.pop_back();
205 return;
206 }
207 }
208}
209
210/// replaceCallEdge - This method replaces the edge in the node for the
211/// specified call site with a new one. Note that this method takes linear
212/// time, so it should be used sparingly.
214 CallGraphNode *NewNode) {
215 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
216 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
217 if (I->first && *I->first == &Call) {
218 I->second->DropRef();
219 I->first = &NewCall;
220 I->second = NewNode;
221 NewNode->AddRef();
222
223 // Refresh callback references. Do not resize CalledFunctions if the
224 // number of callbacks is the same for new and old call sites.
227 forEachCallbackFunction(Call, [this, &OldCBs](Function *CB) {
228 OldCBs.push_back(CG->getOrInsertFunction(CB));
229 });
230 forEachCallbackFunction(NewCall, [this, &NewCBs](Function *CB) {
231 NewCBs.push_back(CG->getOrInsertFunction(CB));
232 });
233 if (OldCBs.size() == NewCBs.size()) {
234 for (unsigned N = 0; N < OldCBs.size(); ++N) {
235 CallGraphNode *OldNode = OldCBs[N];
236 CallGraphNode *NewNode = NewCBs[N];
237 for (auto J = CalledFunctions.begin();; ++J) {
238 assert(J != CalledFunctions.end() &&
239 "Cannot find callsite to update!");
240 if (!J->first && J->second == OldNode) {
241 J->second = NewNode;
242 OldNode->DropRef();
243 NewNode->AddRef();
244 break;
245 }
246 }
247 }
248 } else {
249 for (auto *CGN : OldCBs)
251 for (auto *CGN : NewCBs)
252 addCalledFunction(nullptr, CGN);
253 }
254 return;
255 }
256 }
257}
258
259// Provide an explicit template instantiation for the static ID.
260AnalysisKey CallGraphAnalysis::Key;
261
267
270 auto &CG = AM.getResult<CallGraphAnalysis>(M);
271 unsigned sccNum = 0;
272 OS << "SCCs for the program in PostOrder:";
273 for (scc_iterator<CallGraph *> SCCI = scc_begin(&CG); !SCCI.isAtEnd();
274 ++SCCI) {
275 const std::vector<CallGraphNode *> &nextSCC = *SCCI;
276 OS << "\nSCC #" << ++sccNum << ": ";
277 ListSeparator LS;
278 for (CallGraphNode *CGN : nextSCC)
279 OS << LS
280 << (CGN->getFunction() ? CGN->getFunction()->getName()
281 : "external node");
282 if (nextSCC.size() == 1 && SCCI.hasCycle())
283 OS << " (Has self-loop).";
284 }
285 OS << "\n";
286 return PreservedAnalyses::all();
287}
288
289//===----------------------------------------------------------------------===//
290// Out-of-line definitions of CallGraphAnalysis class members.
291//
292
293//===----------------------------------------------------------------------===//
294// Implementations of the CallGraphWrapperPass class methods.
295//
296
298
300
304
306 // All the real work is done in the constructor for the CallGraph.
307 G.reset(new CallGraph(M));
308 return false;
309}
310
311INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
312 false, true)
313
315
316void CallGraphWrapperPass::releaseMemory() { G.reset(); }
317
319 if (!G) {
320 OS << "No call graph has been built!\n";
321 return;
322 }
323
324 // Just delegate.
325 G->print(OS);
326}
327
328#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
330void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
331#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:638
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
An analysis pass to compute the CallGraph for a Module.
Definition CallGraph.h:286
A node in the call graph for a module.
Definition CallGraph.h:162
LLVM_ABI void print(raw_ostream &OS) const
bool empty() const
Definition CallGraph.h:199
void addCalledFunction(CallBase *Call, CallGraphNode *M)
Adds a function to the list of functions called by this one.
Definition CallGraph.h:238
CallGraphNode(CallGraph *CG, Function *F)
Creates a node for the specified function.
Definition CallGraph.h:180
LLVM_ABI void replaceCallEdge(CallBase &Call, CallBase &NewCall, CallGraphNode *NewNode)
Replaces the edge in the node for the specified call site with a new one.
LLVM_ABI void dump() const
Print out this call graph node.
Function * getFunction() const
Returns the function that this call graph node represents.
Definition CallGraph.h:193
LLVM_ABI void removeOneAbstractEdgeTo(CallGraphNode *Callee)
Removes one edge associated with a null callsite from this node to the specified callee function.
unsigned getNumReferences() const
Returns the number of other CallGraphNodes in this CallGraph that reference this node in their callee...
Definition CallGraph.h:204
std::pair< std::optional< WeakTrackingVH >, CallGraphNode * > CallRecord
A pair of the calling instruction (a call or invoke) and the call graph node being called.
Definition CallGraph.h:174
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
The ModulePass which wraps up a CallGraph and the logic to build it.
Definition CallGraph.h:333
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &o, const Module *) const override
print - Print out the internal state of the pass.
The basic data container for the call graph of a Module of IR.
Definition CallGraph.h:72
LLVM_ABI Function * removeFunctionFromModule(CallGraphNode *CGN)
Unlink the function from this module, returning it.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI void dump() const
LLVM_ABI void populateCallGraphNode(CallGraphNode *CGN)
Populate CGN based on the calls inside the associated function.
Definition CallGraph.cpp:88
LLVM_ABI ~CallGraph()
Definition CallGraph.cpp:53
LLVM_ABI void addToCallGraph(Function *F)
Add a function to the call graph, and link the node to all of the functions that it calls.
Definition CallGraph.cpp:74
LLVM_ABI CallGraphNode * getOrInsertFunction(const Function *F)
Similar to operator[], but this will insert a new CallGraphNode for F if one does not already exist.
LLVM_ABI bool invalidate(Module &, const PreservedAnalyses &PA, ModuleAnalysisManager::Invalidator &)
Definition CallGraph.cpp:66
LLVM_ABI CallGraph(Module &M)
Definition CallGraph.cpp:32
const Function & getFunction() const
Definition Function.h:164
Function::iterator erase(Function::iterator FromIt, Function::iterator ToIt)
Erases a range of BasicBlocks from FromIt to (not including) ToIt.
Definition Function.cpp:467
A helper class to return the specified delimiter string after the first invocation of operator String...
ModulePass(char &pid)
Definition Pass.h:257
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Enumerate the SCCs of a directed graph in reverse topological order of the SCC DAG.
Definition SCCIterator.h:49
bool isAtEnd() const
Direct loop termination test which is more efficient than comparison with end().
CallInst * Call
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1634
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
void forEachCallbackFunction(const CallBase &CB, UnaryFunction Func)
Apply function Func to each CB's callback function.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1915
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29