blob: ef61c65463fdfe39179634376b3252f232b382e9 [file] [log] [blame]
Chris Lattnerf7e95942003-08-31 01:54:59 +00001//===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman01808ca2005-04-21 21:13:18 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerf7e95942003-08-31 01:54:59 +00009//
10// This file implements the CallGraphSCCPass class, which is used for passes
11// which are implemented as bottom-up traversals on the call graph. Because
12// there may be cycles in the call graph, passes of this type operate on the
13// call-graph in SCC order: that is, they process function bottom-up, except for
14// recursive functions, which they process all at once.
15//
16//===----------------------------------------------------------------------===//
17
Chandler Carruth839a98e2013-01-07 15:26:48 +000018#include "llvm/Analysis/CallGraphSCCPass.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000019#include "llvm/ADT/DenseMap.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000020#include "llvm/ADT/SCCIterator.h"
Chris Lattner6fbe7042010-04-21 00:47:40 +000021#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/CallGraph.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000023#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Function.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000025#include "llvm/IR/Intrinsics.h"
Juergen Ributzka34390c72014-05-16 02:33:15 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000027#include "llvm/IR/LegacyPassManagers.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000028#include "llvm/IR/Module.h"
Andrew Kayloraa641a52016-04-22 22:06:11 +000029#include "llvm/IR/OptBisect.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000030#include "llvm/Pass.h"
Chris Lattner6fbe7042010-04-21 00:47:40 +000031#include "llvm/Support/CommandLine.h"
Chris Lattnereedcd842009-08-31 07:23:46 +000032#include "llvm/Support/Debug.h"
Chris Lattner707431c2010-03-30 04:03:22 +000033#include "llvm/Support/Timer.h"
Chris Lattner13626022009-08-23 06:03:38 +000034#include "llvm/Support/raw_ostream.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000035#include <cassert>
36#include <string>
37#include <utility>
38#include <vector>
39
Chris Lattner8d083812004-04-20 21:30:06 +000040using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000041
Chandler Carruthf1221bd2014-04-22 02:48:03 +000042#define DEBUG_TYPE "cgscc-passmgr"
43
Chris Lattner6fbe7042010-04-21 00:47:40 +000044static cl::opt<unsigned>
Chris Lattnerfc8d9ee2010-05-01 01:15:56 +000045MaxIterations("max-cg-scc-iterations", cl::ReallyHidden, cl::init(4));
Chris Lattner6fbe7042010-04-21 00:47:40 +000046
47STATISTIC(MaxSCCIterations, "Maximum CGSCCPassMgr iterations on one SCC");
48
Devang Patel48537a02007-01-17 21:45:01 +000049//===----------------------------------------------------------------------===//
50// CGPassManager
51//
Dale Johannesen50f03762009-09-10 22:01:32 +000052/// CGPassManager manages FPPassManagers and CallGraphSCCPasses.
Devang Patel48537a02007-01-17 21:45:01 +000053
Dan Gohmand78c4002008-05-13 00:00:25 +000054namespace {
55
Devang Patel48537a02007-01-17 21:45:01 +000056class CGPassManager : public ModulePass, public PMDataManager {
Devang Patel48537a02007-01-17 21:45:01 +000057public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000058 static char ID;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000059
60 explicit CGPassManager() : ModulePass(ID), PMDataManager() {}
Devang Patel48537a02007-01-17 21:45:01 +000061
Sanjay Pateld45a3f12015-03-10 03:48:14 +000062 /// Execute all of the passes scheduled for execution. Keep track of
Devang Patel48537a02007-01-17 21:45:01 +000063 /// whether any of the passes modifies the module, and if so, return true.
Craig Toppere9ba7592014-03-05 07:30:04 +000064 bool runOnModule(Module &M) override;
Devang Patel48537a02007-01-17 21:45:01 +000065
Owen Anderson1aa27512012-11-15 00:14:15 +000066 using ModulePass::doInitialization;
67 using ModulePass::doFinalization;
68
Bill Wendling5f14a012009-02-11 18:19:24 +000069 bool doInitialization(CallGraph &CG);
70 bool doFinalization(CallGraph &CG);
Devang Patel48537a02007-01-17 21:45:01 +000071
72 /// Pass Manager itself does not invalidate any analysis info.
Craig Toppere9ba7592014-03-05 07:30:04 +000073 void getAnalysisUsage(AnalysisUsage &Info) const override {
Devang Patel48537a02007-01-17 21:45:01 +000074 // CGPassManager walks SCC and it needs CallGraph.
Chandler Carruth6378cf52013-11-26 04:19:30 +000075 Info.addRequired<CallGraphWrapperPass>();
Devang Patel48537a02007-01-17 21:45:01 +000076 Info.setPreservesAll();
77 }
78
Mehdi Amini117296c2016-10-01 02:56:57 +000079 StringRef getPassName() const override { return "CallGraph Pass Manager"; }
Devang Patelf7fea8a2007-02-01 22:09:37 +000080
Craig Toppere9ba7592014-03-05 07:30:04 +000081 PMDataManager *getAsPMDataManager() override { return this; }
82 Pass *getAsPass() override { return this; }
Chris Lattner2fa26e52010-01-22 05:24:46 +000083
Devang Patel48537a02007-01-17 21:45:01 +000084 // Print passes managed by this manager
Craig Toppere9ba7592014-03-05 07:30:04 +000085 void dumpPassStructure(unsigned Offset) override {
David Greene3d646312009-12-23 23:09:39 +000086 errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n";
Devang Patel48537a02007-01-17 21:45:01 +000087 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
88 Pass *P = getContainedPass(Index);
Dan Gohmanf71c5212010-08-19 01:29:07 +000089 P->dumpPassStructure(Offset + 1);
Devang Patel48537a02007-01-17 21:45:01 +000090 dumpLastUses(P, Offset+1);
91 }
92 }
93
94 Pass *getContainedPass(unsigned N) {
Chris Lattner13626022009-08-23 06:03:38 +000095 assert(N < PassVector.size() && "Pass number out of range!");
96 return static_cast<Pass *>(PassVector[N]);
Devang Patel48537a02007-01-17 21:45:01 +000097 }
98
Craig Toppere9ba7592014-03-05 07:30:04 +000099 PassManagerType getPassManagerType() const override {
Devang Patel48537a02007-01-17 21:45:01 +0000100 return PMT_CallGraphPassManager;
101 }
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000102
103private:
Chris Lattner6fbe7042010-04-21 00:47:40 +0000104 bool RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
105 bool &DevirtualizedCall);
106
Chris Lattner4422d312010-04-16 22:42:17 +0000107 bool RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
Chris Lattner6fbe7042010-04-21 00:47:40 +0000108 CallGraph &CG, bool &CallGraphUpToDate,
109 bool &DevirtualizedCall);
Mehdi Aminic137c282016-08-08 18:51:05 +0000110 bool RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG,
Chris Lattnere33167a2009-09-01 18:32:03 +0000111 bool IsCheckingMode);
Devang Patel48537a02007-01-17 21:45:01 +0000112};
113
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000114} // end anonymous namespace.
Dan Gohmand78c4002008-05-13 00:00:25 +0000115
Devang Patel8c78a0b2007-05-03 01:11:54 +0000116char CGPassManager::ID = 0;
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000117
Chris Lattner4422d312010-04-16 22:42:17 +0000118bool CGPassManager::RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
Chris Lattner6fbe7042010-04-21 00:47:40 +0000119 CallGraph &CG, bool &CallGraphUpToDate,
120 bool &DevirtualizedCall) {
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000121 bool Changed = false;
Chris Lattner0b1c7232010-01-22 05:46:59 +0000122 PMDataManager *PM = P->getAsPMDataManager();
Jessica Paquettee49374d2018-05-18 17:26:39 +0000123 Module &M = CG.getModule();
Chris Lattner0b1c7232010-01-22 05:46:59 +0000124
Craig Topper353eda42014-04-24 06:44:33 +0000125 if (!PM) {
Chris Lattner0b1c7232010-01-22 05:46:59 +0000126 CallGraphSCCPass *CGSP = (CallGraphSCCPass*)P;
Chris Lattnereedcd842009-08-31 07:23:46 +0000127 if (!CallGraphUpToDate) {
Chris Lattner6fbe7042010-04-21 00:47:40 +0000128 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
Chris Lattnereedcd842009-08-31 07:23:46 +0000129 CallGraphUpToDate = true;
130 }
Chris Lattner339c82d2009-09-01 20:33:43 +0000131
Chris Lattner707431c2010-03-30 04:03:22 +0000132 {
133 TimeRegion PassTimer(getPassTimer(CGSP));
Jessica Paquettee49374d2018-05-18 17:26:39 +0000134 unsigned InstrCount = initSizeRemarkInfo(M);
Chris Lattner707431c2010-03-30 04:03:22 +0000135 Changed = CGSP->runOnSCC(CurSCC);
Jessica Paquettee49374d2018-05-18 17:26:39 +0000136
137 // If the pass modified the module, it may have modified the instruction
138 // count of the module. Try emitting a remark.
139 emitInstrCountChangedRemark(P, M, InstrCount);
Chris Lattner707431c2010-03-30 04:03:22 +0000140 }
Chris Lattnere33167a2009-09-01 18:32:03 +0000141
142 // After the CGSCCPass is done, when assertions are enabled, use
143 // RefreshCallGraph to verify that the callgraph was correctly updated.
144#ifndef NDEBUG
145 if (Changed)
146 RefreshCallGraph(CurSCC, CG, true);
147#endif
148
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000149 return Changed;
150 }
151
Chris Lattner0b1c7232010-01-22 05:46:59 +0000152 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
153 "Invalid CGPassManager member");
154 FPPassManager *FPP = (FPPassManager*)P;
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000155
156 // Run pass P on all functions in the current SCC.
Sanjay Patelc6012542015-03-10 03:26:39 +0000157 for (CallGraphNode *CGN : CurSCC) {
158 if (Function *F = CGN->getFunction()) {
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000159 dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());
Juergen Ributzka34390c72014-05-16 02:33:15 +0000160 {
161 TimeRegion PassTimer(getPassTimer(FPP));
162 Changed |= FPP->runOnFunction(*F);
163 }
164 F->getContext().yield();
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000165 }
166 }
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000167
Chris Lattnera9262bb2009-08-31 17:08:30 +0000168 // The function pass(es) modified the IR, they may have clobbered the
Chris Lattnereedcd842009-08-31 07:23:46 +0000169 // callgraph.
170 if (Changed && CallGraphUpToDate) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000171 LLVM_DEBUG(dbgs() << "CGSCCPASSMGR: Pass Dirtied SCC: " << P->getPassName()
172 << '\n');
Chris Lattnereedcd842009-08-31 07:23:46 +0000173 CallGraphUpToDate = false;
174 }
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000175 return Changed;
176}
177
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000178/// Scan the functions in the specified CFG and resync the
Chris Lattnere33167a2009-09-01 18:32:03 +0000179/// callgraph with the call sites found in it. This is used after
180/// FunctionPasses have potentially munged the callgraph, and can be used after
181/// CallGraphSCC passes to verify that they correctly updated the callgraph.
182///
Chris Lattner6fbe7042010-04-21 00:47:40 +0000183/// This function returns true if it devirtualized an existing function call,
184/// meaning it turned an indirect call into a direct call. This happens when
185/// a function pass like GVN optimizes away stuff feeding the indirect call.
186/// This never happens in checking mode.
Mehdi Aminic137c282016-08-08 18:51:05 +0000187bool CGPassManager::RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG,
188 bool CheckingMode) {
Chris Lattner063d0652009-09-01 06:31:31 +0000189 DenseMap<Value*, CallGraphNode*> CallSites;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000190
191 LLVM_DEBUG(dbgs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size()
192 << " nodes:\n";
193 for (CallGraphNode *CGN
194 : CurSCC) CGN->dump(););
Chris Lattnereedcd842009-08-31 07:23:46 +0000195
196 bool MadeChange = false;
Chris Lattner6fbe7042010-04-21 00:47:40 +0000197 bool DevirtualizedCall = false;
Chris Lattnereedcd842009-08-31 07:23:46 +0000198
199 // Scan all functions in the SCC.
Chris Lattner4422d312010-04-16 22:42:17 +0000200 unsigned FunctionNo = 0;
201 for (CallGraphSCC::iterator SCCIdx = CurSCC.begin(), E = CurSCC.end();
202 SCCIdx != E; ++SCCIdx, ++FunctionNo) {
203 CallGraphNode *CGN = *SCCIdx;
Chris Lattnereedcd842009-08-31 07:23:46 +0000204 Function *F = CGN->getFunction();
Craig Topper353eda42014-04-24 06:44:33 +0000205 if (!F || F->isDeclaration()) continue;
Chris Lattnereedcd842009-08-31 07:23:46 +0000206
207 // Walk the function body looking for call sites. Sync up the call sites in
208 // CGN with those actually in the function.
Chris Lattner532112b2010-05-01 06:38:43 +0000209
210 // Keep track of the number of direct and indirect calls that were
211 // invalidated and removed.
212 unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0;
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000213
Chris Lattnereedcd842009-08-31 07:23:46 +0000214 // Get the set of call sites currently in the function.
Duncan Sands5632d962009-09-02 03:48:41 +0000215 for (CallGraphNode::iterator I = CGN->begin(), E = CGN->end(); I != E; ) {
Chris Lattner063d0652009-09-01 06:31:31 +0000216 // If this call site is null, then the function pass deleted the call
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000217 // entirely and the WeakTrackingVH nulled it out.
Craig Topper353eda42014-04-24 06:44:33 +0000218 if (!I->first ||
Chris Lattner063d0652009-09-01 06:31:31 +0000219 // If we've already seen this call site, then the FunctionPass RAUW'd
220 // one call with another, which resulted in two "uses" in the edge
221 // list of the same call.
222 CallSites.count(I->first) ||
223
Chad Rosier7a20ed72015-04-14 15:52:57 +0000224 // If the call edge is not from a call or invoke, or it is a
225 // instrinsic call, then the function pass RAUW'd a call with
226 // another value. This can happen when constant folding happens
227 // of well known functions etc.
228 !CallSite(I->first) ||
Sanjoy Dasc65d43e2015-06-18 19:28:26 +0000229 (CallSite(I->first).getCalledFunction() &&
230 CallSite(I->first).getCalledFunction()->isIntrinsic() &&
231 Intrinsic::isLeaf(
232 CallSite(I->first).getCalledFunction()->getIntrinsicID()))) {
Chris Lattnere33167a2009-09-01 18:32:03 +0000233 assert(!CheckingMode &&
234 "CallGraphSCCPass did not update the CallGraph correctly!");
235
Chris Lattner532112b2010-05-01 06:38:43 +0000236 // If this was an indirect call site, count it.
Craig Topper353eda42014-04-24 06:44:33 +0000237 if (!I->second->getFunction())
Chris Lattner532112b2010-05-01 06:38:43 +0000238 ++NumIndirectRemoved;
239 else
240 ++NumDirectRemoved;
241
Chris Lattner65fb5972009-09-02 04:39:04 +0000242 // Just remove the edge from the set of callees, keep track of whether
243 // I points to the last element of the vector.
244 bool WasLast = I + 1 == E;
Chris Lattner063d0652009-09-01 06:31:31 +0000245 CGN->removeCallEdge(I);
Chris Lattner8f232762009-09-02 04:34:06 +0000246
Chris Lattner65fb5972009-09-02 04:39:04 +0000247 // If I pointed to the last element of the vector, we have to bail out:
248 // iterator checking rejects comparisons of the resultant pointer with
249 // end.
250 if (WasLast)
251 break;
Chris Lattner063d0652009-09-01 06:31:31 +0000252 E = CGN->end();
Chris Lattner063d0652009-09-01 06:31:31 +0000253 continue;
254 }
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000255
Chris Lattner063d0652009-09-01 06:31:31 +0000256 assert(!CallSites.count(I->first) &&
Chris Lattnereedcd842009-08-31 07:23:46 +0000257 "Call site occurs in node multiple times");
Sanjay Patel4c219fd2014-11-12 18:25:47 +0000258
259 CallSite CS(I->first);
260 if (CS) {
261 Function *Callee = CS.getCalledFunction();
262 // Ignore intrinsics because they're not really function calls.
263 if (!Callee || !(Callee->isIntrinsic()))
264 CallSites.insert(std::make_pair(I->first, I->second));
265 }
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000266 ++I;
Chris Lattnereedcd842009-08-31 07:23:46 +0000267 }
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000268
Chris Lattnereedcd842009-08-31 07:23:46 +0000269 // Loop over all of the instructions in the function, getting the callsites.
Chris Lattner532112b2010-05-01 06:38:43 +0000270 // Keep track of the number of direct/indirect calls added.
271 unsigned NumDirectAdded = 0, NumIndirectAdded = 0;
Benjamin Krameraa209152016-06-26 17:27:42 +0000272
273 for (BasicBlock &BB : *F)
274 for (Instruction &I : BB) {
275 CallSite CS(&I);
Nuno Lopes674acc12012-06-29 17:49:32 +0000276 if (!CS) continue;
277 Function *Callee = CS.getCalledFunction();
278 if (Callee && Callee->isIntrinsic()) continue;
Chris Lattnereedcd842009-08-31 07:23:46 +0000279
280 // If this call site already existed in the callgraph, just verify it
281 // matches up to expectations and remove it from CallSites.
Chris Lattner063d0652009-09-01 06:31:31 +0000282 DenseMap<Value*, CallGraphNode*>::iterator ExistingIt =
Chris Lattnereedcd842009-08-31 07:23:46 +0000283 CallSites.find(CS.getInstruction());
284 if (ExistingIt != CallSites.end()) {
285 CallGraphNode *ExistingNode = ExistingIt->second;
286
287 // Remove from CallSites since we have now seen it.
288 CallSites.erase(ExistingIt);
289
290 // Verify that the callee is right.
291 if (ExistingNode->getFunction() == CS.getCalledFunction())
292 continue;
293
Chris Lattnere33167a2009-09-01 18:32:03 +0000294 // If we are in checking mode, we are not allowed to actually mutate
295 // the callgraph. If this is a case where we can infer that the
296 // callgraph is less precise than it could be (e.g. an indirect call
297 // site could be turned direct), don't reject it in checking mode, and
298 // don't tweak it to be more precise.
299 if (CheckingMode && CS.getCalledFunction() &&
Craig Topper353eda42014-04-24 06:44:33 +0000300 ExistingNode->getFunction() == nullptr)
Chris Lattnere33167a2009-09-01 18:32:03 +0000301 continue;
302
303 assert(!CheckingMode &&
304 "CallGraphSCCPass did not update the CallGraph correctly!");
305
Chris Lattnereedcd842009-08-31 07:23:46 +0000306 // If not, we either went from a direct call to indirect, indirect to
307 // direct, or direct to different direct.
308 CallGraphNode *CalleeNode;
Chris Lattner6fbe7042010-04-21 00:47:40 +0000309 if (Function *Callee = CS.getCalledFunction()) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000310 CalleeNode = CG.getOrInsertFunction(Callee);
Chris Lattner6fbe7042010-04-21 00:47:40 +0000311 // Keep track of whether we turned an indirect call into a direct
312 // one.
Craig Topper353eda42014-04-24 06:44:33 +0000313 if (!ExistingNode->getFunction()) {
Chris Lattner6fbe7042010-04-21 00:47:40 +0000314 DevirtualizedCall = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000315 LLVM_DEBUG(dbgs() << " CGSCCPASSMGR: Devirtualized call to '"
316 << Callee->getName() << "'\n");
Chris Lattner6fbe7042010-04-21 00:47:40 +0000317 }
318 } else {
Chris Lattnereedcd842009-08-31 07:23:46 +0000319 CalleeNode = CG.getCallsExternalNode();
Chris Lattner6fbe7042010-04-21 00:47:40 +0000320 }
Chris Lattner339c82d2009-09-01 20:33:43 +0000321
322 // Update the edge target in CGN.
Chris Lattner055cf262010-04-22 20:42:33 +0000323 CGN->replaceCallEdge(CS, CS, CalleeNode);
Chris Lattnereedcd842009-08-31 07:23:46 +0000324 MadeChange = true;
325 continue;
326 }
327
Chris Lattnere33167a2009-09-01 18:32:03 +0000328 assert(!CheckingMode &&
329 "CallGraphSCCPass did not update the CallGraph correctly!");
330
Chris Lattner532112b2010-05-01 06:38:43 +0000331 // If the call site didn't exist in the CGN yet, add it.
Chris Lattnereedcd842009-08-31 07:23:46 +0000332 CallGraphNode *CalleeNode;
Chris Lattner532112b2010-05-01 06:38:43 +0000333 if (Function *Callee = CS.getCalledFunction()) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000334 CalleeNode = CG.getOrInsertFunction(Callee);
Chris Lattner532112b2010-05-01 06:38:43 +0000335 ++NumDirectAdded;
336 } else {
Chris Lattnereedcd842009-08-31 07:23:46 +0000337 CalleeNode = CG.getCallsExternalNode();
Chris Lattner532112b2010-05-01 06:38:43 +0000338 ++NumIndirectAdded;
339 }
Chris Lattnereedcd842009-08-31 07:23:46 +0000340
341 CGN->addCalledFunction(CS, CalleeNode);
342 MadeChange = true;
343 }
344
Chris Lattner532112b2010-05-01 06:38:43 +0000345 // We scanned the old callgraph node, removing invalidated call sites and
346 // then added back newly found call sites. One thing that can happen is
347 // that an old indirect call site was deleted and replaced with a new direct
348 // call. In this case, we have devirtualized a call, and CGSCCPM would like
349 // to iteratively optimize the new code. Unfortunately, we don't really
350 // have a great way to detect when this happens. As an approximation, we
351 // just look at whether the number of indirect calls is reduced and the
352 // number of direct calls is increased. There are tons of ways to fool this
353 // (e.g. DCE'ing an indirect call and duplicating an unrelated block with a
354 // direct call) but this is close enough.
355 if (NumIndirectRemoved > NumIndirectAdded &&
356 NumDirectRemoved < NumDirectAdded)
357 DevirtualizedCall = true;
Sanjoy Das2cbeb002017-04-26 16:37:05 +0000358
Chris Lattnereedcd842009-08-31 07:23:46 +0000359 // After scanning this function, if we still have entries in callsites, then
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000360 // they are dangling pointers. WeakTrackingVH should save us for this, so
361 // abort if
Sanjoy Das2cbeb002017-04-26 16:37:05 +0000362 // this happens.
Chris Lattner063d0652009-09-01 06:31:31 +0000363 assert(CallSites.empty() && "Dangling pointers found in call sites map");
Chris Lattnereedcd842009-08-31 07:23:46 +0000364
Chris Lattner063d0652009-09-01 06:31:31 +0000365 // Periodically do an explicit clear to remove tombstones when processing
366 // large scc's.
Chris Lattner4422d312010-04-16 22:42:17 +0000367 if ((FunctionNo & 15) == 15)
Chris Lattner063d0652009-09-01 06:31:31 +0000368 CallSites.clear();
Chris Lattnereedcd842009-08-31 07:23:46 +0000369 }
370
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000371 LLVM_DEBUG(if (MadeChange) {
372 dbgs() << "CGSCCPASSMGR: Refreshed SCC is now:\n";
373 for (CallGraphNode *CGN : CurSCC)
374 CGN->dump();
375 if (DevirtualizedCall)
376 dbgs() << "CGSCCPASSMGR: Refresh devirtualized a call!\n";
377 } else {
378 dbgs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n";
379 });
Duncan Sandsa41634e2011-08-12 14:54:45 +0000380 (void)MadeChange;
Chris Lattner6fbe7042010-04-21 00:47:40 +0000381
382 return DevirtualizedCall;
383}
384
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000385/// Execute the body of the entire pass manager on the specified SCC.
386/// This keeps track of whether a function pass devirtualizes
Chris Lattner6fbe7042010-04-21 00:47:40 +0000387/// any calls and returns it in DevirtualizedCall.
388bool CGPassManager::RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
389 bool &DevirtualizedCall) {
390 bool Changed = false;
391
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000392 // Keep track of whether the callgraph is known to be up-to-date or not.
393 // The CGSSC pass manager runs two types of passes:
Chris Lattner6fbe7042010-04-21 00:47:40 +0000394 // CallGraphSCC Passes and other random function passes. Because other
395 // random function passes are not CallGraph aware, they may clobber the
396 // call graph by introducing new calls or deleting other ones. This flag
397 // is set to false when we run a function pass so that we know to clean up
398 // the callgraph when we need to run a CGSCCPass again.
399 bool CallGraphUpToDate = true;
400
401 // Run all passes on current SCC.
402 for (unsigned PassNo = 0, e = getNumContainedPasses();
403 PassNo != e; ++PassNo) {
404 Pass *P = getContainedPass(PassNo);
405
406 // If we're in -debug-pass=Executions mode, construct the SCC node list,
407 // otherwise avoid constructing this string as it is expensive.
408 if (isPassDebuggingExecutionsOrMore()) {
409 std::string Functions;
410 #ifndef NDEBUG
411 raw_string_ostream OS(Functions);
412 for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
413 I != E; ++I) {
414 if (I != CurSCC.begin()) OS << ", ";
415 (*I)->print(OS);
416 }
417 OS.flush();
418 #endif
419 dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, Functions);
420 }
421 dumpRequiredSet(P);
422
423 initializeAnalysisImpl(P);
424
425 // Actually run this pass on the current SCC.
426 Changed |= RunPassOnSCC(P, CurSCC, CG,
427 CallGraphUpToDate, DevirtualizedCall);
428
429 if (Changed)
430 dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, "");
431 dumpPreservedSet(P);
432
433 verifyPreservedAnalysis(P);
434 removeNotPreservedAnalysis(P);
435 recordAvailableAnalysis(P);
436 removeDeadPasses(P, "", ON_CG_MSG);
437 }
438
439 // If the callgraph was left out of date (because the last pass run was a
440 // functionpass), refresh it before we move on to the next SCC.
441 if (!CallGraphUpToDate)
442 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
443 return Changed;
Chris Lattnereedcd842009-08-31 07:23:46 +0000444}
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000445
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000446/// Execute all of the passes scheduled for execution. Keep track of
Devang Patel48537a02007-01-17 21:45:01 +0000447/// whether any of the passes modifies the module, and if so, return true.
448bool CGPassManager::runOnModule(Module &M) {
Chandler Carruth6378cf52013-11-26 04:19:30 +0000449 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
Bill Wendling5f14a012009-02-11 18:19:24 +0000450 bool Changed = doInitialization(CG);
Evgeniy Stepanovca8c2f72018-07-13 16:32:31 +0000451
452 // Walk the callgraph in bottom-up SCC order.
453 scc_iterator<CallGraph*> CGI = scc_begin(&CG);
Chris Lattner5518b812010-04-16 22:59:24 +0000454
Evgeniy Stepanovca8c2f72018-07-13 16:32:31 +0000455 CallGraphSCC CurSCC(CG, &CGI);
456 while (!CGI.isAtEnd()) {
457 // Copy the current SCC and increment past it so that the pass can hack
458 // on the SCC if it wants to without invalidating our iterator.
459 const std::vector<CallGraphNode *> &NodeVec = *CGI;
460 CurSCC.initialize(NodeVec);
461 ++CGI;
Yaron Kerenafe39832015-07-02 14:17:12 +0000462
Evgeniy Stepanovca8c2f72018-07-13 16:32:31 +0000463 // At the top level, we run all the passes in this pass manager on the
464 // functions in this SCC. However, we support iterative compilation in the
465 // case where a function pass devirtualizes a call to a function. For
466 // example, it is very common for a function pass (often GVN or instcombine)
467 // to eliminate the addressing that feeds into a call. With that improved
468 // information, we would like the call to be an inline candidate, infer
469 // mod-ref information etc.
470 //
471 // Because of this, we allow iteration up to a specified iteration count.
472 // This only happens in the case of a devirtualized call, so we only burn
473 // compile time in the case that we're making progress. We also have a hard
474 // iteration count limit in case there is crazy code.
475 unsigned Iteration = 0;
476 bool DevirtualizedCall = false;
477 do {
478 LLVM_DEBUG(if (Iteration) dbgs()
479 << " SCCPASSMGR: Re-visiting SCC, iteration #" << Iteration
480 << '\n');
481 DevirtualizedCall = false;
482 Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall);
483 } while (Iteration++ < MaxIterations && DevirtualizedCall);
484
485 if (DevirtualizedCall)
486 LLVM_DEBUG(dbgs() << " CGSCCPASSMGR: Stopped iteration after "
487 << Iteration
488 << " times, due to -max-cg-scc-iterations\n");
Craig Topper8a950272017-05-18 00:51:39 +0000489
Evgeniy Stepanovca8c2f72018-07-13 16:32:31 +0000490 MaxSCCIterations.updateMax(Iteration);
Devang Patel48537a02007-01-17 21:45:01 +0000491 }
Bill Wendling5f14a012009-02-11 18:19:24 +0000492 Changed |= doFinalization(CG);
Devang Patel48537a02007-01-17 21:45:01 +0000493 return Changed;
494}
495
496/// Initialize CG
Bill Wendling5f14a012009-02-11 18:19:24 +0000497bool CGPassManager::doInitialization(CallGraph &CG) {
Devang Patel48537a02007-01-17 21:45:01 +0000498 bool Changed = false;
Chris Lattner0b1c7232010-01-22 05:46:59 +0000499 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
500 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
501 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
502 "Invalid CGPassManager member");
503 Changed |= ((FPPassManager*)PM)->doInitialization(CG.getModule());
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000504 } else {
Chris Lattner0b1c7232010-01-22 05:46:59 +0000505 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doInitialization(CG);
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000506 }
Devang Patel48537a02007-01-17 21:45:01 +0000507 }
508 return Changed;
509}
510
511/// Finalize CG
Bill Wendling5f14a012009-02-11 18:19:24 +0000512bool CGPassManager::doFinalization(CallGraph &CG) {
Devang Patel48537a02007-01-17 21:45:01 +0000513 bool Changed = false;
Chris Lattner0b1c7232010-01-22 05:46:59 +0000514 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
515 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
516 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
517 "Invalid CGPassManager member");
518 Changed |= ((FPPassManager*)PM)->doFinalization(CG.getModule());
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000519 } else {
Chris Lattner0b1c7232010-01-22 05:46:59 +0000520 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doFinalization(CG);
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000521 }
Devang Patel48537a02007-01-17 21:45:01 +0000522 }
523 return Changed;
524}
525
Chris Lattner6d1208f2010-04-16 21:43:55 +0000526//===----------------------------------------------------------------------===//
Chris Lattner4422d312010-04-16 22:42:17 +0000527// CallGraphSCC Implementation
528//===----------------------------------------------------------------------===//
529
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000530/// This informs the SCC and the pass manager that the specified
Chris Lattner5518b812010-04-16 22:59:24 +0000531/// Old node has been deleted, and New is to be used in its place.
532void CallGraphSCC::ReplaceNode(CallGraphNode *Old, CallGraphNode *New) {
533 assert(Old != New && "Should not replace node with self");
534 for (unsigned i = 0; ; ++i) {
535 assert(i != Nodes.size() && "Node not in SCC");
536 if (Nodes[i] != Old) continue;
537 Nodes[i] = New;
538 break;
539 }
Chris Lattnerde023a32010-04-16 23:04:30 +0000540
541 // Update the active scc_iterator so that it doesn't contain dangling
542 // pointers to the old CallGraphNode.
543 scc_iterator<CallGraph*> *CGI = (scc_iterator<CallGraph*>*)Context;
544 CGI->ReplaceNode(Old, New);
Chris Lattner5518b812010-04-16 22:59:24 +0000545}
Chris Lattner4422d312010-04-16 22:42:17 +0000546
Chris Lattner4422d312010-04-16 22:42:17 +0000547//===----------------------------------------------------------------------===//
Chris Lattner6d1208f2010-04-16 21:43:55 +0000548// CallGraphSCCPass Implementation
549//===----------------------------------------------------------------------===//
David Greene9b063df2010-04-02 23:17:14 +0000550
Devang Patel020f4f22007-01-23 21:55:17 +0000551/// Assign pass manager to manage this pass.
Devang Patel1f8200b2007-01-23 21:52:35 +0000552void CallGraphSCCPass::assignPassManager(PMStack &PMS,
Anton Korobeynikovfb801512007-04-16 18:10:23 +0000553 PassManagerType PreferredType) {
Devang Patel1f8200b2007-01-23 21:52:35 +0000554 // Find CGPassManager
Duncan Sands60f28bf2007-07-19 09:42:01 +0000555 while (!PMS.empty() &&
556 PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)
557 PMS.pop();
Devang Patel1f8200b2007-01-23 21:52:35 +0000558
Chris Lattner9efd4fc2010-01-22 05:37:10 +0000559 assert(!PMS.empty() && "Unable to handle Call Graph Pass");
560 CGPassManager *CGP;
561
562 if (PMS.top()->getPassManagerType() == PMT_CallGraphPassManager)
563 CGP = (CGPassManager*)PMS.top();
564 else {
565 // Create new Call Graph SCC Pass Manager if it does not exist.
566 assert(!PMS.empty() && "Unable to create Call Graph Pass Manager");
Devang Patel1f8200b2007-01-23 21:52:35 +0000567 PMDataManager *PMD = PMS.top();
568
569 // [1] Create new Call Graph Pass Manager
Andrew Trick08966212011-08-29 17:07:00 +0000570 CGP = new CGPassManager();
Devang Patel1f8200b2007-01-23 21:52:35 +0000571
572 // [2] Set up new manager's top level manager
573 PMTopLevelManager *TPM = PMD->getTopLevelManager();
574 TPM->addIndirectPassManager(CGP);
575
576 // [3] Assign manager to manage this new manager. This may create
577 // and push new managers into PMS
Chris Lattner9efd4fc2010-01-22 05:37:10 +0000578 Pass *P = CGP;
Devang Patel703de8f2007-06-21 22:29:02 +0000579 TPM->schedulePass(P);
Devang Patel1f8200b2007-01-23 21:52:35 +0000580
581 // [4] Push new manager into PMS
582 PMS.push(CGP);
583 }
584
585 CGP->add(this);
586}
587
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000588/// For this class, we declare that we require and preserve the call graph.
589/// If the derived class implements this method, it should
Chris Lattnerf7e95942003-08-31 01:54:59 +0000590/// always explicitly call the implementation here.
591void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth6378cf52013-11-26 04:19:30 +0000592 AU.addRequired<CallGraphWrapperPass>();
593 AU.addPreserved<CallGraphWrapperPass>();
Chris Lattnerf7e95942003-08-31 01:54:59 +0000594}
Chris Lattner6d1208f2010-04-16 21:43:55 +0000595
Chris Lattner6d1208f2010-04-16 21:43:55 +0000596//===----------------------------------------------------------------------===//
597// PrintCallGraphPass Implementation
598//===----------------------------------------------------------------------===//
599
600namespace {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000601
Chris Lattner6d1208f2010-04-16 21:43:55 +0000602 /// PrintCallGraphPass - Print a Module corresponding to a call graph.
603 ///
604 class PrintCallGraphPass : public CallGraphSCCPass {
605 std::string Banner;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000606 raw_ostream &OS; // raw_ostream to print on.
Chris Lattner6d1208f2010-04-16 21:43:55 +0000607
608 public:
609 static char ID;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000610
611 PrintCallGraphPass(const std::string &B, raw_ostream &OS)
612 : CallGraphSCCPass(ID), Banner(B), OS(OS) {}
Craig Toppere9ba7592014-03-05 07:30:04 +0000613
614 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattner6d1208f2010-04-16 21:43:55 +0000615 AU.setPreservesAll();
616 }
Craig Toppere9ba7592014-03-05 07:30:04 +0000617
618 bool runOnSCC(CallGraphSCC &SCC) override {
Yaron Keren7d463922017-06-12 02:18:50 +0000619 bool BannerPrinted = false;
Mehdi Amini062b3fe2017-01-18 21:37:11 +0000620 auto PrintBannerOnce = [&] () {
Mehdi Amini062b3fe2017-01-18 21:37:11 +0000621 if (BannerPrinted)
622 return;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000623 OS << Banner;
Mehdi Amini062b3fe2017-01-18 21:37:11 +0000624 BannerPrinted = true;
625 };
Sanjay Patelc6012542015-03-10 03:26:39 +0000626 for (CallGraphNode *CGN : SCC) {
Yaron Keren7d463922017-06-12 02:18:50 +0000627 if (Function *F = CGN->getFunction()) {
628 if (!F->isDeclaration() && isFunctionInPrintList(F->getName())) {
Mehdi Amini062b3fe2017-01-18 21:37:11 +0000629 PrintBannerOnce();
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000630 F->print(OS);
Mehdi Amini062b3fe2017-01-18 21:37:11 +0000631 }
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000632 } else if (isFunctionInPrintList("*")) {
Mehdi Amini062b3fe2017-01-18 21:37:11 +0000633 PrintBannerOnce();
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000634 OS << "\nPrinting <null> Function\n";
Mehdi Amini062b3fe2017-01-18 21:37:11 +0000635 }
Richard Trieua23043c2014-06-09 22:53:16 +0000636 }
Chris Lattner6d1208f2010-04-16 21:43:55 +0000637 return false;
638 }
Yaron Keren1de47922017-03-10 07:09:20 +0000639
640 StringRef getPassName() const override { return "Print CallGraph IR"; }
Chris Lattner6d1208f2010-04-16 21:43:55 +0000641 };
642
643} // end anonymous namespace.
644
645char PrintCallGraphPass::ID = 0;
646
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000647Pass *CallGraphSCCPass::createPrinterPass(raw_ostream &OS,
Chris Lattner6d1208f2010-04-16 21:43:55 +0000648 const std::string &Banner) const {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000649 return new PrintCallGraphPass(Banner, OS);
Chris Lattner6d1208f2010-04-16 21:43:55 +0000650}
651
Andrew Kayloraa641a52016-04-22 22:06:11 +0000652bool CallGraphSCCPass::skipSCC(CallGraphSCC &SCC) const {
653 return !SCC.getCallGraph().getModule()
654 .getContext()
Fedor Sergeev98014e42018-03-27 16:57:20 +0000655 .getOptPassGate()
Andrew Kayloraa641a52016-04-22 22:06:11 +0000656 .shouldRunPass(this, SCC);
657}
Mehdi Aminibbacddf2016-06-10 16:19:46 +0000658
659char DummyCGSCCPass::ID = 0;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000660
Mehdi Aminibbacddf2016-06-10 16:19:46 +0000661INITIALIZE_PASS(DummyCGSCCPass, "DummyCGSCCPass", "DummyCGSCCPass", false,
662 false)