LLVM 24.0.0git
CallGraphSCCPass.cpp
Go to the documentation of this file.
1//===- CallGraphSCCPass.cpp - Pass that operates BU on 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 implements the CallGraphSCCPass class, which is used for passes
10// which are implemented as bottom-up traversals on the call graph. Because
11// there may be cycles in the call graph, passes of this type operate on the
12// call-graph in SCC order: that is, they process function bottom-up, except for
13// recursive functions, which they process all at once.
14//
15//===----------------------------------------------------------------------===//
16
18#include "AnalysisOptions.h"
19#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/Statistic.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Module.h"
31#include "llvm/IR/PrintPasses.h"
33#include "llvm/Pass.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/Timer.h"
37#include <cassert>
38#include <string>
39#include <utility>
40#include <vector>
41
42using namespace llvm;
43
44#define DEBUG_TYPE "cgscc-passmgr"
45
46unsigned
49 .max_devirt_iterations;
50}
51
52STATISTIC(MaxSCCIterations, "Maximum CGSCCPassMgr iterations on one SCC");
53
54//===----------------------------------------------------------------------===//
55// CGPassManager
56//
57/// CGPassManager manages FPPassManagers and CallGraphSCCPasses.
58
59namespace {
60
61class CGPassManager : public ModulePass, public PMDataManager {
62public:
63 static char ID;
64
65 explicit CGPassManager() : ModulePass(ID) {}
66
67 /// Execute all of the passes scheduled for execution. Keep track of
68 /// whether any of the passes modifies the module, and if so, return true.
69 bool runOnModule(Module &M) override;
70
71 using ModulePass::doInitialization;
72 using ModulePass::doFinalization;
73
74 bool doInitialization(CallGraph &CG);
75 bool doFinalization(CallGraph &CG);
76
77 /// Pass Manager itself does not invalidate any analysis info.
78 void getAnalysisUsage(AnalysisUsage &Info) const override {
79 // CGPassManager walks SCC and it needs CallGraph.
80 Info.addRequired<CallGraphWrapperPass>();
81 Info.setPreservesAll();
82 }
83
84 StringRef getPassName() const override { return "CallGraph Pass Manager"; }
85
86 PMDataManager *getAsPMDataManager() override { return this; }
87 Pass *getAsPass() override { return this; }
88
89 // Print passes managed by this manager
90 void dumpPassStructure(unsigned Offset) override {
91 errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n";
92 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
93 Pass *P = getContainedPass(Index);
94 P->dumpPassStructure(Offset + 1);
95 dumpLastUses(P, Offset+1);
96 }
97 }
98
99 Pass *getContainedPass(unsigned N) {
100 assert(N < PassVector.size() && "Pass number out of range!");
101 return static_cast<Pass *>(PassVector[N]);
102 }
103
104 PassManagerType getPassManagerType() const override {
106 }
107
108private:
109 bool RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
110 bool &DevirtualizedCall);
111
112 bool RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
113 CallGraph &CG, bool &CallGraphUpToDate,
114 bool &DevirtualizedCall);
115 bool RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG,
116 bool IsCheckingMode);
117};
118
119} // end anonymous namespace.
120
121char CGPassManager::ID = 0;
122
123bool CGPassManager::RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
124 CallGraph &CG, bool &CallGraphUpToDate,
125 bool &DevirtualizedCall) {
126 bool Changed = false;
127 PMDataManager *PM = P->getAsPMDataManager();
128 Module &M = CG.getModule();
129
130 if (!PM) {
131 CallGraphSCCPass *CGSP = (CallGraphSCCPass *)P;
132 if (!CallGraphUpToDate) {
133 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
134 CallGraphUpToDate = true;
135 }
136
137 {
138 unsigned InstrCount, SCCCount = 0;
139 StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
140 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
141 TimeRegion PassTimer(getPassTimer(CGSP));
142 if (EmitICRemark)
143 InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
144 Changed = CGSP->runOnSCC(CurSCC);
145
146 if (EmitICRemark) {
147 // FIXME: Add getInstructionCount to CallGraphSCC.
148 SCCCount = M.getInstructionCount();
149 // Is there a difference in the number of instructions in the module?
150 if (SCCCount != InstrCount) {
151 // Yep. Emit a remark and update InstrCount.
152 int64_t Delta =
153 static_cast<int64_t>(SCCCount) - static_cast<int64_t>(InstrCount);
154 emitInstrCountChangedRemark(P, M, Delta, InstrCount,
155 FunctionToInstrCount);
156 InstrCount = SCCCount;
157 }
158 }
159 }
160
161 // After the CGSCCPass is done, when assertions are enabled, use
162 // RefreshCallGraph to verify that the callgraph was correctly updated.
163#ifndef NDEBUG
164 if (Changed)
165 RefreshCallGraph(CurSCC, CG, true);
166#endif
167
168 return Changed;
169 }
170
172 "Invalid CGPassManager member");
173 FPPassManager *FPP = (FPPassManager*)P;
174
175 // Run pass P on all functions in the current SCC.
176 for (CallGraphNode *CGN : CurSCC) {
177 if (Function *F = CGN->getFunction()) {
178 dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());
179 {
180 TimeRegion PassTimer(getPassTimer(FPP));
181 Changed |= FPP->runOnFunction(*F);
182 }
183 F->getContext().yield();
184 }
185 }
186
187 // The function pass(es) modified the IR, they may have clobbered the
188 // callgraph.
189 if (Changed && CallGraphUpToDate) {
190 LLVM_DEBUG(dbgs() << "CGSCCPASSMGR: Pass Dirtied SCC: " << P->getPassName()
191 << '\n');
192 CallGraphUpToDate = false;
193 }
194 return Changed;
195}
196
197/// Scan the functions in the specified CFG and resync the
198/// callgraph with the call sites found in it. This is used after
199/// FunctionPasses have potentially munged the callgraph, and can be used after
200/// CallGraphSCC passes to verify that they correctly updated the callgraph.
201///
202/// This function returns true if it devirtualized an existing function call,
203/// meaning it turned an indirect call into a direct call. This happens when
204/// a function pass like GVN optimizes away stuff feeding the indirect call.
205/// This never happens in checking mode.
206bool CGPassManager::RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG,
207 bool CheckingMode) {
208 DenseMap<Value *, CallGraphNode *> Calls;
209
210 LLVM_DEBUG(dbgs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size()
211 << " nodes:\n";
212 for (CallGraphNode *CGN
213 : CurSCC) CGN->dump(););
214
215 bool MadeChange = false;
216 bool DevirtualizedCall = false;
217
218 // Scan all functions in the SCC.
219 unsigned FunctionNo = 0;
220 for (CallGraphSCC::iterator SCCIdx = CurSCC.begin(), E = CurSCC.end();
221 SCCIdx != E; ++SCCIdx, ++FunctionNo) {
222 CallGraphNode *CGN = *SCCIdx;
223 Function *F = CGN->getFunction();
224 if (!F || F->isDeclaration()) continue;
225
226 // Walk the function body looking for call sites. Sync up the call sites in
227 // CGN with those actually in the function.
228
229 // Keep track of the number of direct and indirect calls that were
230 // invalidated and removed.
231 unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0;
232
233 CallGraphNode::iterator CGNEnd = CGN->end();
234
235 auto RemoveAndCheckForDone = [&](CallGraphNode::iterator I) {
236 // Just remove the edge from the set of callees, keep track of whether
237 // I points to the last element of the vector.
238 bool WasLast = I + 1 == CGNEnd;
239 CGN->removeCallEdge(I);
240
241 // If I pointed to the last element of the vector, we have to bail out:
242 // iterator checking rejects comparisons of the resultant pointer with
243 // end.
244 if (WasLast)
245 return true;
246
247 CGNEnd = CGN->end();
248 return false;
249 };
250
251 // Get the set of call sites currently in the function.
252 for (CallGraphNode::iterator I = CGN->begin(); I != CGNEnd;) {
253 // Delete "reference" call records that do not have call instruction. We
254 // reinsert them as needed later. However, keep them in checking mode.
255 if (!I->first) {
256 if (CheckingMode) {
257 ++I;
258 continue;
259 }
260 if (RemoveAndCheckForDone(I))
261 break;
262 continue;
263 }
264
265 // If this call site is null, then the function pass deleted the call
266 // entirely and the WeakTrackingVH nulled it out.
267 auto *Call = dyn_cast_or_null<CallBase>(*I->first);
268 if (!Call ||
269 // If we've already seen this call site, then the FunctionPass RAUW'd
270 // one call with another, which resulted in two "uses" in the edge
271 // list of the same call.
272 Calls.count(Call)) {
273 assert(!CheckingMode &&
274 "CallGraphSCCPass did not update the CallGraph correctly!");
275
276 // If this was an indirect call site, count it.
277 if (!I->second->getFunction())
278 ++NumIndirectRemoved;
279 else
280 ++NumDirectRemoved;
281
282 if (RemoveAndCheckForDone(I))
283 break;
284 continue;
285 }
286
287 assert(!Calls.count(Call) && "Call site occurs in node multiple times");
288
289 if (Call) {
291 // Ignore intrinsics because they're not really function calls.
292 if (!Callee || !(Callee->isIntrinsic()))
293 Calls.insert(std::make_pair(Call, I->second));
294 }
295 ++I;
296 }
297
298 // Loop over all of the instructions in the function, getting the callsites.
299 // Keep track of the number of direct/indirect calls added.
300 unsigned NumDirectAdded = 0, NumIndirectAdded = 0;
301
302 for (BasicBlock &BB : *F)
303 for (Instruction &I : BB) {
304 auto *Call = dyn_cast<CallBase>(&I);
305 if (!Call)
306 continue;
308 if (Callee && Callee->isIntrinsic())
309 continue;
310
311 // If we are not in checking mode, insert potential callback calls as
312 // references. This is not a requirement but helps to iterate over the
313 // functions in the right order.
314 if (!CheckingMode) {
316 CGN->addCalledFunction(nullptr, CG.getOrInsertFunction(CB));
317 });
318 }
319
320 // If this call site already existed in the callgraph, just verify it
321 // matches up to expectations and remove it from Calls.
322 auto ExistingIt = Calls.find(Call);
323 if (ExistingIt != Calls.end()) {
324 CallGraphNode *ExistingNode = ExistingIt->second;
325
326 // Remove from Calls since we have now seen it.
327 Calls.erase(ExistingIt);
328
329 // Verify that the callee is right.
330 if (ExistingNode->getFunction() == Call->getCalledFunction())
331 continue;
332
333 // If we are in checking mode, we are not allowed to actually mutate
334 // the callgraph. If this is a case where we can infer that the
335 // callgraph is less precise than it could be (e.g. an indirect call
336 // site could be turned direct), don't reject it in checking mode, and
337 // don't tweak it to be more precise.
338 if (CheckingMode && Call->getCalledFunction() &&
339 ExistingNode->getFunction() == nullptr)
340 continue;
341
342 assert(!CheckingMode &&
343 "CallGraphSCCPass did not update the CallGraph correctly!");
344
345 // If not, we either went from a direct call to indirect, indirect to
346 // direct, or direct to different direct.
347 CallGraphNode *CalleeNode;
348 if (Function *Callee = Call->getCalledFunction()) {
349 CalleeNode = CG.getOrInsertFunction(Callee);
350 // Keep track of whether we turned an indirect call into a direct
351 // one.
352 if (!ExistingNode->getFunction()) {
353 DevirtualizedCall = true;
354 LLVM_DEBUG(dbgs() << " CGSCCPASSMGR: Devirtualized call to '"
355 << Callee->getName() << "'\n");
356 }
357 } else {
358 CalleeNode = CG.getCallsExternalNode();
359 }
360
361 // Update the edge target in CGN.
362 CGN->replaceCallEdge(*Call, *Call, CalleeNode);
363 MadeChange = true;
364 continue;
365 }
366
367 assert(!CheckingMode &&
368 "CallGraphSCCPass did not update the CallGraph correctly!");
369
370 // If the call site didn't exist in the CGN yet, add it.
371 CallGraphNode *CalleeNode;
372 if (Function *Callee = Call->getCalledFunction()) {
373 CalleeNode = CG.getOrInsertFunction(Callee);
374 ++NumDirectAdded;
375 } else {
376 CalleeNode = CG.getCallsExternalNode();
377 ++NumIndirectAdded;
378 }
379
380 CGN->addCalledFunction(Call, CalleeNode);
381 MadeChange = true;
382 }
383
384 // We scanned the old callgraph node, removing invalidated call sites and
385 // then added back newly found call sites. One thing that can happen is
386 // that an old indirect call site was deleted and replaced with a new direct
387 // call. In this case, we have devirtualized a call, and CGSCCPM would like
388 // to iteratively optimize the new code. Unfortunately, we don't really
389 // have a great way to detect when this happens. As an approximation, we
390 // just look at whether the number of indirect calls is reduced and the
391 // number of direct calls is increased. There are tons of ways to fool this
392 // (e.g. DCE'ing an indirect call and duplicating an unrelated block with a
393 // direct call) but this is close enough.
394 if (NumIndirectRemoved > NumIndirectAdded &&
395 NumDirectRemoved < NumDirectAdded)
396 DevirtualizedCall = true;
397
398 // After scanning this function, if we still have entries in callsites, then
399 // they are dangling pointers. WeakTrackingVH should save us for this, so
400 // abort if
401 // this happens.
402 assert(Calls.empty() && "Dangling pointers found in call sites map");
403
404 // Periodically do an explicit clear to remove tombstones when processing
405 // large scc's.
406 if ((FunctionNo & 15) == 15)
407 Calls.clear();
408 }
409
410 LLVM_DEBUG(if (MadeChange) {
411 dbgs() << "CGSCCPASSMGR: Refreshed SCC is now:\n";
412 for (CallGraphNode *CGN : CurSCC)
413 CGN->dump();
414 if (DevirtualizedCall)
415 dbgs() << "CGSCCPASSMGR: Refresh devirtualized a call!\n";
416 } else {
417 dbgs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n";
418 });
419 (void)MadeChange;
420
421 return DevirtualizedCall;
422}
423
424/// Execute the body of the entire pass manager on the specified SCC.
425/// This keeps track of whether a function pass devirtualizes
426/// any calls and returns it in DevirtualizedCall.
427bool CGPassManager::RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
428 bool &DevirtualizedCall) {
429 bool Changed = false;
430
431 // Keep track of whether the callgraph is known to be up-to-date or not.
432 // The CGSSC pass manager runs two types of passes:
433 // CallGraphSCC Passes and other random function passes. Because other
434 // random function passes are not CallGraph aware, they may clobber the
435 // call graph by introducing new calls or deleting other ones. This flag
436 // is set to false when we run a function pass so that we know to clean up
437 // the callgraph when we need to run a CGSCCPass again.
438 bool CallGraphUpToDate = true;
439
440 // Run all passes on current SCC.
441 for (unsigned PassNo = 0, e = getNumContainedPasses();
442 PassNo != e; ++PassNo) {
443 Pass *P = getContainedPass(PassNo);
444
445 // If we're in -debug-pass=Executions mode, construct the SCC node list,
446 // otherwise avoid constructing this string as it is expensive.
447 if (isPassDebuggingExecutionsOrMore()) {
448 std::string Functions;
449 #ifndef NDEBUG
450 raw_string_ostream OS(Functions);
451 ListSeparator LS;
452 for (const CallGraphNode *CGN : CurSCC) {
453 OS << LS;
454 CGN->print(OS);
455 }
456 #endif
457 dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, Functions);
458 }
459 dumpRequiredSet(P);
460
461 initializeAnalysisImpl(P);
462
463#ifdef EXPENSIVE_CHECKS
464 uint64_t RefHash = P->structuralHash(CG.getModule());
465#endif
466
467 // Actually run this pass on the current SCC.
468 bool LocalChanged =
469 RunPassOnSCC(P, CurSCC, CG, CallGraphUpToDate, DevirtualizedCall);
470
471 Changed |= LocalChanged;
472
473#ifdef EXPENSIVE_CHECKS
474 if (!LocalChanged && (RefHash != P->structuralHash(CG.getModule()))) {
475 llvm::errs() << "Pass modifies its input and doesn't report it: "
476 << P->getPassName() << "\n";
477 llvm_unreachable("Pass modifies its input and doesn't report it");
478 }
479#endif
480 if (LocalChanged)
481 dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, "");
482 dumpPreservedSet(P);
483
484 verifyPreservedAnalysis(P);
485 if (LocalChanged)
486 removeNotPreservedAnalysis(P);
487 recordAvailableAnalysis(P);
488 removeDeadPasses(P, "", ON_CG_MSG);
489 }
490
491 // If the callgraph was left out of date (because the last pass run was a
492 // functionpass), refresh it before we move on to the next SCC.
493 if (!CallGraphUpToDate)
494 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
495 return Changed;
496}
497
498/// Execute all of the passes scheduled for execution. Keep track of
499/// whether any of the passes modifies the module, and if so, return true.
500bool CGPassManager::runOnModule(Module &M) {
501 const unsigned MaxDevirtIterations =
502 getAnalysisOptions(M).max_devirt_iterations;
503 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
504 bool Changed = doInitialization(CG);
505
506 // Walk the callgraph in bottom-up SCC order.
507 scc_iterator<CallGraph*> CGI = scc_begin(&CG);
508
509 CallGraphSCC CurSCC(CG);
510 while (!CGI.isAtEnd()) {
511 // Copy the current SCC and increment past it so that the pass can hack
512 // on the SCC if it wants to without invalidating our iterator.
513 const std::vector<CallGraphNode *> &NodeVec = *CGI;
514 CurSCC.initialize(NodeVec);
515 ++CGI;
516
517 // At the top level, we run all the passes in this pass manager on the
518 // functions in this SCC. However, we support iterative compilation in the
519 // case where a function pass devirtualizes a call to a function. For
520 // example, it is very common for a function pass (often GVN or instcombine)
521 // to eliminate the addressing that feeds into a call. With that improved
522 // information, we would like the call to be an inline candidate, infer
523 // mod-ref information etc.
524 //
525 // Because of this, we allow iteration up to a specified iteration count.
526 // This only happens in the case of a devirtualized call, so we only burn
527 // compile time in the case that we're making progress. We also have a hard
528 // iteration count limit in case there is crazy code.
529 unsigned Iteration = 0;
530 bool DevirtualizedCall = false;
531 do {
532 LLVM_DEBUG(if (Iteration) dbgs()
533 << " SCCPASSMGR: Re-visiting SCC, iteration #" << Iteration
534 << '\n');
535 DevirtualizedCall = false;
536 Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall);
537 } while (Iteration++ < MaxDevirtIterations && DevirtualizedCall);
538
539 if (DevirtualizedCall)
540 LLVM_DEBUG(dbgs() << " CGSCCPASSMGR: Stopped iteration after "
541 << Iteration
542 << " times, due to -max-devirt-iterations\n");
543
544 MaxSCCIterations.updateMax(Iteration);
545 }
546 Changed |= doFinalization(CG);
547 return Changed;
548}
549
550/// Initialize CG
551bool CGPassManager::doInitialization(CallGraph &CG) {
552 bool Changed = false;
553 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
554 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
556 "Invalid CGPassManager member");
557 Changed |= ((FPPassManager*)PM)->doInitialization(CG.getModule());
558 } else {
559 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doInitialization(CG);
560 }
561 }
562 return Changed;
563}
564
565/// Finalize CG
566bool CGPassManager::doFinalization(CallGraph &CG) {
567 bool Changed = false;
568 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
569 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
571 "Invalid CGPassManager member");
572 Changed |= ((FPPassManager*)PM)->doFinalization(CG.getModule());
573 } else {
574 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doFinalization(CG);
575 }
576 }
577 return Changed;
578}
579
580//===----------------------------------------------------------------------===//
581// CallGraphSCCPass Implementation
582//===----------------------------------------------------------------------===//
583
584/// Assign pass manager to manage this pass.
586 PassManagerType PreferredType) {
587 // Find CGPassManager
588 while (!PMS.empty() &&
590 PMS.pop();
591
592 assert(!PMS.empty() && "Unable to handle Call Graph Pass");
593 CGPassManager *CGP;
594
596 CGP = (CGPassManager*)PMS.top();
597 else {
598 // Create new Call Graph SCC Pass Manager if it does not exist.
599 assert(!PMS.empty() && "Unable to create Call Graph Pass Manager");
600 PMDataManager *PMD = PMS.top();
601
602 // [1] Create new Call Graph Pass Manager
603 CGP = new CGPassManager();
604
605 // [2] Set up new manager's top level manager
607 TPM->addIndirectPassManager(CGP);
608
609 // [3] Assign manager to manage this new manager. This may create
610 // and push new managers into PMS
611 Pass *P = CGP;
612 TPM->schedulePass(P);
613
614 // [4] Push new manager into PMS
615 PMS.push(CGP);
616 }
617
618 CGP->add(this);
619}
620
621/// For this class, we declare that we require and preserve the call graph.
622/// If the derived class implements this method, it should
623/// always explicitly call the implementation here.
628
629//===----------------------------------------------------------------------===//
630// PrintCallGraphPass Implementation
631//===----------------------------------------------------------------------===//
632
633namespace {
634
635 /// PrintCallGraphPass - Print a Module corresponding to a call graph.
636 ///
637 class PrintCallGraphPass : public CallGraphSCCPass {
638 std::string Banner;
639 raw_ostream &OS; // raw_ostream to print on.
640
641 public:
642 static char ID;
643
644 PrintCallGraphPass(const std::string &B, raw_ostream &OS)
645 : CallGraphSCCPass(ID), Banner(B), OS(OS) {}
646
647 void getAnalysisUsage(AnalysisUsage &AU) const override {
648 AU.setPreservesAll();
649 }
650
651 bool runOnSCC(CallGraphSCC &SCC) override {
652 bool BannerPrinted = false;
653 auto PrintBannerOnce = [&]() {
654 if (BannerPrinted)
655 return;
656 OS << Banner << "\n";
657 BannerPrinted = true;
658 };
659
660 bool NeedModule = llvm::forcePrintModuleIR();
661 if (shouldPrintAllFunctions() && NeedModule) {
662 PrintBannerOnce();
663 OS << "\n";
664 SCC.getCallGraph().getModule().print(OS, nullptr);
665 return false;
666 }
667 bool FoundFunction = false;
668 for (CallGraphNode *CGN : SCC) {
669 if (Function *F = CGN->getFunction()) {
670 if (!F->isDeclaration() && shouldPrintFunction(*F)) {
671 FoundFunction = true;
672 if (!NeedModule) {
673 PrintBannerOnce();
674 F->print(OS);
675 }
676 }
677 } else if (shouldPrintAllFunctions()) {
678 PrintBannerOnce();
679 OS << "\nPrinting <null> Function\n";
680 }
681 }
682 if (NeedModule && FoundFunction) {
683 PrintBannerOnce();
684 OS << "\n";
685 SCC.getCallGraph().getModule().print(OS, nullptr);
686 }
687 return false;
688 }
689
690 StringRef getPassName() const override { return "Print CallGraph IR"; }
691 };
692
693} // end anonymous namespace.
694
695char PrintCallGraphPass::ID = 0;
696
698 const std::string &Banner) const {
699 return new PrintCallGraphPass(Banner, OS);
700}
701
702char DummyCGSCCPass::ID = 0;
703
704INITIALIZE_PASS(DummyCGSCCPass, "DummyCGSCCPass", "DummyCGSCCPass", false,
705 false)
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
static unsigned InstrCount
This file defines the DenseMap class.
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:629
Machine Check Debug Module
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This header defines classes/functions to handle pass execution timing information with interfaces for...
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI void print(raw_ostream &OS) const
void addCalledFunction(CallBase *Call, CallGraphNode *M)
Adds a function to the list of functions called by this one.
Definition CallGraph.h:222
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
std::vector< CallRecord >::iterator iterator
Definition CallGraph.h:189
void removeCallEdge(iterator I)
Definition CallGraph.h:229
Pass * createPrinterPass(raw_ostream &OS, const std::string &Banner) const override
createPrinterPass - Get a pass that prints the Module corresponding to a CallGraph.
virtual bool runOnSCC(CallGraphSCC &SCC)=0
runOnSCC - This method should be implemented by the subclass to perform whatever action is necessary ...
void getAnalysisUsage(AnalysisUsage &Info) const override
getAnalysisUsage - For this class, we declare that we require and preserve the call graph.
void assignPassManager(PMStack &PMS, PassManagerType PMT) override
Assign pass manager to manager this pass.
CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
std::vector< CallGraphNode * >::const_iterator iterator
unsigned size() const
iterator begin() const
iterator end() const
The ModulePass which wraps up a CallGraph and the logic to build it.
Definition CallGraph.h:314
The basic data container for the call graph of a Module of IR.
Definition CallGraph.h:72
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.
CallGraphNode * getCallsExternalNode() const
Definition CallGraph.h:129
Module & getModule() const
Returns the module the call graph corresponds to.
Definition CallGraph.h:101
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
This pass is required by interprocedural register allocation.
static LLVM_ABI char ID
bool runOnFunction(Function &F)
run - Execute all of the passes scheduled for execution.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
PMDataManager provides the common place to manage the analysis data used by pass managers.
PMTopLevelManager * getTopLevelManager()
virtual PassManagerType getPassManagerType() const
PMStack - This class implements a stack data structure of PMDataManager pointers.
LLVM_ABI void pop()
PMDataManager * top() const
LLVM_ABI void push(PMDataManager *PM)
PMTopLevelManager manages LastUser info and collects common APIs used by top level pass managers.
void addIndirectPassManager(PMDataManager *Manager)
void schedulePass(Pass *P)
Schedule pass P for execution.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
Pass(PassKind K, char &pid)
Definition Pass.h:103
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
bool isAtEnd() const
Direct loop termination test which is more efficient than comparison with end().
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr double e
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI unsigned getMaxDevirtIterations(const cl::LibraryOptionsContext *)
LLVM_ABI bool forcePrintModuleIR()
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
PassManagerType
Different types of internal pass managers.
Definition Pass.h:56
@ PMT_CallGraphPassManager
CGPassManager.
Definition Pass.h:59
@ PMT_FunctionPassManager
FPPassManager.
Definition Pass.h:60
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI Timer * getPassTimer(Pass *)
Request the timer for this legacy-pass-manager's pass instance.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool shouldPrintFunction(const Function &F)
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void forEachCallbackFunction(const CallBase &CB, UnaryFunction Func)
Apply function Func to each CB's callback function.
LLVM_ABI bool shouldPrintAllFunctions()
#define N