42 #define DEBUG_TYPE "cgscc-passmgr" 47 STATISTIC(MaxSCCIterations,
"Maximum CGSCCPassMgr iterations on one SCC");
64 bool runOnModule(
Module &M)
override;
79 StringRef getPassName()
const override {
return "CallGraph Pass Manager"; }
82 Pass *getAsPass()
override {
return this; }
85 void dumpPassStructure(
unsigned Offset)
override {
86 errs().
indent(Offset*2) <<
"Call Graph SCC Pass Manager\n";
90 dumpLastUses(P, Offset+1);
94 Pass *getContainedPass(
unsigned N) {
95 assert(N < PassVector.size() &&
"Pass number out of range!");
96 return static_cast<Pass *
>(PassVector[
N]);
105 bool &DevirtualizedCall);
109 bool &DevirtualizedCall);
111 bool IsCheckingMode);
120 bool &DevirtualizedCall) {
121 bool Changed =
false;
127 if (!CallGraphUpToDate) {
128 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG,
false);
129 CallGraphUpToDate =
true;
138 InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
145 if (SCCCount != InstrCount) {
148 static_cast<int64_t
>(SCCCount) - static_cast<int64_t>(InstrCount);
149 emitInstrCountChangedRemark(P, M, Delta, InstrCount,
150 FunctionToInstrCount);
151 InstrCount = SCCCount;
160 RefreshCallGraph(CurSCC, CG,
true);
167 "Invalid CGPassManager member");
176 Changed |= FPP->runOnFunction(*
F);
178 F->getContext().yield();
184 if (Changed && CallGraphUpToDate) {
187 CallGraphUpToDate =
false;
208 : CurSCC) CGN->dump(););
210 bool MadeChange =
false;
211 bool DevirtualizedCall =
false;
214 unsigned FunctionNo = 0;
216 SCCIdx !=
E; ++SCCIdx, ++FunctionNo) {
226 unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0;
232 auto *Call = dyn_cast_or_null<CallBase>(
I->first);
244 (Call->getCalledFunction() &&
245 Call->getCalledFunction()->isIntrinsic() &&
248 "CallGraphSCCPass did not update the CallGraph correctly!");
251 if (!
I->second->getFunction())
252 ++NumIndirectRemoved;
258 bool WasLast =
I + 1 ==
E;
271 "Call site occurs in node multiple times");
277 Calls.
insert(std::make_pair(
I->first,
I->second));
284 unsigned NumDirectAdded = 0, NumIndirectAdded = 0;
291 Function *Callee = Call->getCalledFunction();
299 if (ExistingIt != Calls.
end()) {
303 Calls.
erase(ExistingIt);
306 if (ExistingNode->
getFunction() == Call->getCalledFunction())
314 if (CheckingMode && Call->getCalledFunction() &&
319 "CallGraphSCCPass did not update the CallGraph correctly!");
324 if (
Function *Callee = Call->getCalledFunction()) {
329 DevirtualizedCall =
true;
331 << Callee->
getName() <<
"'\n");
344 "CallGraphSCCPass did not update the CallGraph correctly!");
348 if (
Function *Callee = Call->getCalledFunction()) {
370 if (NumIndirectRemoved > NumIndirectAdded &&
371 NumDirectRemoved < NumDirectAdded)
372 DevirtualizedCall =
true;
378 assert(Calls.
empty() &&
"Dangling pointers found in call sites map");
382 if ((FunctionNo & 15) == 15)
387 dbgs() <<
"CGSCCPASSMGR: Refreshed SCC is now:\n";
390 if (DevirtualizedCall)
391 dbgs() <<
"CGSCCPASSMGR: Refresh devirtualized a call!\n";
393 dbgs() <<
"CGSCCPASSMGR: SCC Refresh didn't change call graph.\n";
397 return DevirtualizedCall;
404 bool &DevirtualizedCall) {
405 bool Changed =
false;
414 bool CallGraphUpToDate =
true;
417 for (
unsigned PassNo = 0,
e = getNumContainedPasses();
418 PassNo !=
e; ++PassNo) {
419 Pass *P = getContainedPass(PassNo);
423 if (isPassDebuggingExecutionsOrMore()) {
424 std::string Functions;
429 if (
I != CurSCC.
begin()) OS <<
", ";
438 initializeAnalysisImpl(P);
441 Changed |= RunPassOnSCC(P, CurSCC, CG,
442 CallGraphUpToDate, DevirtualizedCall);
448 verifyPreservedAnalysis(P);
449 removeNotPreservedAnalysis(P);
450 recordAvailableAnalysis(P);
456 if (!CallGraphUpToDate)
457 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG,
false);
463 bool CGPassManager::runOnModule(
Module &M) {
464 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
465 bool Changed = doInitialization(CG);
474 const std::vector<CallGraphNode *> &NodeVec = *CGI;
490 unsigned Iteration = 0;
491 bool DevirtualizedCall =
false;
494 <<
" SCCPASSMGR: Re-visiting SCC, iteration #" << Iteration
496 DevirtualizedCall =
false;
497 Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall);
500 if (DevirtualizedCall)
503 <<
" times, due to -max-cg-scc-iterations\n");
505 MaxSCCIterations.updateMax(Iteration);
507 Changed |= doFinalization(CG);
512 bool CGPassManager::doInitialization(
CallGraph &CG) {
513 bool Changed =
false;
514 for (
unsigned i = 0,
e = getNumContainedPasses(); i !=
e; ++i) {
515 if (
PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
517 "Invalid CGPassManager member");
527 bool CGPassManager::doFinalization(
CallGraph &CG) {
528 bool Changed =
false;
529 for (
unsigned i = 0,
e = getNumContainedPasses(); i !=
e; ++i) {
530 if (
PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
532 "Invalid CGPassManager member");
548 assert(Old != New &&
"Should not replace node with self");
549 for (
unsigned i = 0; ; ++i) {
550 assert(i != Nodes.size() &&
"Node not in SCC");
551 if (Nodes[i] != Old)
continue;
570 while (!PMS.
empty() &&
574 assert(!PMS.
empty() &&
"Unable to handle Call Graph Pass");
578 CGP = (CGPassManager*)PMS.
top();
581 assert(!PMS.
empty() &&
"Unable to create Call Graph Pass Manager");
585 CGP =
new CGPassManager();
626 PrintCallGraphPass(
const std::string &
B,
raw_ostream &OS)
634 bool BannerPrinted =
false;
635 auto PrintBannerOnce = [&]() {
639 BannerPrinted =
true;
649 bool FoundFunction =
false;
653 FoundFunction =
true;
661 OS <<
"\nPrinting <null> Function\n";
664 if (NeedModule && FoundFunction) {
667 SCC.getCallGraph().getModule().print(OS,
nullptr);
672 StringRef getPassName()
const override {
return "Print CallGraph IR"; }
680 const std::string &Banner)
const {
681 return new PrintCallGraphPass(Banner, OS);
685 std::string Desc =
"SCC (";
696 Desc +=
"<<null function>>";
Pass interface - Implemented by all 'passes'.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
PassManagerType
Different types of internal pass managers.
bool forcePrintModuleIR()
forcePrintModuleIR - returns true if IR printing passes should
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
This class represents lattice values for constants.
virtual PMDataManager * getAsPMDataManager()
virtual void dumpPassStructure(unsigned Offset=0)
A Module instance is used to store all the information related to an LLVM module. ...
Extensions to this class implement mechanisms to disable passes and individual optimizations at compi...
void ReplaceNode(NodeRef Old, NodeRef New)
This informs the scc_iterator that the specified Old node has been deleted, and New is to be used in ...
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
STATISTIC(NumFunctions, "Total number of functions")
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
static unsigned InstrCount
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
A node in the call graph for a module.
bool skipSCC(CallGraphSCC &SCC) const
Optional passes call this function to check whether the pass should be skipped.
void getAnalysisUsage(AnalysisUsage &Info) const override
getAnalysisUsage - For this class, we declare that we require and preserve the call graph...
Module & getModule() const
Returns the module the call graph corresponds to.
virtual bool shouldRunPass(const Pass *P, StringRef IRDescription)
IRDescription is a textual description of the IR unit the pass is running over.
Pass * createPrinterPass(raw_ostream &OS, const std::string &Banner) const override
createPrinterPass - Get a pass that prints the Module corresponding to a CallGraph.
PMTopLevelManager manages LastUser info and collects common APIs used by top level pass managers...
Timer * getPassTimer(Pass *)
Request the timer for this legacy-pass-manager's pass instance.
The TimeRegion class is used as a helper class to call the startTimer() and stopTimer() methods of th...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
void schedulePass(Pass *P)
Schedule pass P for execution.
AnalysisUsage & addRequired()
LLVMContext & getContext() const
Get the global data context.
virtual bool doFinalization(Module &)
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
unsigned getInstructionCount()
Returns the number of non-debug IR instructions in the module.
const CallGraph & getCallGraph()
This header defines classes/functions to handle pass execution timing information with interfaces for...
FPPassManager manages BBPassManagers and FunctionPasses.
PMStack - This class implements a stack data structure of PMDataManager pointers. ...
virtual bool isEnabled() const
isEnabled should return true before calling shouldRunPass
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
bool isAtEnd() const
Direct loop termination test which is more efficient than comparison with end().
void dump() const
Print out this call graph node.
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
OptPassGate & getOptPassGate() const
Access the object which can disable optional passes and individual optimizations at compile time...
static std::string getDescription(const CallGraphSCC &SCC)
Analysis containing CSE Info
virtual bool doInitialization(Module &)
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
static cl::opt< unsigned > MaxIterations("max-cg-scc-iterations", cl::ReallyHidden, cl::init(4))
iterator find(const_arg_type_t< KeyT > Val)
initializer< Ty > init(const Ty &Val)
bool erase(const KeyT &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This pass is required by interprocedural register allocation.
The ModulePass which wraps up a CallGraph and the logic to build it.
bool isLeaf(ID id)
Returns true if the intrinsic is a leaf, i.e.
CallGraphNode * getCallsExternalNode() const
LLVM Basic Block Representation.
bool shouldEmitInstrCountChangedRemark()
Return true if size-info optimization remark is enabled, false otherwise.
void addIndirectPassManager(PMDataManager *Manager)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
virtual PassManagerType getPassManagerType() const
Represent the analysis usage information of a pass.
void initialize(ArrayRef< CallGraphNode *> NewNodes)
void assignPassManager(PMStack &PMS, PassManagerType PMT) override
Assign pass manager to manager this pass.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Function * getFunction() const
Returns the function that this call graph node represents.
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the module to an output stream with an optional AssemblyAnnotationWriter.
Module.h This file contains the declarations for the Module class.
This file declares the interface for bisecting optimizations.
bool isFunctionInPrintList(StringRef FunctionName)
isFunctionInPrintList - returns true if a function should be printed via
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
amdgpu Simplify well known AMD library false FunctionCallee Callee
void setPreservesAll()
Set by analyses that do not transform their input at all.
void removeCallEdge(iterator I)
The basic data container for the call graph of a Module of IR.
void ReplaceNode(CallGraphNode *Old, CallGraphNode *New)
ReplaceNode - This informs the SCC and the pass manager that the specified Old node has been deleted...
void replaceCallEdge(CallBase &Call, CallBase &NewCall, CallGraphNode *NewNode)
Replaces the edge in the node for the specified call site with a new one.
StringRef getName() const
Return a constant reference to the value's name.
std::vector< CallGraphNode * >::const_iterator iterator
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
std::vector< CallRecord >::iterator iterator
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
void push(PMDataManager *PM)
LLVM_NODISCARD bool empty() const
PMDataManager provides the common place to manage the analysis data used by pass managers.
This file defines passes to print out IR in various granularities.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
virtual bool runOnSCC(CallGraphSCC &SCC)=0
runOnSCC - This method should be implemented by the subclass to perform whatever action is necessary ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
PMDataManager * top() const
CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
CallGraphNode * getOrInsertFunction(const Function *F)
Similar to operator[], but this will insert a new CallGraphNode for F if one does not already exist...
This class implements an extremely fast bulk output stream that can only output to a stream...
StringRef - Represent a constant reference to a string, i.e.
void addCalledFunction(CallBase *Call, CallGraphNode *M)
Adds a function to the list of functions called by this one.
Enumerate the SCCs of a directed graph in reverse topological order of the SCC DAG.