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 
9 #include "llvm/Analysis/CallGraph.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/Config/llvm-config.h"
13 #include "llvm/IR/Function.h"
14 #include "llvm/IR/Intrinsics.h"
15 #include "llvm/IR/Module.h"
16 #include "llvm/IR/PassManager.h"
17 #include "llvm/InitializePasses.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <algorithm>
23 #include <cassert>
24 
25 using namespace llvm;
26 
27 //===----------------------------------------------------------------------===//
28 // Implementations of the CallGraph class methods.
29 //
30 
31 CallGraph::CallGraph(Module &M)
32     : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)),
33       CallsExternalNode(std::make_unique<CallGraphNode>(nullptr)) {
34   // Add every function to the call graph.
35   for (Function &F : M)
36     addToCallGraph(&F);
37 }
38 
39 CallGraph::CallGraph(CallGraph &&Arg)
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 
47 CallGraph::~CallGraph() {
48   // CallsExternalNode is not in the function map, delete it explicitly.
49   if (CallsExternalNode)
50     CallsExternalNode->allReferencesDropped();
51 
52 // Reset all node's use counts to zero before deleting them to prevent an
53 // assertion from firing.
54 #ifndef NDEBUG
55   for (auto &I : FunctionMap)
56     I.second->allReferencesDropped();
57 #endif
58 }
59 
60 bool CallGraph::invalidate(Module &, const PreservedAnalyses &PA,
61                            ModuleAnalysisManager::Invalidator &) {
62   // Check whether the analysis, all analyses on functions, or the function's
63   // CFG have been preserved.
64   auto PAC = PA.getChecker<CallGraphAnalysis>();
65   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>() ||
66            PAC.preservedSet<CFGAnalyses>());
67 }
68 
69 void CallGraph::addToCallGraph(Function *F) {
70   CallGraphNode *Node = getOrInsertFunction(F);
71 
72   // If this function has external linkage or has its address taken, anything
73   // could call it.
74   if (!F->hasLocalLinkage() || F->hasAddressTaken())
75     ExternalCallingNode->addCalledFunction(nullptr, Node);
76 
77   populateCallGraphNode(Node);
78 }
79 
80 void CallGraph::populateCallGraphNode(CallGraphNode *Node) {
81   Function *F = Node->getFunction();
82 
83   // If this function is not defined in this translation unit, it could call
84   // anything.
85   if (F->isDeclaration() && !F->isIntrinsic())
86     Node->addCalledFunction(nullptr, CallsExternalNode.get());
87 
88   // Look for calls by this function.
89   for (BasicBlock &BB : *F)
90     for (Instruction &I : BB) {
91       if (auto *Call = dyn_cast<CallBase>(&I)) {
92         const Function *Callee = Call->getCalledFunction();
93         if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
94           // Indirect calls of intrinsics are not allowed so no need to check.
95           // We can be more precise here by using TargetArg returned by
96           // Intrinsic::isLeaf.
97           Node->addCalledFunction(Call, CallsExternalNode.get());
98         else if (!Callee->isIntrinsic())
99           Node->addCalledFunction(Call, getOrInsertFunction(Callee));
100       }
101     }
102 }
103 
104 void CallGraph::print(raw_ostream &OS) const {
105   // Print in a deterministic order by sorting CallGraphNodes by name.  We do
106   // this here to avoid slowing down the non-printing fast path.
107 
108   SmallVector<CallGraphNode *, 16> Nodes;
109   Nodes.reserve(FunctionMap.size());
110 
111   for (const auto &I : *this)
112     Nodes.push_back(I.second.get());
113 
114   llvm::sort(Nodes, [](CallGraphNode *LHS, CallGraphNode *RHS) {
115     if (Function *LF = LHS->getFunction())
116       if (Function *RF = RHS->getFunction())
117         return LF->getName() < RF->getName();
118 
119     return RHS->getFunction() != nullptr;
120   });
121 
122   for (CallGraphNode *CN : Nodes)
123     CN->print(OS);
124 }
125 
126 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
127 LLVM_DUMP_METHOD void CallGraph::dump() const { print(dbgs()); }
128 #endif
129 
130 // removeFunctionFromModule - Unlink the function from this module, returning
131 // it.  Because this removes the function from the module, the call graph node
132 // is destroyed.  This is only valid if the function does not call any other
133 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
134 // is to dropAllReferences before calling this.
135 //
136 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
137   assert(CGN->empty() && "Cannot remove function from call "
138          "graph if it references other functions!");
139   Function *F = CGN->getFunction(); // Get the function for the call graph node
140   FunctionMap.erase(F);             // Remove the call graph node from the map
141 
142   M.getFunctionList().remove(F);
143   return F;
144 }
145 
146 /// spliceFunction - Replace the function represented by this node by another.
147 /// This does not rescan the body of the function, so it is suitable when
148 /// splicing the body of the old function to the new while also updating all
149 /// callers from old to new.
150 void CallGraph::spliceFunction(const Function *From, const Function *To) {
151   assert(FunctionMap.count(From) && "No CallGraphNode for function!");
152   assert(!FunctionMap.count(To) &&
153          "Pointing CallGraphNode at a function that already exists");
154   FunctionMapTy::iterator I = FunctionMap.find(From);
155   I->second->F = const_cast<Function*>(To);
156   FunctionMap[To] = std::move(I->second);
157   FunctionMap.erase(I);
158 }
159 
160 // getOrInsertFunction - This method is identical to calling operator[], but
161 // it will insert a new CallGraphNode for the specified function if one does
162 // not already exist.
163 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
164   auto &CGN = FunctionMap[F];
165   if (CGN)
166     return CGN.get();
167 
168   assert((!F || F->getParent() == &M) && "Function not in current module!");
169   CGN = std::make_unique<CallGraphNode>(const_cast<Function *>(F));
170   return CGN.get();
171 }
172 
173 //===----------------------------------------------------------------------===//
174 // Implementations of the CallGraphNode class methods.
175 //
176 
177 void CallGraphNode::print(raw_ostream &OS) const {
178   if (Function *F = getFunction())
179     OS << "Call graph node for function: '" << F->getName() << "'";
180   else
181     OS << "Call graph node <<null function>>";
182 
183   OS << "<<" << this << ">>  #uses=" << getNumReferences() << '\n';
184 
185   for (const auto &I : *this) {
186     OS << "  CS<" << I.first << "> calls ";
187     if (Function *FI = I.second->getFunction())
188       OS << "function '" << FI->getName() <<"'\n";
189     else
190       OS << "external node\n";
191   }
192   OS << '\n';
193 }
194 
195 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
196 LLVM_DUMP_METHOD void CallGraphNode::dump() const { print(dbgs()); }
197 #endif
198 
199 /// removeCallEdgeFor - This method removes the edge in the node for the
200 /// specified call site.  Note that this method takes linear time, so it
201 /// should be used sparingly.
202 void CallGraphNode::removeCallEdgeFor(CallBase &Call) {
203   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
204     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
205     if (I->first == &Call) {
206       I->second->DropRef();
207       *I = CalledFunctions.back();
208       CalledFunctions.pop_back();
209       return;
210     }
211   }
212 }
213 
214 // removeAnyCallEdgeTo - This method removes any call edges from this node to
215 // the specified callee function.  This takes more time to execute than
216 // removeCallEdgeTo, so it should not be used unless necessary.
217 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
218   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
219     if (CalledFunctions[i].second == Callee) {
220       Callee->DropRef();
221       CalledFunctions[i] = CalledFunctions.back();
222       CalledFunctions.pop_back();
223       --i; --e;
224     }
225 }
226 
227 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
228 /// from this node to the specified callee function.
229 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
230   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
231     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
232     CallRecord &CR = *I;
233     if (CR.second == Callee && CR.first == nullptr) {
234       Callee->DropRef();
235       *I = CalledFunctions.back();
236       CalledFunctions.pop_back();
237       return;
238     }
239   }
240 }
241 
242 /// replaceCallEdge - This method replaces the edge in the node for the
243 /// specified call site with a new one.  Note that this method takes linear
244 /// time, so it should be used sparingly.
245 void CallGraphNode::replaceCallEdge(CallBase &Call, CallBase &NewCall,
246                                     CallGraphNode *NewNode) {
247   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
248     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
249     if (I->first == &Call) {
250       I->second->DropRef();
251       I->first = &NewCall;
252       I->second = NewNode;
253       NewNode->AddRef();
254       return;
255     }
256   }
257 }
258 
259 // Provide an explicit template instantiation for the static ID.
260 AnalysisKey CallGraphAnalysis::Key;
261 
262 PreservedAnalyses CallGraphPrinterPass::run(Module &M,
263                                             ModuleAnalysisManager &AM) {
264   AM.getResult<CallGraphAnalysis>(M).print(OS);
265   return PreservedAnalyses::all();
266 }
267 
268 //===----------------------------------------------------------------------===//
269 // Out-of-line definitions of CallGraphAnalysis class members.
270 //
271 
272 //===----------------------------------------------------------------------===//
273 // Implementations of the CallGraphWrapperPass class methods.
274 //
275 
276 CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
277   initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
278 }
279 
280 CallGraphWrapperPass::~CallGraphWrapperPass() = default;
281 
282 void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
283   AU.setPreservesAll();
284 }
285 
286 bool CallGraphWrapperPass::runOnModule(Module &M) {
287   // All the real work is done in the constructor for the CallGraph.
288   G.reset(new CallGraph(M));
289   return false;
290 }
291 
292 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
293                 false, true)
294 
295 char CallGraphWrapperPass::ID = 0;
296 
297 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
298 
299 void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
300   if (!G) {
301     OS << "No call graph has been built!\n";
302     return;
303   }
304 
305   // Just delegate.
306   G->print(OS);
307 }
308 
309 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
310 LLVM_DUMP_METHOD
311 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
312 #endif
313 
314 namespace {
315 
316 struct CallGraphPrinterLegacyPass : public ModulePass {
317   static char ID; // Pass ID, replacement for typeid
318 
319   CallGraphPrinterLegacyPass() : ModulePass(ID) {
320     initializeCallGraphPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
321   }
322 
323   void getAnalysisUsage(AnalysisUsage &AU) const override {
324     AU.setPreservesAll();
325     AU.addRequiredTransitive<CallGraphWrapperPass>();
326   }
327 
328   bool runOnModule(Module &M) override {
329     getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
330     return false;
331   }
332 };
333 
334 } // end anonymous namespace
335 
336 char CallGraphPrinterLegacyPass::ID = 0;
337 
338 INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph",
339                       "Print a call graph", true, true)
340 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
341 INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph",
342                     "Print a call graph", true, true)
343