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"
13#include "llvm/Config/llvm-config.h"
15#include "llvm/IR/Function.h"
16#include "llvm/IR/Module.h"
17#include "llvm/IR/PassManager.h"
19#include "llvm/Pass.h"
21#include "llvm/Support/Debug.h"
23#include <cassert>
24
25using namespace llvm;
26
27//===----------------------------------------------------------------------===//
28// Implementations of the CallGraph class methods.
29//
30
32 : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)),
33 CallsExternalNode(std::make_unique<CallGraphNode>(this, nullptr)) {
34 // Add every interesting function to the call graph.
35 for (Function &F : M)
37}
38
40 : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)),
41 ExternalCallingNode(Arg.ExternalCallingNode),
42 CallsExternalNode(std::move(Arg.CallsExternalNode)) {
43 Arg.FunctionMap.clear();
44 Arg.ExternalCallingNode = nullptr;
45
46 // Update parent CG for all call graph's nodes.
47 CallsExternalNode->CG = this;
48 for (auto &P : FunctionMap)
49 P.second->CG = this;
50}
51
53 // CallsExternalNode is not in the function map, delete it explicitly.
54 if (CallsExternalNode)
55 CallsExternalNode->allReferencesDropped();
56
57// Reset all node's use counts to zero before deleting them to prevent an
58// assertion from firing.
59#ifndef NDEBUG
60 for (auto &I : FunctionMap)
61 I.second->allReferencesDropped();
62#endif
63}
64
67 // Check whether the analysis, all analyses on functions, or the function's
68 // CFG have been preserved.
69 auto PAC = PA.getChecker<CallGraphAnalysis>();
70 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>());
71}
72
75
76 // If this function has external linkage or has its address taken and
77 // it is not a callback, then anything could call it.
78 if (!F->hasLocalLinkage() ||
79 F->hasAddressTaken(nullptr, /*IgnoreCallbackUses=*/true,
80 /* IgnoreAssumeLikeCalls */ true,
81 /* IgnoreLLVMUsed */ false))
82 ExternalCallingNode->addCalledFunction(nullptr, Node);
83
85}
86
88 Function *F = Node->getFunction();
89
90 // If this function is not defined in this translation unit, it could call
91 // anything.
92 if (F->isDeclaration() && !F->hasFnAttribute(Attribute::NoCallback))
93 Node->addCalledFunction(nullptr, CallsExternalNode.get());
94
95 // Look for calls by this function.
96 for (BasicBlock &BB : *F)
97 for (Instruction &I : BB) {
98 if (auto *Call = dyn_cast<CallBase>(&I)) {
99 const Function *Callee = Call->getCalledFunction();
100 if (!Callee)
101 Node->addCalledFunction(Call, CallsExternalNode.get());
102 else
103 Node->addCalledFunction(Call, getOrInsertFunction(Callee));
104
105 // Add reference to callback functions.
106 forEachCallbackFunction(*Call, [=](Function *CB) {
107 Node->addCalledFunction(nullptr, getOrInsertFunction(CB));
108 });
109 }
110 }
111}
112
114 // Print in a deterministic order by sorting CallGraphNodes by name. We do
115 // this here to avoid slowing down the non-printing fast path.
116
118 Nodes.reserve(FunctionMap.size());
119
120 for (const auto &I : *this)
121 Nodes.push_back(I.second.get());
122
124 if (Function *LF = LHS->getFunction())
125 if (Function *RF = RHS->getFunction())
126 return LF->getName() < RF->getName();
127
128 return RHS->getFunction() != nullptr;
129 });
130
131 for (CallGraphNode *CN : Nodes)
132 CN->print(OS);
133}
134
135#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
137#endif
138
139// removeFunctionFromModule - Unlink the function from this module, returning
140// it. Because this removes the function from the module, the call graph node
141// is destroyed. This is only valid if the function does not call any other
142// functions (ie, there are no edges in it's CGN). The easiest way to do this
143// is to dropAllReferences before calling this.
144//
146 assert(CGN->empty() && "Cannot remove function from call "
147 "graph if it references other functions!");
148 Function *F = CGN->getFunction(); // Get the function for the call graph node
149 FunctionMap.erase(F); // Remove the call graph node from the map
150
152 return F;
153}
154
155// getOrInsertFunction - This method is identical to calling operator[], but
156// it will insert a new CallGraphNode for the specified function if one does
157// not already exist.
159 auto &CGN = FunctionMap[F];
160 if (CGN)
161 return CGN.get();
162
163 assert((!F || F->getParent() == &M) && "Function not in current module!");
164 CGN = std::make_unique<CallGraphNode>(this, const_cast<Function *>(F));
165 return CGN.get();
166}
167
168//===----------------------------------------------------------------------===//
169// Implementations of the CallGraphNode class methods.
170//
171
173 if (Function *F = getFunction())
174 OS << "Call graph node for function: '" << F->getName() << "'";
175 else
176 OS << "Call graph node <<null function>>";
177
178 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
179
180 for (const auto &I : *this) {
181 OS << " CS<" << I.first << "> calls ";
182 if (Function *FI = I.second->getFunction())
183 OS << "function '" << FI->getName() <<"'\n";
184 else
185 OS << "external node\n";
186 }
187 OS << '\n';
188}
189
190#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
192#endif
193
194/// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
195/// from this node to the specified callee function.
197 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
198 assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
199 CallRecord &CR = *I;
200 if (CR.second == Callee && !CR.first) {
201 Callee->DropRef();
202 *I = CalledFunctions.back();
203 CalledFunctions.pop_back();
204 return;
205 }
206 }
207}
208
209/// replaceCallEdge - This method replaces the edge in the node for the
210/// specified call site with a new one. Note that this method takes linear
211/// time, so it should be used sparingly.
213 CallGraphNode *NewNode) {
214 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
215 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
216 if (I->first && *I->first == &Call) {
217 I->second->DropRef();
218 I->first = &NewCall;
219 I->second = NewNode;
220 NewNode->AddRef();
221
222 // Refresh callback references. Do not resize CalledFunctions if the
223 // number of callbacks is the same for new and old call sites.
226 forEachCallbackFunction(Call, [this, &OldCBs](Function *CB) {
227 OldCBs.push_back(CG->getOrInsertFunction(CB));
228 });
229 forEachCallbackFunction(NewCall, [this, &NewCBs](Function *CB) {
230 NewCBs.push_back(CG->getOrInsertFunction(CB));
231 });
232 if (OldCBs.size() == NewCBs.size()) {
233 for (unsigned N = 0; N < OldCBs.size(); ++N) {
234 CallGraphNode *OldNode = OldCBs[N];
235 CallGraphNode *NewNode = NewCBs[N];
236 for (auto J = CalledFunctions.begin();; ++J) {
237 assert(J != CalledFunctions.end() &&
238 "Cannot find callsite to update!");
239 if (!J->first && J->second == OldNode) {
240 J->second = NewNode;
241 OldNode->DropRef();
242 NewNode->AddRef();
243 break;
244 }
245 }
246 }
247 } else {
248 for (auto *CGN : OldCBs)
250 for (auto *CGN : NewCBs)
251 addCalledFunction(nullptr, CGN);
252 }
253 return;
254 }
255 }
256}
257
258// Provide an explicit template instantiation for the static ID.
259AnalysisKey CallGraphAnalysis::Key;
260
264 return PreservedAnalyses::all();
265}
266
269 auto &CG = AM.getResult<CallGraphAnalysis>(M);
270 unsigned sccNum = 0;
271 OS << "SCCs for the program in PostOrder:";
272 for (scc_iterator<CallGraph *> SCCI = scc_begin(&CG); !SCCI.isAtEnd();
273 ++SCCI) {
274 const std::vector<CallGraphNode *> &nextSCC = *SCCI;
275 OS << "\nSCC #" << ++sccNum << ": ";
276 bool First = true;
277 for (CallGraphNode *CGN : nextSCC) {
278 if (First)
279 First = false;
280 else
281 OS << ", ";
282 OS << (CGN->getFunction() ? CGN->getFunction()->getName()
283 : "external node");
284 }
285
286 if (nextSCC.size() == 1 && SCCI.hasCycle())
287 OS << " (Has self-loop).";
288 }
289 OS << "\n";
290 return PreservedAnalyses::all();
291}
292
293//===----------------------------------------------------------------------===//
294// Out-of-line definitions of CallGraphAnalysis class members.
295//
296
297//===----------------------------------------------------------------------===//
298// Implementations of the CallGraphWrapperPass class methods.
299//
300
302
304
306 AU.setPreservesAll();
307}
308
310 // All the real work is done in the constructor for the CallGraph.
311 G.reset(new CallGraph(M));
312 return false;
313}
314
315INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
316 false, true)
317
319
320void CallGraphWrapperPass::releaseMemory() { G.reset(); }
321
323 if (!G) {
324 OS << "No call graph has been built!\n";
325 return;
326 }
327
328 // Just delegate.
329 G->print(OS);
330}
331
332#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
334void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
335#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:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
#define P(N)
if(PassOpts->AAPipeline)
#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.
raw_pwrite_stream & OS
This file defines the SmallVector class.
Value * RHS
Value * LHS
This templated class represents "all analyses that operate over <a particular IR unit>" (e....
Definition: Analysis.h:50
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:294
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:412
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...
Definition: InstrTypes.h:1116
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
Definition: CallGraph.cpp:172
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
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.
Definition: CallGraph.cpp:212
LLVM_ABI void dump() const
Print out this call graph node.
Definition: CallGraph.cpp:191
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.
Definition: CallGraph.cpp:196
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)
Definition: CallGraph.cpp:261
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Definition: CallGraph.cpp:267
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.
Definition: CallGraph.cpp:309
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: CallGraph.cpp:305
void print(raw_ostream &o, const Module *) const override
print - Print out the internal state of the pass.
Definition: CallGraph.cpp:322
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.
Definition: CallGraph.cpp:145
LLVM_ABI void print(raw_ostream &OS) const
Definition: CallGraph.cpp:113
LLVM_ABI void dump() const
Definition: CallGraph.cpp:136
LLVM_ABI void populateCallGraphNode(CallGraphNode *CGN)
Populate CGN based on the calls inside the associated function.
Definition: CallGraph.cpp:87
LLVM_ABI ~CallGraph()
Definition: CallGraph.cpp:52
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:73
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.
Definition: CallGraph.cpp:158
LLVM_ABI bool invalidate(Module &, const PreservedAnalyses &PA, ModuleAnalysisManager::Invalidator &)
Definition: CallGraph.cpp:65
LLVM_ABI CallGraph(Module &M)
Definition: CallGraph.cpp:31
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
Definition: Module.h:596
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
size_t size() const
Definition: SmallVector.h:79
void reserve(size_type N)
Definition: SmallVector.h:664
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:322
pointer remove(iterator &IT)
Definition: ilist.h:188
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
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
Definition: SCCIterator.h:233
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1669
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
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:1886
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:29