1 //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Analysis/CallGraph.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/Config/llvm-config.h"
14 #include "llvm/IR/CallSite.h"
15 #include "llvm/IR/Module.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/PassManager.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
28 //===----------------------------------------------------------------------===//
29 // Implementations of the CallGraph class methods.
32 CallGraph::CallGraph(Module
&M
)
33 : M(M
), ExternalCallingNode(getOrInsertFunction(nullptr)),
34 CallsExternalNode(llvm::make_unique
<CallGraphNode
>(nullptr)) {
35 // Add every function to the call graph.
40 CallGraph::CallGraph(CallGraph
&&Arg
)
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;
48 CallGraph::~CallGraph() {
49 // CallsExternalNode is not in the function map, delete it explicitly.
50 if (CallsExternalNode
)
51 CallsExternalNode
->allReferencesDropped();
53 // Reset all node's use counts to zero before deleting them to prevent an
54 // assertion from firing.
56 for (auto &I
: FunctionMap
)
57 I
.second
->allReferencesDropped();
61 void CallGraph::addToCallGraph(Function
*F
) {
62 CallGraphNode
*Node
= getOrInsertFunction(F
);
64 // If this function has external linkage or has its address taken, anything
66 if (!F
->hasLocalLinkage() || F
->hasAddressTaken())
67 ExternalCallingNode
->addCalledFunction(CallSite(), Node
);
69 // If this function is not defined in this translation unit, it could call
71 if (F
->isDeclaration() && !F
->isIntrinsic())
72 Node
->addCalledFunction(CallSite(), CallsExternalNode
.get());
74 // Look for calls by this function.
75 for (BasicBlock
&BB
: *F
)
76 for (Instruction
&I
: BB
) {
77 if (auto CS
= CallSite(&I
)) {
78 const Function
*Callee
= CS
.getCalledFunction();
79 if (!Callee
|| !Intrinsic::isLeaf(Callee
->getIntrinsicID()))
80 // Indirect calls of intrinsics are not allowed so no need to check.
81 // We can be more precise here by using TargetArg returned by
83 Node
->addCalledFunction(CS
, CallsExternalNode
.get());
84 else if (!Callee
->isIntrinsic())
85 Node
->addCalledFunction(CS
, getOrInsertFunction(Callee
));
90 void CallGraph::print(raw_ostream
&OS
) const {
91 // Print in a deterministic order by sorting CallGraphNodes by name. We do
92 // this here to avoid slowing down the non-printing fast path.
94 SmallVector
<CallGraphNode
*, 16> Nodes
;
95 Nodes
.reserve(FunctionMap
.size());
97 for (const auto &I
: *this)
98 Nodes
.push_back(I
.second
.get());
100 llvm::sort(Nodes
, [](CallGraphNode
*LHS
, CallGraphNode
*RHS
) {
101 if (Function
*LF
= LHS
->getFunction())
102 if (Function
*RF
= RHS
->getFunction())
103 return LF
->getName() < RF
->getName();
105 return RHS
->getFunction() != nullptr;
108 for (CallGraphNode
*CN
: Nodes
)
112 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
113 LLVM_DUMP_METHOD
void CallGraph::dump() const { print(dbgs()); }
116 // removeFunctionFromModule - Unlink the function from this module, returning
117 // it. Because this removes the function from the module, the call graph node
118 // is destroyed. This is only valid if the function does not call any other
119 // functions (ie, there are no edges in it's CGN). The easiest way to do this
120 // is to dropAllReferences before calling this.
122 Function
*CallGraph::removeFunctionFromModule(CallGraphNode
*CGN
) {
123 assert(CGN
->empty() && "Cannot remove function from call "
124 "graph if it references other functions!");
125 Function
*F
= CGN
->getFunction(); // Get the function for the call graph node
126 FunctionMap
.erase(F
); // Remove the call graph node from the map
128 M
.getFunctionList().remove(F
);
132 /// spliceFunction - Replace the function represented by this node by another.
133 /// This does not rescan the body of the function, so it is suitable when
134 /// splicing the body of the old function to the new while also updating all
135 /// callers from old to new.
136 void CallGraph::spliceFunction(const Function
*From
, const Function
*To
) {
137 assert(FunctionMap
.count(From
) && "No CallGraphNode for function!");
138 assert(!FunctionMap
.count(To
) &&
139 "Pointing CallGraphNode at a function that already exists");
140 FunctionMapTy::iterator I
= FunctionMap
.find(From
);
141 I
->second
->F
= const_cast<Function
*>(To
);
142 FunctionMap
[To
] = std::move(I
->second
);
143 FunctionMap
.erase(I
);
146 // getOrInsertFunction - This method is identical to calling operator[], but
147 // it will insert a new CallGraphNode for the specified function if one does
148 // not already exist.
149 CallGraphNode
*CallGraph::getOrInsertFunction(const Function
*F
) {
150 auto &CGN
= FunctionMap
[F
];
154 assert((!F
|| F
->getParent() == &M
) && "Function not in current module!");
155 CGN
= llvm::make_unique
<CallGraphNode
>(const_cast<Function
*>(F
));
159 //===----------------------------------------------------------------------===//
160 // Implementations of the CallGraphNode class methods.
163 void CallGraphNode::print(raw_ostream
&OS
) const {
164 if (Function
*F
= getFunction())
165 OS
<< "Call graph node for function: '" << F
->getName() << "'";
167 OS
<< "Call graph node <<null function>>";
169 OS
<< "<<" << this << ">> #uses=" << getNumReferences() << '\n';
171 for (const auto &I
: *this) {
172 OS
<< " CS<" << I
.first
<< "> calls ";
173 if (Function
*FI
= I
.second
->getFunction())
174 OS
<< "function '" << FI
->getName() <<"'\n";
176 OS
<< "external node\n";
181 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
182 LLVM_DUMP_METHOD
void CallGraphNode::dump() const { print(dbgs()); }
185 /// removeCallEdgeFor - This method removes the edge in the node for the
186 /// specified call site. Note that this method takes linear time, so it
187 /// should be used sparingly.
188 void CallGraphNode::removeCallEdgeFor(CallSite CS
) {
189 for (CalledFunctionsVector::iterator I
= CalledFunctions
.begin(); ; ++I
) {
190 assert(I
!= CalledFunctions
.end() && "Cannot find callsite to remove!");
191 if (I
->first
== CS
.getInstruction()) {
192 I
->second
->DropRef();
193 *I
= CalledFunctions
.back();
194 CalledFunctions
.pop_back();
200 // removeAnyCallEdgeTo - This method removes any call edges from this node to
201 // the specified callee function. This takes more time to execute than
202 // removeCallEdgeTo, so it should not be used unless necessary.
203 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode
*Callee
) {
204 for (unsigned i
= 0, e
= CalledFunctions
.size(); i
!= e
; ++i
)
205 if (CalledFunctions
[i
].second
== Callee
) {
207 CalledFunctions
[i
] = CalledFunctions
.back();
208 CalledFunctions
.pop_back();
213 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
214 /// from this node to the specified callee function.
215 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode
*Callee
) {
216 for (CalledFunctionsVector::iterator I
= CalledFunctions
.begin(); ; ++I
) {
217 assert(I
!= CalledFunctions
.end() && "Cannot find callee to remove!");
219 if (CR
.second
== Callee
&& CR
.first
== nullptr) {
221 *I
= CalledFunctions
.back();
222 CalledFunctions
.pop_back();
228 /// replaceCallEdge - This method replaces the edge in the node for the
229 /// specified call site with a new one. Note that this method takes linear
230 /// time, so it should be used sparingly.
231 void CallGraphNode::replaceCallEdge(CallSite CS
,
232 CallSite NewCS
, CallGraphNode
*NewNode
){
233 for (CalledFunctionsVector::iterator I
= CalledFunctions
.begin(); ; ++I
) {
234 assert(I
!= CalledFunctions
.end() && "Cannot find callsite to remove!");
235 if (I
->first
== CS
.getInstruction()) {
236 I
->second
->DropRef();
237 I
->first
= NewCS
.getInstruction();
245 // Provide an explicit template instantiation for the static ID.
246 AnalysisKey
CallGraphAnalysis::Key
;
248 PreservedAnalyses
CallGraphPrinterPass::run(Module
&M
,
249 ModuleAnalysisManager
&AM
) {
250 AM
.getResult
<CallGraphAnalysis
>(M
).print(OS
);
251 return PreservedAnalyses::all();
254 //===----------------------------------------------------------------------===//
255 // Out-of-line definitions of CallGraphAnalysis class members.
258 //===----------------------------------------------------------------------===//
259 // Implementations of the CallGraphWrapperPass class methods.
262 CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID
) {
263 initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
266 CallGraphWrapperPass::~CallGraphWrapperPass() = default;
268 void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage
&AU
) const {
269 AU
.setPreservesAll();
272 bool CallGraphWrapperPass::runOnModule(Module
&M
) {
273 // All the real work is done in the constructor for the CallGraph.
274 G
.reset(new CallGraph(M
));
278 INITIALIZE_PASS(CallGraphWrapperPass
, "basiccg", "CallGraph Construction",
281 char CallGraphWrapperPass::ID
= 0;
283 void CallGraphWrapperPass::releaseMemory() { G
.reset(); }
285 void CallGraphWrapperPass::print(raw_ostream
&OS
, const Module
*) const {
287 OS
<< "No call graph has been built!\n";
295 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
297 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
302 struct CallGraphPrinterLegacyPass
: public ModulePass
{
303 static char ID
; // Pass ID, replacement for typeid
305 CallGraphPrinterLegacyPass() : ModulePass(ID
) {
306 initializeCallGraphPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
309 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
310 AU
.setPreservesAll();
311 AU
.addRequiredTransitive
<CallGraphWrapperPass
>();
314 bool runOnModule(Module
&M
) override
{
315 getAnalysis
<CallGraphWrapperPass
>().print(errs(), &M
);
320 } // end anonymous namespace
322 char CallGraphPrinterLegacyPass::ID
= 0;
324 INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass
, "print-callgraph",
325 "Print a call graph", true, true)
326 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass
)
327 INITIALIZE_PASS_END(CallGraphPrinterLegacyPass
, "print-callgraph",
328 "Print a call graph", true, true)