15ca98fd9SDimitry Andric //===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===//
25ca98fd9SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ca98fd9SDimitry Andric //
75ca98fd9SDimitry Andric //===----------------------------------------------------------------------===//
85ca98fd9SDimitry Andric
95ca98fd9SDimitry Andric #include "llvm/Analysis/CGSCCPassManager.h"
10044eb2f6SDimitry Andric #include "llvm/ADT/ArrayRef.h"
11145449b1SDimitry Andric #include "llvm/ADT/PriorityWorklist.h"
12044eb2f6SDimitry Andric #include "llvm/ADT/STLExtras.h"
13044eb2f6SDimitry Andric #include "llvm/ADT/SetVector.h"
14044eb2f6SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
15044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
16044eb2f6SDimitry Andric #include "llvm/ADT/iterator_range.h"
17044eb2f6SDimitry Andric #include "llvm/Analysis/LazyCallGraph.h"
18044eb2f6SDimitry Andric #include "llvm/IR/Constant.h"
19b915e9e0SDimitry Andric #include "llvm/IR/InstIterator.h"
20044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
21044eb2f6SDimitry Andric #include "llvm/IR/PassManager.h"
22cfca06d7SDimitry Andric #include "llvm/IR/PassManagerImpl.h"
23b60736ecSDimitry Andric #include "llvm/IR/ValueHandle.h"
24044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
25b60736ecSDimitry Andric #include "llvm/Support/CommandLine.h"
26044eb2f6SDimitry Andric #include "llvm/Support/Debug.h"
27b60736ecSDimitry Andric #include "llvm/Support/ErrorHandling.h"
28cfca06d7SDimitry Andric #include "llvm/Support/TimeProfiler.h"
29b60736ecSDimitry Andric #include "llvm/Support/raw_ostream.h"
30044eb2f6SDimitry Andric #include <cassert>
31044eb2f6SDimitry Andric #include <iterator>
32e3b55780SDimitry Andric #include <optional>
33044eb2f6SDimitry Andric
34044eb2f6SDimitry Andric #define DEBUG_TYPE "cgscc"
355ca98fd9SDimitry Andric
365ca98fd9SDimitry Andric using namespace llvm;
375ca98fd9SDimitry Andric
38eb11fae6SDimitry Andric // Explicit template instantiations and specialization definitions for core
39b915e9e0SDimitry Andric // template typedefs.
4001095a5dSDimitry Andric namespace llvm {
41b60736ecSDimitry Andric static cl::opt<bool> AbortOnMaxDevirtIterationsReached(
42b60736ecSDimitry Andric "abort-on-max-devirt-iterations-reached",
43b60736ecSDimitry Andric cl::desc("Abort when the max iterations for devirtualization CGSCC repeat "
44b60736ecSDimitry Andric "pass is reached"));
45b60736ecSDimitry Andric
46c0981da4SDimitry Andric AnalysisKey ShouldNotRunFunctionPassesAnalysis::Key;
47c0981da4SDimitry Andric
48b915e9e0SDimitry Andric // Explicit instantiations for the core proxy templates.
49b915e9e0SDimitry Andric template class AllAnalysesOn<LazyCallGraph::SCC>;
50b915e9e0SDimitry Andric template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
51b915e9e0SDimitry Andric template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
52b915e9e0SDimitry Andric LazyCallGraph &, CGSCCUpdateResult &>;
5301095a5dSDimitry Andric template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
5401095a5dSDimitry Andric template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
55b915e9e0SDimitry Andric LazyCallGraph::SCC, LazyCallGraph &>;
5601095a5dSDimitry Andric template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
57b915e9e0SDimitry Andric
58b915e9e0SDimitry Andric /// Explicitly specialize the pass manager run method to handle call graph
59b915e9e0SDimitry Andric /// updates.
60b915e9e0SDimitry Andric template <>
61b915e9e0SDimitry Andric PreservedAnalyses
62b915e9e0SDimitry Andric PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
run(LazyCallGraph::SCC & InitialC,CGSCCAnalysisManager & AM,LazyCallGraph & G,CGSCCUpdateResult & UR)63b915e9e0SDimitry Andric CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
64b915e9e0SDimitry Andric CGSCCAnalysisManager &AM,
65b915e9e0SDimitry Andric LazyCallGraph &G, CGSCCUpdateResult &UR) {
66d8e91e46SDimitry Andric // Request PassInstrumentation from analysis manager, will use it to run
67d8e91e46SDimitry Andric // instrumenting callbacks for the passes later.
68d8e91e46SDimitry Andric PassInstrumentation PI =
69d8e91e46SDimitry Andric AM.getResult<PassInstrumentationAnalysis>(InitialC, G);
70d8e91e46SDimitry Andric
71b915e9e0SDimitry Andric PreservedAnalyses PA = PreservedAnalyses::all();
72b915e9e0SDimitry Andric
73b915e9e0SDimitry Andric // The SCC may be refined while we are running passes over it, so set up
74b915e9e0SDimitry Andric // a pointer that we can update.
75b915e9e0SDimitry Andric LazyCallGraph::SCC *C = &InitialC;
76b915e9e0SDimitry Andric
77cfca06d7SDimitry Andric // Get Function analysis manager from its proxy.
78cfca06d7SDimitry Andric FunctionAnalysisManager &FAM =
79cfca06d7SDimitry Andric AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*C)->getManager();
80b915e9e0SDimitry Andric
81cfca06d7SDimitry Andric for (auto &Pass : Passes) {
82d8e91e46SDimitry Andric // Check the PassInstrumentation's BeforePass callbacks before running the
83d8e91e46SDimitry Andric // pass, skip its execution completely if asked to (callback returns false).
84d8e91e46SDimitry Andric if (!PI.runBeforePass(*Pass, *C))
85d8e91e46SDimitry Andric continue;
86d8e91e46SDimitry Andric
87e3b55780SDimitry Andric PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR);
88b915e9e0SDimitry Andric
89b915e9e0SDimitry Andric // Update the SCC if necessary.
90b915e9e0SDimitry Andric C = UR.UpdatedC ? UR.UpdatedC : C;
91cfca06d7SDimitry Andric if (UR.UpdatedC) {
92cfca06d7SDimitry Andric // If C is updated, also create a proxy and update FAM inside the result.
93cfca06d7SDimitry Andric auto *ResultFAMCP =
94cfca06d7SDimitry Andric &AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G);
95cfca06d7SDimitry Andric ResultFAMCP->updateFAM(FAM);
96cfca06d7SDimitry Andric }
97b915e9e0SDimitry Andric
98e3b55780SDimitry Andric // Intersect the final preserved analyses to compute the aggregate
99e3b55780SDimitry Andric // preserved set for this pass manager.
100e3b55780SDimitry Andric PA.intersect(PassPA);
101e3b55780SDimitry Andric
102044eb2f6SDimitry Andric // If the CGSCC pass wasn't able to provide a valid updated SCC, the
103044eb2f6SDimitry Andric // current SCC may simply need to be skipped if invalid.
104044eb2f6SDimitry Andric if (UR.InvalidatedSCCs.count(C)) {
1057fa27ce4SDimitry Andric PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass, PassPA);
106eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
107044eb2f6SDimitry Andric break;
108044eb2f6SDimitry Andric }
109e3b55780SDimitry Andric
110b915e9e0SDimitry Andric // Check that we didn't miss any update scenario.
111b915e9e0SDimitry Andric assert(C->begin() != C->end() && "Cannot have an empty SCC!");
112b915e9e0SDimitry Andric
113b915e9e0SDimitry Andric // Update the analysis manager as each pass runs and potentially
114b915e9e0SDimitry Andric // invalidates analyses.
115b915e9e0SDimitry Andric AM.invalidate(*C, PassPA);
1167fa27ce4SDimitry Andric
1177fa27ce4SDimitry Andric PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C, PassPA);
118b915e9e0SDimitry Andric }
119b915e9e0SDimitry Andric
120e6d15924SDimitry Andric // Before we mark all of *this* SCC's analyses as preserved below, intersect
121e6d15924SDimitry Andric // this with the cross-SCC preserved analysis set. This is used to allow
122e6d15924SDimitry Andric // CGSCC passes to mutate ancestor SCCs and still trigger proper invalidation
123e6d15924SDimitry Andric // for them.
124e6d15924SDimitry Andric UR.CrossSCCPA.intersect(PA);
125e6d15924SDimitry Andric
126eb11fae6SDimitry Andric // Invalidation was handled after each pass in the above loop for the current
127b915e9e0SDimitry Andric // SCC. Therefore, the remaining analysis results in the AnalysisManager are
128b915e9e0SDimitry Andric // preserved. We mark this with a set so that we don't need to inspect each
129b915e9e0SDimitry Andric // one individually.
130b915e9e0SDimitry Andric PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>();
131b915e9e0SDimitry Andric
132b915e9e0SDimitry Andric return PA;
133b915e9e0SDimitry Andric }
134b915e9e0SDimitry Andric
135b60736ecSDimitry Andric PreservedAnalyses
run(Module & M,ModuleAnalysisManager & AM)136b60736ecSDimitry Andric ModuleToPostOrderCGSCCPassAdaptor::run(Module &M, ModuleAnalysisManager &AM) {
137b60736ecSDimitry Andric // Setup the CGSCC analysis manager from its proxy.
138b60736ecSDimitry Andric CGSCCAnalysisManager &CGAM =
139b60736ecSDimitry Andric AM.getResult<CGSCCAnalysisManagerModuleProxy>(M).getManager();
140b60736ecSDimitry Andric
141b60736ecSDimitry Andric // Get the call graph for this module.
142b60736ecSDimitry Andric LazyCallGraph &CG = AM.getResult<LazyCallGraphAnalysis>(M);
143b60736ecSDimitry Andric
144b60736ecSDimitry Andric // Get Function analysis manager from its proxy.
145b60736ecSDimitry Andric FunctionAnalysisManager &FAM =
146b60736ecSDimitry Andric AM.getCachedResult<FunctionAnalysisManagerModuleProxy>(M)->getManager();
147b60736ecSDimitry Andric
148b60736ecSDimitry Andric // We keep worklists to allow us to push more work onto the pass manager as
149b60736ecSDimitry Andric // the passes are run.
150b60736ecSDimitry Andric SmallPriorityWorklist<LazyCallGraph::RefSCC *, 1> RCWorklist;
151b60736ecSDimitry Andric SmallPriorityWorklist<LazyCallGraph::SCC *, 1> CWorklist;
152b60736ecSDimitry Andric
153ac9a064cSDimitry Andric // Keep sets for invalidated SCCs that should be skipped when
154b60736ecSDimitry Andric // iterating off the worklists.
155b60736ecSDimitry Andric SmallPtrSet<LazyCallGraph::SCC *, 4> InvalidSCCSet;
156b60736ecSDimitry Andric
157b60736ecSDimitry Andric SmallDenseSet<std::pair<LazyCallGraph::Node *, LazyCallGraph::SCC *>, 4>
158b60736ecSDimitry Andric InlinedInternalEdges;
159b60736ecSDimitry Andric
160ac9a064cSDimitry Andric SmallVector<Function *, 4> DeadFunctions;
161ac9a064cSDimitry Andric
162ac9a064cSDimitry Andric CGSCCUpdateResult UR = {CWorklist,
163ac9a064cSDimitry Andric InvalidSCCSet,
164ac9a064cSDimitry Andric nullptr,
165ac9a064cSDimitry Andric PreservedAnalyses::all(),
166ac9a064cSDimitry Andric InlinedInternalEdges,
167ac9a064cSDimitry Andric DeadFunctions,
168ac9a064cSDimitry Andric {}};
169b60736ecSDimitry Andric
170b60736ecSDimitry Andric // Request PassInstrumentation from analysis manager, will use it to run
171b60736ecSDimitry Andric // instrumenting callbacks for the passes later.
172b60736ecSDimitry Andric PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(M);
173b60736ecSDimitry Andric
174b60736ecSDimitry Andric PreservedAnalyses PA = PreservedAnalyses::all();
175b60736ecSDimitry Andric CG.buildRefSCCs();
176145449b1SDimitry Andric for (LazyCallGraph::RefSCC &RC :
177145449b1SDimitry Andric llvm::make_early_inc_range(CG.postorder_ref_sccs())) {
178b60736ecSDimitry Andric assert(RCWorklist.empty() &&
179b60736ecSDimitry Andric "Should always start with an empty RefSCC worklist");
180b60736ecSDimitry Andric // The postorder_ref_sccs range we are walking is lazily constructed, so
181b60736ecSDimitry Andric // we only push the first one onto the worklist. The worklist allows us
182b60736ecSDimitry Andric // to capture *new* RefSCCs created during transformations.
183b60736ecSDimitry Andric //
184b60736ecSDimitry Andric // We really want to form RefSCCs lazily because that makes them cheaper
185b60736ecSDimitry Andric // to update as the program is simplified and allows us to have greater
186b60736ecSDimitry Andric // cache locality as forming a RefSCC touches all the parts of all the
187b60736ecSDimitry Andric // functions within that RefSCC.
188b60736ecSDimitry Andric //
189b60736ecSDimitry Andric // We also eagerly increment the iterator to the next position because
190b60736ecSDimitry Andric // the CGSCC passes below may delete the current RefSCC.
191145449b1SDimitry Andric RCWorklist.insert(&RC);
192b60736ecSDimitry Andric
193b60736ecSDimitry Andric do {
194b60736ecSDimitry Andric LazyCallGraph::RefSCC *RC = RCWorklist.pop_back_val();
195b60736ecSDimitry Andric assert(CWorklist.empty() &&
196b60736ecSDimitry Andric "Should always start with an empty SCC worklist");
197b60736ecSDimitry Andric
198b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Running an SCC pass across the RefSCC: " << *RC
199b60736ecSDimitry Andric << "\n");
200b60736ecSDimitry Andric
201b60736ecSDimitry Andric // The top of the worklist may *also* be the same SCC we just ran over
202b60736ecSDimitry Andric // (and invalidated for). Keep track of that last SCC we processed due
203b60736ecSDimitry Andric // to SCC update to avoid redundant processing when an SCC is both just
204b60736ecSDimitry Andric // updated itself and at the top of the worklist.
205b60736ecSDimitry Andric LazyCallGraph::SCC *LastUpdatedC = nullptr;
206b60736ecSDimitry Andric
207b60736ecSDimitry Andric // Push the initial SCCs in reverse post-order as we'll pop off the
208b60736ecSDimitry Andric // back and so see this in post-order.
209b60736ecSDimitry Andric for (LazyCallGraph::SCC &C : llvm::reverse(*RC))
210b60736ecSDimitry Andric CWorklist.insert(&C);
211b60736ecSDimitry Andric
212b60736ecSDimitry Andric do {
213b60736ecSDimitry Andric LazyCallGraph::SCC *C = CWorklist.pop_back_val();
214b60736ecSDimitry Andric // Due to call graph mutations, we may have invalid SCCs or SCCs from
215b60736ecSDimitry Andric // other RefSCCs in the worklist. The invalid ones are dead and the
216b60736ecSDimitry Andric // other RefSCCs should be queued above, so we just need to skip both
217b60736ecSDimitry Andric // scenarios here.
218b60736ecSDimitry Andric if (InvalidSCCSet.count(C)) {
219b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Skipping an invalid SCC...\n");
220b60736ecSDimitry Andric continue;
221b60736ecSDimitry Andric }
222b60736ecSDimitry Andric if (LastUpdatedC == C) {
223b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Skipping redundant run on SCC: " << *C << "\n");
224b60736ecSDimitry Andric continue;
225b60736ecSDimitry Andric }
226145449b1SDimitry Andric // We used to also check if the current SCC is part of the current
227145449b1SDimitry Andric // RefSCC and bail if it wasn't, since it should be in RCWorklist.
228145449b1SDimitry Andric // However, this can cause compile time explosions in some cases on
229145449b1SDimitry Andric // modules with a huge RefSCC. If a non-trivial amount of SCCs in the
230145449b1SDimitry Andric // huge RefSCC can become their own child RefSCC, we create one child
231145449b1SDimitry Andric // RefSCC, bail on the current RefSCC, visit the child RefSCC, revisit
232145449b1SDimitry Andric // the huge RefSCC, and repeat. By visiting all SCCs in the original
233145449b1SDimitry Andric // RefSCC we create all the child RefSCCs in one pass of the RefSCC,
234145449b1SDimitry Andric // rather one pass of the RefSCC creating one child RefSCC at a time.
235b60736ecSDimitry Andric
236b60736ecSDimitry Andric // Ensure we can proxy analysis updates from the CGSCC analysis manager
237b1c73532SDimitry Andric // into the Function analysis manager by getting a proxy here.
238b60736ecSDimitry Andric // This also needs to update the FunctionAnalysisManager, as this may be
239b60736ecSDimitry Andric // the first time we see this SCC.
240b60736ecSDimitry Andric CGAM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, CG).updateFAM(
241b60736ecSDimitry Andric FAM);
242b60736ecSDimitry Andric
243b60736ecSDimitry Andric // Each time we visit a new SCC pulled off the worklist,
244b60736ecSDimitry Andric // a transformation of a child SCC may have also modified this parent
245b60736ecSDimitry Andric // and invalidated analyses. So we invalidate using the update record's
246b60736ecSDimitry Andric // cross-SCC preserved set. This preserved set is intersected by any
247b60736ecSDimitry Andric // CGSCC pass that handles invalidation (primarily pass managers) prior
248b60736ecSDimitry Andric // to marking its SCC as preserved. That lets us track everything that
249b60736ecSDimitry Andric // might need invalidation across SCCs without excessive invalidations
250b60736ecSDimitry Andric // on a single SCC.
251b60736ecSDimitry Andric //
252b60736ecSDimitry Andric // This essentially allows SCC passes to freely invalidate analyses
253b60736ecSDimitry Andric // of any ancestor SCC. If this becomes detrimental to successfully
254b60736ecSDimitry Andric // caching analyses, we could force each SCC pass to manually
255b60736ecSDimitry Andric // invalidate the analyses for any SCCs other than themselves which
256b60736ecSDimitry Andric // are mutated. However, that seems to lose the robustness of the
257b60736ecSDimitry Andric // pass-manager driven invalidation scheme.
258b60736ecSDimitry Andric CGAM.invalidate(*C, UR.CrossSCCPA);
259b60736ecSDimitry Andric
260b60736ecSDimitry Andric do {
261b60736ecSDimitry Andric // Check that we didn't miss any update scenario.
262b60736ecSDimitry Andric assert(!InvalidSCCSet.count(C) && "Processing an invalid SCC!");
263b60736ecSDimitry Andric assert(C->begin() != C->end() && "Cannot have an empty SCC!");
264b60736ecSDimitry Andric
265b60736ecSDimitry Andric LastUpdatedC = UR.UpdatedC;
266b60736ecSDimitry Andric UR.UpdatedC = nullptr;
267b60736ecSDimitry Andric
268b60736ecSDimitry Andric // Check the PassInstrumentation's BeforePass callbacks before
269b60736ecSDimitry Andric // running the pass, skip its execution completely if asked to
270b60736ecSDimitry Andric // (callback returns false).
271b60736ecSDimitry Andric if (!PI.runBeforePass<LazyCallGraph::SCC>(*Pass, *C))
272b60736ecSDimitry Andric continue;
273b60736ecSDimitry Andric
274e3b55780SDimitry Andric PreservedAnalyses PassPA = Pass->run(*C, CGAM, CG, UR);
275b60736ecSDimitry Andric
276b60736ecSDimitry Andric // Update the SCC and RefSCC if necessary.
277b60736ecSDimitry Andric C = UR.UpdatedC ? UR.UpdatedC : C;
278b60736ecSDimitry Andric
279b60736ecSDimitry Andric if (UR.UpdatedC) {
280b60736ecSDimitry Andric // If we're updating the SCC, also update the FAM inside the proxy's
281b60736ecSDimitry Andric // result.
282b60736ecSDimitry Andric CGAM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, CG).updateFAM(
283b60736ecSDimitry Andric FAM);
284b60736ecSDimitry Andric }
285b60736ecSDimitry Andric
286e3b55780SDimitry Andric // Intersect with the cross-SCC preserved set to capture any
287e3b55780SDimitry Andric // cross-SCC invalidation.
288e3b55780SDimitry Andric UR.CrossSCCPA.intersect(PassPA);
289e3b55780SDimitry Andric // Intersect the preserved set so that invalidation of module
290e3b55780SDimitry Andric // analyses will eventually occur when the module pass completes.
291e3b55780SDimitry Andric PA.intersect(PassPA);
292e3b55780SDimitry Andric
293b60736ecSDimitry Andric // If the CGSCC pass wasn't able to provide a valid updated SCC,
294b60736ecSDimitry Andric // the current SCC may simply need to be skipped if invalid.
295b60736ecSDimitry Andric if (UR.InvalidatedSCCs.count(C)) {
2967fa27ce4SDimitry Andric PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass, PassPA);
297b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
298b60736ecSDimitry Andric break;
299b60736ecSDimitry Andric }
300e3b55780SDimitry Andric
301b60736ecSDimitry Andric // Check that we didn't miss any update scenario.
302b60736ecSDimitry Andric assert(C->begin() != C->end() && "Cannot have an empty SCC!");
303b60736ecSDimitry Andric
304b60736ecSDimitry Andric // We handle invalidating the CGSCC analysis manager's information
305b60736ecSDimitry Andric // for the (potentially updated) SCC here. Note that any other SCCs
306b60736ecSDimitry Andric // whose structure has changed should have been invalidated by
307b60736ecSDimitry Andric // whatever was updating the call graph. This SCC gets invalidated
308b60736ecSDimitry Andric // late as it contains the nodes that were actively being
309b60736ecSDimitry Andric // processed.
310b60736ecSDimitry Andric CGAM.invalidate(*C, PassPA);
311b60736ecSDimitry Andric
3127fa27ce4SDimitry Andric PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C, PassPA);
3137fa27ce4SDimitry Andric
314b60736ecSDimitry Andric // The pass may have restructured the call graph and refined the
315b60736ecSDimitry Andric // current SCC and/or RefSCC. We need to update our current SCC and
316b60736ecSDimitry Andric // RefSCC pointers to follow these. Also, when the current SCC is
317b60736ecSDimitry Andric // refined, re-run the SCC pass over the newly refined SCC in order
318b60736ecSDimitry Andric // to observe the most precise SCC model available. This inherently
319b60736ecSDimitry Andric // cannot cycle excessively as it only happens when we split SCCs
320b60736ecSDimitry Andric // apart, at most converging on a DAG of single nodes.
321b60736ecSDimitry Andric // FIXME: If we ever start having RefSCC passes, we'll want to
322b60736ecSDimitry Andric // iterate there too.
323b60736ecSDimitry Andric if (UR.UpdatedC)
324b60736ecSDimitry Andric LLVM_DEBUG(dbgs()
325b60736ecSDimitry Andric << "Re-running SCC passes after a refinement of the "
326b60736ecSDimitry Andric "current SCC: "
327b60736ecSDimitry Andric << *UR.UpdatedC << "\n");
328b60736ecSDimitry Andric
329b60736ecSDimitry Andric // Note that both `C` and `RC` may at this point refer to deleted,
330b60736ecSDimitry Andric // invalid SCC and RefSCCs respectively. But we will short circuit
331b60736ecSDimitry Andric // the processing when we check them in the loop above.
332b60736ecSDimitry Andric } while (UR.UpdatedC);
333b60736ecSDimitry Andric } while (!CWorklist.empty());
334b60736ecSDimitry Andric
335b60736ecSDimitry Andric // We only need to keep internal inlined edge information within
336b60736ecSDimitry Andric // a RefSCC, clear it to save on space and let the next time we visit
337b60736ecSDimitry Andric // any of these functions have a fresh start.
338b60736ecSDimitry Andric InlinedInternalEdges.clear();
339b60736ecSDimitry Andric } while (!RCWorklist.empty());
340b60736ecSDimitry Andric }
341b60736ecSDimitry Andric
342ac9a064cSDimitry Andric CG.removeDeadFunctions(DeadFunctions);
343ac9a064cSDimitry Andric for (Function *DeadF : DeadFunctions)
344ac9a064cSDimitry Andric DeadF->eraseFromParent();
345ac9a064cSDimitry Andric
346ac9a064cSDimitry Andric #if defined(EXPENSIVE_CHECKS)
347ac9a064cSDimitry Andric // Verify that the call graph is still valid.
348ac9a064cSDimitry Andric CG.verify();
349ac9a064cSDimitry Andric #endif
350ac9a064cSDimitry Andric
351b60736ecSDimitry Andric // By definition we preserve the call garph, all SCC analyses, and the
352b60736ecSDimitry Andric // analysis proxies by handling them above and in any nested pass managers.
353b60736ecSDimitry Andric PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>();
354b60736ecSDimitry Andric PA.preserve<LazyCallGraphAnalysis>();
355b60736ecSDimitry Andric PA.preserve<CGSCCAnalysisManagerModuleProxy>();
356b60736ecSDimitry Andric PA.preserve<FunctionAnalysisManagerModuleProxy>();
357b60736ecSDimitry Andric return PA;
358b60736ecSDimitry Andric }
359b60736ecSDimitry Andric
run(LazyCallGraph::SCC & InitialC,CGSCCAnalysisManager & AM,LazyCallGraph & CG,CGSCCUpdateResult & UR)360b60736ecSDimitry Andric PreservedAnalyses DevirtSCCRepeatedPass::run(LazyCallGraph::SCC &InitialC,
361b60736ecSDimitry Andric CGSCCAnalysisManager &AM,
362b60736ecSDimitry Andric LazyCallGraph &CG,
363b60736ecSDimitry Andric CGSCCUpdateResult &UR) {
364b60736ecSDimitry Andric PreservedAnalyses PA = PreservedAnalyses::all();
365b60736ecSDimitry Andric PassInstrumentation PI =
366b60736ecSDimitry Andric AM.getResult<PassInstrumentationAnalysis>(InitialC, CG);
367b60736ecSDimitry Andric
368b60736ecSDimitry Andric // The SCC may be refined while we are running passes over it, so set up
369b60736ecSDimitry Andric // a pointer that we can update.
370b60736ecSDimitry Andric LazyCallGraph::SCC *C = &InitialC;
371b60736ecSDimitry Andric
372b60736ecSDimitry Andric // Struct to track the counts of direct and indirect calls in each function
373b60736ecSDimitry Andric // of the SCC.
374b60736ecSDimitry Andric struct CallCount {
375b60736ecSDimitry Andric int Direct;
376b60736ecSDimitry Andric int Indirect;
377b60736ecSDimitry Andric };
378b60736ecSDimitry Andric
379b60736ecSDimitry Andric // Put value handles on all of the indirect calls and return the number of
380b60736ecSDimitry Andric // direct calls for each function in the SCC.
381b60736ecSDimitry Andric auto ScanSCC = [](LazyCallGraph::SCC &C,
382b60736ecSDimitry Andric SmallMapVector<Value *, WeakTrackingVH, 16> &CallHandles) {
383b60736ecSDimitry Andric assert(CallHandles.empty() && "Must start with a clear set of handles.");
384b60736ecSDimitry Andric
385b60736ecSDimitry Andric SmallDenseMap<Function *, CallCount> CallCounts;
386b60736ecSDimitry Andric CallCount CountLocal = {0, 0};
387b60736ecSDimitry Andric for (LazyCallGraph::Node &N : C) {
388b60736ecSDimitry Andric CallCount &Count =
389b60736ecSDimitry Andric CallCounts.insert(std::make_pair(&N.getFunction(), CountLocal))
390b60736ecSDimitry Andric .first->second;
391b60736ecSDimitry Andric for (Instruction &I : instructions(N.getFunction()))
392b60736ecSDimitry Andric if (auto *CB = dyn_cast<CallBase>(&I)) {
393b60736ecSDimitry Andric if (CB->getCalledFunction()) {
394b60736ecSDimitry Andric ++Count.Direct;
395b60736ecSDimitry Andric } else {
396b60736ecSDimitry Andric ++Count.Indirect;
397b60736ecSDimitry Andric CallHandles.insert({CB, WeakTrackingVH(CB)});
398b60736ecSDimitry Andric }
399b60736ecSDimitry Andric }
400b60736ecSDimitry Andric }
401b60736ecSDimitry Andric
402b60736ecSDimitry Andric return CallCounts;
403b60736ecSDimitry Andric };
404b60736ecSDimitry Andric
405b60736ecSDimitry Andric UR.IndirectVHs.clear();
406b60736ecSDimitry Andric // Populate the initial call handles and get the initial call counts.
407b60736ecSDimitry Andric auto CallCounts = ScanSCC(*C, UR.IndirectVHs);
408b60736ecSDimitry Andric
409b60736ecSDimitry Andric for (int Iteration = 0;; ++Iteration) {
410b60736ecSDimitry Andric if (!PI.runBeforePass<LazyCallGraph::SCC>(*Pass, *C))
411b60736ecSDimitry Andric continue;
412b60736ecSDimitry Andric
413b60736ecSDimitry Andric PreservedAnalyses PassPA = Pass->run(*C, AM, CG, UR);
414b60736ecSDimitry Andric
415e3b55780SDimitry Andric PA.intersect(PassPA);
416e3b55780SDimitry Andric
4177fa27ce4SDimitry Andric // If the CGSCC pass wasn't able to provide a valid updated SCC, the
4187fa27ce4SDimitry Andric // current SCC may simply need to be skipped if invalid.
4197fa27ce4SDimitry Andric if (UR.InvalidatedSCCs.count(C)) {
4207fa27ce4SDimitry Andric PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass, PassPA);
4217fa27ce4SDimitry Andric LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
4227fa27ce4SDimitry Andric break;
4237fa27ce4SDimitry Andric }
4247fa27ce4SDimitry Andric
4257fa27ce4SDimitry Andric // Update the analysis manager with each run and intersect the total set
4267fa27ce4SDimitry Andric // of preserved analyses so we're ready to iterate.
4277fa27ce4SDimitry Andric AM.invalidate(*C, PassPA);
4287fa27ce4SDimitry Andric
4297fa27ce4SDimitry Andric PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C, PassPA);
4307fa27ce4SDimitry Andric
431b60736ecSDimitry Andric // If the SCC structure has changed, bail immediately and let the outer
432b60736ecSDimitry Andric // CGSCC layer handle any iteration to reflect the refined structure.
433e3b55780SDimitry Andric if (UR.UpdatedC && UR.UpdatedC != C)
434b60736ecSDimitry Andric break;
435b60736ecSDimitry Andric
436b60736ecSDimitry Andric assert(C->begin() != C->end() && "Cannot have an empty SCC!");
437b60736ecSDimitry Andric
438b60736ecSDimitry Andric // Check whether any of the handles were devirtualized.
439b60736ecSDimitry Andric bool Devirt = llvm::any_of(UR.IndirectVHs, [](auto &P) -> bool {
440b60736ecSDimitry Andric if (P.second) {
441b60736ecSDimitry Andric if (CallBase *CB = dyn_cast<CallBase>(P.second)) {
442b60736ecSDimitry Andric if (CB->getCalledFunction()) {
443b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Found devirtualized call: " << *CB << "\n");
444b60736ecSDimitry Andric return true;
445b60736ecSDimitry Andric }
446b60736ecSDimitry Andric }
447b60736ecSDimitry Andric }
448b60736ecSDimitry Andric return false;
449b60736ecSDimitry Andric });
450b60736ecSDimitry Andric
451b60736ecSDimitry Andric // Rescan to build up a new set of handles and count how many direct
452b60736ecSDimitry Andric // calls remain. If we decide to iterate, this also sets up the input to
453b60736ecSDimitry Andric // the next iteration.
454b60736ecSDimitry Andric UR.IndirectVHs.clear();
455b60736ecSDimitry Andric auto NewCallCounts = ScanSCC(*C, UR.IndirectVHs);
456b60736ecSDimitry Andric
457b60736ecSDimitry Andric // If we haven't found an explicit devirtualization already see if we
458b60736ecSDimitry Andric // have decreased the number of indirect calls and increased the number
459b60736ecSDimitry Andric // of direct calls for any function in the SCC. This can be fooled by all
460b60736ecSDimitry Andric // manner of transformations such as DCE and other things, but seems to
461b60736ecSDimitry Andric // work well in practice.
462b60736ecSDimitry Andric if (!Devirt)
463b60736ecSDimitry Andric // Iterate over the keys in NewCallCounts, if Function also exists in
464b60736ecSDimitry Andric // CallCounts, make the check below.
465b60736ecSDimitry Andric for (auto &Pair : NewCallCounts) {
466b60736ecSDimitry Andric auto &CallCountNew = Pair.second;
467b60736ecSDimitry Andric auto CountIt = CallCounts.find(Pair.first);
468b60736ecSDimitry Andric if (CountIt != CallCounts.end()) {
469b60736ecSDimitry Andric const auto &CallCountOld = CountIt->second;
470b60736ecSDimitry Andric if (CallCountOld.Indirect > CallCountNew.Indirect &&
471b60736ecSDimitry Andric CallCountOld.Direct < CallCountNew.Direct) {
472b60736ecSDimitry Andric Devirt = true;
473b60736ecSDimitry Andric break;
474b60736ecSDimitry Andric }
475b60736ecSDimitry Andric }
476b60736ecSDimitry Andric }
477b60736ecSDimitry Andric
478b60736ecSDimitry Andric if (!Devirt) {
479b60736ecSDimitry Andric break;
480b60736ecSDimitry Andric }
481b60736ecSDimitry Andric
482b60736ecSDimitry Andric // Otherwise, if we've already hit our max, we're done.
483b60736ecSDimitry Andric if (Iteration >= MaxIterations) {
484b60736ecSDimitry Andric if (AbortOnMaxDevirtIterationsReached)
485b60736ecSDimitry Andric report_fatal_error("Max devirtualization iterations reached");
486b60736ecSDimitry Andric LLVM_DEBUG(
487b60736ecSDimitry Andric dbgs() << "Found another devirtualization after hitting the max "
488b60736ecSDimitry Andric "number of repetitions ("
489b60736ecSDimitry Andric << MaxIterations << ") on SCC: " << *C << "\n");
490b60736ecSDimitry Andric break;
491b60736ecSDimitry Andric }
492b60736ecSDimitry Andric
493b60736ecSDimitry Andric LLVM_DEBUG(
494b60736ecSDimitry Andric dbgs() << "Repeating an SCC pass after finding a devirtualization in: "
495b60736ecSDimitry Andric << *C << "\n");
496b60736ecSDimitry Andric
497b60736ecSDimitry Andric // Move over the new call counts in preparation for iterating.
498b60736ecSDimitry Andric CallCounts = std::move(NewCallCounts);
499b60736ecSDimitry Andric }
500b60736ecSDimitry Andric
501b60736ecSDimitry Andric // Note that we don't add any preserved entries here unlike a more normal
502b60736ecSDimitry Andric // "pass manager" because we only handle invalidation *between* iterations,
503b60736ecSDimitry Andric // not after the last iteration.
504b60736ecSDimitry Andric return PA;
505b60736ecSDimitry Andric }
506b60736ecSDimitry Andric
run(LazyCallGraph::SCC & C,CGSCCAnalysisManager & AM,LazyCallGraph & CG,CGSCCUpdateResult & UR)507b60736ecSDimitry Andric PreservedAnalyses CGSCCToFunctionPassAdaptor::run(LazyCallGraph::SCC &C,
508b60736ecSDimitry Andric CGSCCAnalysisManager &AM,
509b60736ecSDimitry Andric LazyCallGraph &CG,
510b60736ecSDimitry Andric CGSCCUpdateResult &UR) {
511b60736ecSDimitry Andric // Setup the function analysis manager from its proxy.
512b60736ecSDimitry Andric FunctionAnalysisManager &FAM =
513b60736ecSDimitry Andric AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
514b60736ecSDimitry Andric
515b60736ecSDimitry Andric SmallVector<LazyCallGraph::Node *, 4> Nodes;
516b60736ecSDimitry Andric for (LazyCallGraph::Node &N : C)
517b60736ecSDimitry Andric Nodes.push_back(&N);
518b60736ecSDimitry Andric
519b60736ecSDimitry Andric // The SCC may get split while we are optimizing functions due to deleting
520b60736ecSDimitry Andric // edges. If this happens, the current SCC can shift, so keep track of
521b60736ecSDimitry Andric // a pointer we can overwrite.
522b60736ecSDimitry Andric LazyCallGraph::SCC *CurrentC = &C;
523b60736ecSDimitry Andric
524b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Running function passes across an SCC: " << C << "\n");
525b60736ecSDimitry Andric
526b60736ecSDimitry Andric PreservedAnalyses PA = PreservedAnalyses::all();
527b60736ecSDimitry Andric for (LazyCallGraph::Node *N : Nodes) {
528b60736ecSDimitry Andric // Skip nodes from other SCCs. These may have been split out during
529b60736ecSDimitry Andric // processing. We'll eventually visit those SCCs and pick up the nodes
530b60736ecSDimitry Andric // there.
531b60736ecSDimitry Andric if (CG.lookupSCC(*N) != CurrentC)
532b60736ecSDimitry Andric continue;
533b60736ecSDimitry Andric
534b60736ecSDimitry Andric Function &F = N->getFunction();
535b60736ecSDimitry Andric
536c0981da4SDimitry Andric if (NoRerun && FAM.getCachedResult<ShouldNotRunFunctionPassesAnalysis>(F))
537c0981da4SDimitry Andric continue;
538c0981da4SDimitry Andric
539b60736ecSDimitry Andric PassInstrumentation PI = FAM.getResult<PassInstrumentationAnalysis>(F);
540b60736ecSDimitry Andric if (!PI.runBeforePass<Function>(*Pass, F))
541b60736ecSDimitry Andric continue;
542b60736ecSDimitry Andric
543e3b55780SDimitry Andric PreservedAnalyses PassPA = Pass->run(F, FAM);
544b60736ecSDimitry Andric
545b60736ecSDimitry Andric // We know that the function pass couldn't have invalidated any other
546b60736ecSDimitry Andric // function's analyses (that's the contract of a function pass), so
547b60736ecSDimitry Andric // directly handle the function analysis manager's invalidation here.
548c0981da4SDimitry Andric FAM.invalidate(F, EagerlyInvalidate ? PreservedAnalyses::none() : PassPA);
5497fa27ce4SDimitry Andric
5507fa27ce4SDimitry Andric PI.runAfterPass<Function>(*Pass, F, PassPA);
551b60736ecSDimitry Andric
552b60736ecSDimitry Andric // Then intersect the preserved set so that invalidation of module
553b60736ecSDimitry Andric // analyses will eventually occur when the module pass completes.
554b60736ecSDimitry Andric PA.intersect(std::move(PassPA));
555b60736ecSDimitry Andric
556b60736ecSDimitry Andric // If the call graph hasn't been preserved, update it based on this
557b60736ecSDimitry Andric // function pass. This may also update the current SCC to point to
558b60736ecSDimitry Andric // a smaller, more refined SCC.
559b60736ecSDimitry Andric auto PAC = PA.getChecker<LazyCallGraphAnalysis>();
560b60736ecSDimitry Andric if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Module>>()) {
561b60736ecSDimitry Andric CurrentC = &updateCGAndAnalysisManagerForFunctionPass(CG, *CurrentC, *N,
562b60736ecSDimitry Andric AM, UR, FAM);
563b60736ecSDimitry Andric assert(CG.lookupSCC(*N) == CurrentC &&
564b60736ecSDimitry Andric "Current SCC not updated to the SCC containing the current node!");
565b60736ecSDimitry Andric }
566b60736ecSDimitry Andric }
567b60736ecSDimitry Andric
568b60736ecSDimitry Andric // By definition we preserve the proxy. And we preserve all analyses on
569b60736ecSDimitry Andric // Functions. This precludes *any* invalidation of function analyses by the
570b60736ecSDimitry Andric // proxy, but that's OK because we've taken care to invalidate analyses in
571b60736ecSDimitry Andric // the function analysis manager incrementally above.
572b60736ecSDimitry Andric PA.preserveSet<AllAnalysesOn<Function>>();
573b60736ecSDimitry Andric PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
574b60736ecSDimitry Andric
575b60736ecSDimitry Andric // We've also ensured that we updated the call graph along the way.
576b60736ecSDimitry Andric PA.preserve<LazyCallGraphAnalysis>();
577b60736ecSDimitry Andric
578b60736ecSDimitry Andric return PA;
579b60736ecSDimitry Andric }
580b60736ecSDimitry Andric
invalidate(Module & M,const PreservedAnalyses & PA,ModuleAnalysisManager::Invalidator & Inv)581b915e9e0SDimitry Andric bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
582b915e9e0SDimitry Andric Module &M, const PreservedAnalyses &PA,
583b915e9e0SDimitry Andric ModuleAnalysisManager::Invalidator &Inv) {
584b915e9e0SDimitry Andric // If literally everything is preserved, we're done.
585b915e9e0SDimitry Andric if (PA.areAllPreserved())
586b915e9e0SDimitry Andric return false; // This is still a valid proxy.
587b915e9e0SDimitry Andric
588b915e9e0SDimitry Andric // If this proxy or the call graph is going to be invalidated, we also need
589b915e9e0SDimitry Andric // to clear all the keys coming from that analysis.
590b915e9e0SDimitry Andric //
591b915e9e0SDimitry Andric // We also directly invalidate the FAM's module proxy if necessary, and if
592b915e9e0SDimitry Andric // that proxy isn't preserved we can't preserve this proxy either. We rely on
593b915e9e0SDimitry Andric // it to handle module -> function analysis invalidation in the face of
594b915e9e0SDimitry Andric // structural changes and so if it's unavailable we conservatively clear the
595b915e9e0SDimitry Andric // entire SCC layer as well rather than trying to do invalidation ourselves.
596b915e9e0SDimitry Andric auto PAC = PA.getChecker<CGSCCAnalysisManagerModuleProxy>();
597b915e9e0SDimitry Andric if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>()) ||
598b915e9e0SDimitry Andric Inv.invalidate<LazyCallGraphAnalysis>(M, PA) ||
599b915e9e0SDimitry Andric Inv.invalidate<FunctionAnalysisManagerModuleProxy>(M, PA)) {
600b915e9e0SDimitry Andric InnerAM->clear();
601b915e9e0SDimitry Andric
602b915e9e0SDimitry Andric // And the proxy itself should be marked as invalid so that we can observe
603b915e9e0SDimitry Andric // the new call graph. This isn't strictly necessary because we cheat
604b915e9e0SDimitry Andric // above, but is still useful.
605b915e9e0SDimitry Andric return true;
606b915e9e0SDimitry Andric }
607b915e9e0SDimitry Andric
608b915e9e0SDimitry Andric // Directly check if the relevant set is preserved so we can short circuit
609b915e9e0SDimitry Andric // invalidating SCCs below.
610b915e9e0SDimitry Andric bool AreSCCAnalysesPreserved =
611b915e9e0SDimitry Andric PA.allAnalysesInSetPreserved<AllAnalysesOn<LazyCallGraph::SCC>>();
612b915e9e0SDimitry Andric
613b915e9e0SDimitry Andric // Ok, we have a graph, so we can propagate the invalidation down into it.
61471d5a254SDimitry Andric G->buildRefSCCs();
615b915e9e0SDimitry Andric for (auto &RC : G->postorder_ref_sccs())
616b915e9e0SDimitry Andric for (auto &C : RC) {
617e3b55780SDimitry Andric std::optional<PreservedAnalyses> InnerPA;
618b915e9e0SDimitry Andric
619b915e9e0SDimitry Andric // Check to see whether the preserved set needs to be adjusted based on
620b915e9e0SDimitry Andric // module-level analysis invalidation triggering deferred invalidation
621b915e9e0SDimitry Andric // for this SCC.
622b915e9e0SDimitry Andric if (auto *OuterProxy =
623b915e9e0SDimitry Andric InnerAM->getCachedResult<ModuleAnalysisManagerCGSCCProxy>(C))
624b915e9e0SDimitry Andric for (const auto &OuterInvalidationPair :
625b915e9e0SDimitry Andric OuterProxy->getOuterInvalidations()) {
626b915e9e0SDimitry Andric AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
627b915e9e0SDimitry Andric const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
628b915e9e0SDimitry Andric if (Inv.invalidate(OuterAnalysisID, M, PA)) {
629b915e9e0SDimitry Andric if (!InnerPA)
630b915e9e0SDimitry Andric InnerPA = PA;
631b915e9e0SDimitry Andric for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
632b915e9e0SDimitry Andric InnerPA->abandon(InnerAnalysisID);
633b915e9e0SDimitry Andric }
634b915e9e0SDimitry Andric }
635b915e9e0SDimitry Andric
636b915e9e0SDimitry Andric // Check if we needed a custom PA set. If so we'll need to run the inner
637b915e9e0SDimitry Andric // invalidation.
638b915e9e0SDimitry Andric if (InnerPA) {
639b915e9e0SDimitry Andric InnerAM->invalidate(C, *InnerPA);
640b915e9e0SDimitry Andric continue;
641b915e9e0SDimitry Andric }
642b915e9e0SDimitry Andric
643b915e9e0SDimitry Andric // Otherwise we only need to do invalidation if the original PA set didn't
644b915e9e0SDimitry Andric // preserve all SCC analyses.
645b915e9e0SDimitry Andric if (!AreSCCAnalysesPreserved)
646b915e9e0SDimitry Andric InnerAM->invalidate(C, PA);
647b915e9e0SDimitry Andric }
648b915e9e0SDimitry Andric
649b915e9e0SDimitry Andric // Return false to indicate that this result is still a valid proxy.
650b915e9e0SDimitry Andric return false;
651b915e9e0SDimitry Andric }
652b915e9e0SDimitry Andric
653b915e9e0SDimitry Andric template <>
654b915e9e0SDimitry Andric CGSCCAnalysisManagerModuleProxy::Result
run(Module & M,ModuleAnalysisManager & AM)655b915e9e0SDimitry Andric CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM) {
656b915e9e0SDimitry Andric // Force the Function analysis manager to also be available so that it can
657b915e9e0SDimitry Andric // be accessed in an SCC analysis and proxied onward to function passes.
658b915e9e0SDimitry Andric // FIXME: It is pretty awkward to just drop the result here and assert that
659b915e9e0SDimitry Andric // we can find it again later.
660b915e9e0SDimitry Andric (void)AM.getResult<FunctionAnalysisManagerModuleProxy>(M);
661b915e9e0SDimitry Andric
662b915e9e0SDimitry Andric return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M));
663b915e9e0SDimitry Andric }
664b915e9e0SDimitry Andric
665b915e9e0SDimitry Andric AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key;
666b915e9e0SDimitry Andric
667b915e9e0SDimitry Andric FunctionAnalysisManagerCGSCCProxy::Result
run(LazyCallGraph::SCC & C,CGSCCAnalysisManager & AM,LazyCallGraph & CG)668b915e9e0SDimitry Andric FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C,
669b915e9e0SDimitry Andric CGSCCAnalysisManager &AM,
670b915e9e0SDimitry Andric LazyCallGraph &CG) {
671cfca06d7SDimitry Andric // Note: unconditionally getting checking that the proxy exists may get it at
672cfca06d7SDimitry Andric // this point. There are cases when this is being run unnecessarily, but
673cfca06d7SDimitry Andric // it is cheap and having the assertion in place is more valuable.
674cfca06d7SDimitry Andric auto &MAMProxy = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG);
675b915e9e0SDimitry Andric Module &M = *C.begin()->getFunction().getParent();
676cfca06d7SDimitry Andric bool ProxyExists =
677cfca06d7SDimitry Andric MAMProxy.cachedResultExists<FunctionAnalysisManagerModuleProxy>(M);
678cfca06d7SDimitry Andric assert(ProxyExists &&
679cfca06d7SDimitry Andric "The CGSCC pass manager requires that the FAM module proxy is run "
680cfca06d7SDimitry Andric "on the module prior to entering the CGSCC walk");
681cfca06d7SDimitry Andric (void)ProxyExists;
682b915e9e0SDimitry Andric
683cfca06d7SDimitry Andric // We just return an empty result. The caller will use the updateFAM interface
684cfca06d7SDimitry Andric // to correctly register the relevant FunctionAnalysisManager based on the
685cfca06d7SDimitry Andric // context in which this proxy is run.
686cfca06d7SDimitry Andric return Result();
687b915e9e0SDimitry Andric }
688b915e9e0SDimitry Andric
invalidate(LazyCallGraph::SCC & C,const PreservedAnalyses & PA,CGSCCAnalysisManager::Invalidator & Inv)689b915e9e0SDimitry Andric bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate(
690b915e9e0SDimitry Andric LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
691b915e9e0SDimitry Andric CGSCCAnalysisManager::Invalidator &Inv) {
692ca089b24SDimitry Andric // If literally everything is preserved, we're done.
693ca089b24SDimitry Andric if (PA.areAllPreserved())
694ca089b24SDimitry Andric return false; // This is still a valid proxy.
695b915e9e0SDimitry Andric
696cfca06d7SDimitry Andric // All updates to preserve valid results are done below, so we don't need to
697cfca06d7SDimitry Andric // invalidate this proxy.
698ca089b24SDimitry Andric //
699ca089b24SDimitry Andric // Note that in order to preserve this proxy, a module pass must ensure that
700ca089b24SDimitry Andric // the FAM has been completely updated to handle the deletion of functions.
701ca089b24SDimitry Andric // Specifically, any FAM-cached results for those functions need to have been
702ca089b24SDimitry Andric // forcibly cleared. When preserved, this proxy will only invalidate results
703ca089b24SDimitry Andric // cached on functions *still in the module* at the end of the module pass.
704ca089b24SDimitry Andric auto PAC = PA.getChecker<FunctionAnalysisManagerCGSCCProxy>();
705ca089b24SDimitry Andric if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<LazyCallGraph::SCC>>()) {
706ca089b24SDimitry Andric for (LazyCallGraph::Node &N : C)
707344a3780SDimitry Andric FAM->invalidate(N.getFunction(), PA);
708ca089b24SDimitry Andric
709cfca06d7SDimitry Andric return false;
710ca089b24SDimitry Andric }
711ca089b24SDimitry Andric
712ca089b24SDimitry Andric // Directly check if the relevant set is preserved.
713ca089b24SDimitry Andric bool AreFunctionAnalysesPreserved =
714ca089b24SDimitry Andric PA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>();
715ca089b24SDimitry Andric
716ca089b24SDimitry Andric // Now walk all the functions to see if any inner analysis invalidation is
717ca089b24SDimitry Andric // necessary.
718ca089b24SDimitry Andric for (LazyCallGraph::Node &N : C) {
719ca089b24SDimitry Andric Function &F = N.getFunction();
720e3b55780SDimitry Andric std::optional<PreservedAnalyses> FunctionPA;
721ca089b24SDimitry Andric
722ca089b24SDimitry Andric // Check to see whether the preserved set needs to be pruned based on
723ca089b24SDimitry Andric // SCC-level analysis invalidation that triggers deferred invalidation
724ca089b24SDimitry Andric // registered with the outer analysis manager proxy for this function.
725ca089b24SDimitry Andric if (auto *OuterProxy =
726ca089b24SDimitry Andric FAM->getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F))
727ca089b24SDimitry Andric for (const auto &OuterInvalidationPair :
728ca089b24SDimitry Andric OuterProxy->getOuterInvalidations()) {
729ca089b24SDimitry Andric AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
730ca089b24SDimitry Andric const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
731ca089b24SDimitry Andric if (Inv.invalidate(OuterAnalysisID, C, PA)) {
732ca089b24SDimitry Andric if (!FunctionPA)
733ca089b24SDimitry Andric FunctionPA = PA;
734ca089b24SDimitry Andric for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
735ca089b24SDimitry Andric FunctionPA->abandon(InnerAnalysisID);
736ca089b24SDimitry Andric }
737ca089b24SDimitry Andric }
738ca089b24SDimitry Andric
739ca089b24SDimitry Andric // Check if we needed a custom PA set, and if so we'll need to run the
740ca089b24SDimitry Andric // inner invalidation.
741ca089b24SDimitry Andric if (FunctionPA) {
742ca089b24SDimitry Andric FAM->invalidate(F, *FunctionPA);
743ca089b24SDimitry Andric continue;
744ca089b24SDimitry Andric }
745ca089b24SDimitry Andric
746ca089b24SDimitry Andric // Otherwise we only need to do invalidation if the original PA set didn't
747ca089b24SDimitry Andric // preserve all function analyses.
748ca089b24SDimitry Andric if (!AreFunctionAnalysesPreserved)
749ca089b24SDimitry Andric FAM->invalidate(F, PA);
750ca089b24SDimitry Andric }
751ca089b24SDimitry Andric
752ca089b24SDimitry Andric // Return false to indicate that this result is still a valid proxy.
753b915e9e0SDimitry Andric return false;
754b915e9e0SDimitry Andric }
755b915e9e0SDimitry Andric
756044eb2f6SDimitry Andric } // end namespace llvm
757b915e9e0SDimitry Andric
758cfca06d7SDimitry Andric /// When a new SCC is created for the graph we first update the
759cfca06d7SDimitry Andric /// FunctionAnalysisManager in the Proxy's result.
760cfca06d7SDimitry Andric /// As there might be function analysis results cached for the functions now in
761cfca06d7SDimitry Andric /// that SCC, two forms of updates are required.
762ca089b24SDimitry Andric ///
763ca089b24SDimitry Andric /// First, a proxy from the SCC to the FunctionAnalysisManager needs to be
764ca089b24SDimitry Andric /// created so that any subsequent invalidation events to the SCC are
765ca089b24SDimitry Andric /// propagated to the function analysis results cached for functions within it.
766ca089b24SDimitry Andric ///
767ca089b24SDimitry Andric /// Second, if any of the functions within the SCC have analysis results with
768ca089b24SDimitry Andric /// outer analysis dependencies, then those dependencies would point to the
769ca089b24SDimitry Andric /// *wrong* SCC's analysis result. We forcibly invalidate the necessary
770ca089b24SDimitry Andric /// function analyses so that they don't retain stale handles.
updateNewSCCFunctionAnalyses(LazyCallGraph::SCC & C,LazyCallGraph & G,CGSCCAnalysisManager & AM,FunctionAnalysisManager & FAM)771ca089b24SDimitry Andric static void updateNewSCCFunctionAnalyses(LazyCallGraph::SCC &C,
772ca089b24SDimitry Andric LazyCallGraph &G,
773cfca06d7SDimitry Andric CGSCCAnalysisManager &AM,
774cfca06d7SDimitry Andric FunctionAnalysisManager &FAM) {
775cfca06d7SDimitry Andric AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, G).updateFAM(FAM);
776ca089b24SDimitry Andric
777ca089b24SDimitry Andric // Now walk the functions in this SCC and invalidate any function analysis
778ca089b24SDimitry Andric // results that might have outer dependencies on an SCC analysis.
779ca089b24SDimitry Andric for (LazyCallGraph::Node &N : C) {
780ca089b24SDimitry Andric Function &F = N.getFunction();
781ca089b24SDimitry Andric
782ca089b24SDimitry Andric auto *OuterProxy =
783ca089b24SDimitry Andric FAM.getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F);
784ca089b24SDimitry Andric if (!OuterProxy)
785ca089b24SDimitry Andric // No outer analyses were queried, nothing to do.
786ca089b24SDimitry Andric continue;
787ca089b24SDimitry Andric
788ca089b24SDimitry Andric // Forcibly abandon all the inner analyses with dependencies, but
789ca089b24SDimitry Andric // invalidate nothing else.
790ca089b24SDimitry Andric auto PA = PreservedAnalyses::all();
791ca089b24SDimitry Andric for (const auto &OuterInvalidationPair :
792ca089b24SDimitry Andric OuterProxy->getOuterInvalidations()) {
793ca089b24SDimitry Andric const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
794ca089b24SDimitry Andric for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
795ca089b24SDimitry Andric PA.abandon(InnerAnalysisID);
796ca089b24SDimitry Andric }
797ca089b24SDimitry Andric
798ca089b24SDimitry Andric // Now invalidate anything we found.
799ca089b24SDimitry Andric FAM.invalidate(F, PA);
800ca089b24SDimitry Andric }
801ca089b24SDimitry Andric }
802ca089b24SDimitry Andric
803b915e9e0SDimitry Andric /// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
804b915e9e0SDimitry Andric /// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
805b915e9e0SDimitry Andric /// added SCCs.
806b915e9e0SDimitry Andric ///
807b915e9e0SDimitry Andric /// The range of new SCCs must be in postorder already. The SCC they were split
808b915e9e0SDimitry Andric /// out of must be provided as \p C. The current node being mutated and
809b915e9e0SDimitry Andric /// triggering updates must be passed as \p N.
810b915e9e0SDimitry Andric ///
811b915e9e0SDimitry Andric /// This function returns the SCC containing \p N. This will be either \p C if
812b915e9e0SDimitry Andric /// no new SCCs have been split out, or it will be the new SCC containing \p N.
813b915e9e0SDimitry Andric template <typename SCCRangeT>
814044eb2f6SDimitry Andric static LazyCallGraph::SCC *
incorporateNewSCCRange(const SCCRangeT & NewSCCRange,LazyCallGraph & G,LazyCallGraph::Node & N,LazyCallGraph::SCC * C,CGSCCAnalysisManager & AM,CGSCCUpdateResult & UR)815b915e9e0SDimitry Andric incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
816b915e9e0SDimitry Andric LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
817044eb2f6SDimitry Andric CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
818044eb2f6SDimitry Andric using SCC = LazyCallGraph::SCC;
819b915e9e0SDimitry Andric
820b60736ecSDimitry Andric if (NewSCCRange.empty())
821b915e9e0SDimitry Andric return C;
822b915e9e0SDimitry Andric
823b915e9e0SDimitry Andric // Add the current SCC to the worklist as its shape has changed.
824b915e9e0SDimitry Andric UR.CWorklist.insert(C);
825eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist:" << *C
826eb11fae6SDimitry Andric << "\n");
827b915e9e0SDimitry Andric
828b915e9e0SDimitry Andric SCC *OldC = C;
829b915e9e0SDimitry Andric
830b915e9e0SDimitry Andric // Update the current SCC. Note that if we have new SCCs, this must actually
831b915e9e0SDimitry Andric // change the SCC.
832b915e9e0SDimitry Andric assert(C != &*NewSCCRange.begin() &&
833b915e9e0SDimitry Andric "Cannot insert new SCCs without changing current SCC!");
834b915e9e0SDimitry Andric C = &*NewSCCRange.begin();
835b915e9e0SDimitry Andric assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
836b915e9e0SDimitry Andric
837ca089b24SDimitry Andric // If we had a cached FAM proxy originally, we will want to create more of
838ca089b24SDimitry Andric // them for each SCC that was split off.
839cfca06d7SDimitry Andric FunctionAnalysisManager *FAM = nullptr;
840cfca06d7SDimitry Andric if (auto *FAMProxy =
841cfca06d7SDimitry Andric AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*OldC))
842cfca06d7SDimitry Andric FAM = &FAMProxy->getManager();
843ca089b24SDimitry Andric
844ca089b24SDimitry Andric // We need to propagate an invalidation call to all but the newly current SCC
845ca089b24SDimitry Andric // because the outer pass manager won't do that for us after splitting them.
846ca089b24SDimitry Andric // FIXME: We should accept a PreservedAnalysis from the CG updater so that if
847eb11fae6SDimitry Andric // there are preserved analysis we can avoid invalidating them here for
848ca089b24SDimitry Andric // split-off SCCs.
849ca089b24SDimitry Andric // We know however that this will preserve any FAM proxy so go ahead and mark
850ca089b24SDimitry Andric // that.
851c0981da4SDimitry Andric auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
852ca089b24SDimitry Andric PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
853ca089b24SDimitry Andric AM.invalidate(*OldC, PA);
854ca089b24SDimitry Andric
855ca089b24SDimitry Andric // Ensure the now-current SCC's function analyses are updated.
856cfca06d7SDimitry Andric if (FAM)
857cfca06d7SDimitry Andric updateNewSCCFunctionAnalyses(*C, G, AM, *FAM);
858ca089b24SDimitry Andric
859344a3780SDimitry Andric for (SCC &NewC : llvm::reverse(llvm::drop_begin(NewSCCRange))) {
860b915e9e0SDimitry Andric assert(C != &NewC && "No need to re-visit the current SCC!");
861b915e9e0SDimitry Andric assert(OldC != &NewC && "Already handled the original SCC!");
862b915e9e0SDimitry Andric UR.CWorklist.insert(&NewC);
863eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n");
864ca089b24SDimitry Andric
865ca089b24SDimitry Andric // Ensure new SCCs' function analyses are updated.
866cfca06d7SDimitry Andric if (FAM)
867cfca06d7SDimitry Andric updateNewSCCFunctionAnalyses(NewC, G, AM, *FAM);
868ca089b24SDimitry Andric
869ca089b24SDimitry Andric // Also propagate a normal invalidation to the new SCC as only the current
870ca089b24SDimitry Andric // will get one from the pass manager infrastructure.
871ca089b24SDimitry Andric AM.invalidate(NewC, PA);
872b915e9e0SDimitry Andric }
873b915e9e0SDimitry Andric return C;
874b915e9e0SDimitry Andric }
875b915e9e0SDimitry Andric
updateCGAndAnalysisManagerForPass(LazyCallGraph & G,LazyCallGraph::SCC & InitialC,LazyCallGraph::Node & N,CGSCCAnalysisManager & AM,CGSCCUpdateResult & UR,FunctionAnalysisManager & FAM,bool FunctionPass)876cfca06d7SDimitry Andric static LazyCallGraph::SCC &updateCGAndAnalysisManagerForPass(
877b915e9e0SDimitry Andric LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
878cfca06d7SDimitry Andric CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
879cfca06d7SDimitry Andric FunctionAnalysisManager &FAM, bool FunctionPass) {
880044eb2f6SDimitry Andric using Node = LazyCallGraph::Node;
881044eb2f6SDimitry Andric using Edge = LazyCallGraph::Edge;
882044eb2f6SDimitry Andric using SCC = LazyCallGraph::SCC;
883044eb2f6SDimitry Andric using RefSCC = LazyCallGraph::RefSCC;
884b915e9e0SDimitry Andric
885b915e9e0SDimitry Andric RefSCC &InitialRC = InitialC.getOuterRefSCC();
886b915e9e0SDimitry Andric SCC *C = &InitialC;
887b915e9e0SDimitry Andric RefSCC *RC = &InitialRC;
888b915e9e0SDimitry Andric Function &F = N.getFunction();
889b915e9e0SDimitry Andric
890b915e9e0SDimitry Andric // Walk the function body and build up the set of retained, promoted, and
891b915e9e0SDimitry Andric // demoted edges.
892b915e9e0SDimitry Andric SmallVector<Constant *, 16> Worklist;
893b915e9e0SDimitry Andric SmallPtrSet<Constant *, 16> Visited;
89471d5a254SDimitry Andric SmallPtrSet<Node *, 16> RetainedEdges;
89571d5a254SDimitry Andric SmallSetVector<Node *, 4> PromotedRefTargets;
89671d5a254SDimitry Andric SmallSetVector<Node *, 4> DemotedCallTargets;
897cfca06d7SDimitry Andric SmallSetVector<Node *, 4> NewCallEdges;
898cfca06d7SDimitry Andric SmallSetVector<Node *, 4> NewRefEdges;
899b915e9e0SDimitry Andric
900b915e9e0SDimitry Andric // First walk the function and handle all called functions. We do this first
901b915e9e0SDimitry Andric // because if there is a single call edge, whether there are ref edges is
902b915e9e0SDimitry Andric // irrelevant.
903b60736ecSDimitry Andric for (Instruction &I : instructions(F)) {
904b60736ecSDimitry Andric if (auto *CB = dyn_cast<CallBase>(&I)) {
905b60736ecSDimitry Andric if (Function *Callee = CB->getCalledFunction()) {
906b915e9e0SDimitry Andric if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
907b60736ecSDimitry Andric Node *CalleeN = G.lookup(*Callee);
908b60736ecSDimitry Andric assert(CalleeN &&
909b60736ecSDimitry Andric "Visited function should already have an associated node");
910b60736ecSDimitry Andric Edge *E = N->lookup(*CalleeN);
911cfca06d7SDimitry Andric assert((E || !FunctionPass) &&
912cfca06d7SDimitry Andric "No function transformations should introduce *new* "
913b915e9e0SDimitry Andric "call edges! Any new calls should be modeled as "
914b915e9e0SDimitry Andric "promoted existing ref edges!");
915b60736ecSDimitry Andric bool Inserted = RetainedEdges.insert(CalleeN).second;
916044eb2f6SDimitry Andric (void)Inserted;
917044eb2f6SDimitry Andric assert(Inserted && "We should never visit a function twice.");
918cfca06d7SDimitry Andric if (!E)
919b60736ecSDimitry Andric NewCallEdges.insert(CalleeN);
920cfca06d7SDimitry Andric else if (!E->isCall())
921b60736ecSDimitry Andric PromotedRefTargets.insert(CalleeN);
922b60736ecSDimitry Andric }
923b60736ecSDimitry Andric } else {
924b60736ecSDimitry Andric // We can miss devirtualization if an indirect call is created then
925b60736ecSDimitry Andric // promoted before updateCGAndAnalysisManagerForPass runs.
926b60736ecSDimitry Andric auto *Entry = UR.IndirectVHs.find(CB);
927b60736ecSDimitry Andric if (Entry == UR.IndirectVHs.end())
928b60736ecSDimitry Andric UR.IndirectVHs.insert({CB, WeakTrackingVH(CB)});
929b60736ecSDimitry Andric else if (!Entry->second)
930b60736ecSDimitry Andric Entry->second = WeakTrackingVH(CB);
931b60736ecSDimitry Andric }
932b60736ecSDimitry Andric }
933b915e9e0SDimitry Andric }
934b915e9e0SDimitry Andric
935b915e9e0SDimitry Andric // Now walk all references.
936b915e9e0SDimitry Andric for (Instruction &I : instructions(F))
937b915e9e0SDimitry Andric for (Value *Op : I.operand_values())
938b60736ecSDimitry Andric if (auto *OpC = dyn_cast<Constant>(Op))
939b60736ecSDimitry Andric if (Visited.insert(OpC).second)
940b60736ecSDimitry Andric Worklist.push_back(OpC);
941b915e9e0SDimitry Andric
94293c91e39SDimitry Andric auto VisitRef = [&](Function &Referee) {
943b60736ecSDimitry Andric Node *RefereeN = G.lookup(Referee);
944b60736ecSDimitry Andric assert(RefereeN &&
945b60736ecSDimitry Andric "Visited function should already have an associated node");
946b60736ecSDimitry Andric Edge *E = N->lookup(*RefereeN);
947cfca06d7SDimitry Andric assert((E || !FunctionPass) &&
948cfca06d7SDimitry Andric "No function transformations should introduce *new* ref "
949b915e9e0SDimitry Andric "edges! Any new ref edges would require IPO which "
950b915e9e0SDimitry Andric "function passes aren't allowed to do!");
951b60736ecSDimitry Andric bool Inserted = RetainedEdges.insert(RefereeN).second;
952044eb2f6SDimitry Andric (void)Inserted;
953044eb2f6SDimitry Andric assert(Inserted && "We should never visit a function twice.");
954cfca06d7SDimitry Andric if (!E)
955b60736ecSDimitry Andric NewRefEdges.insert(RefereeN);
956cfca06d7SDimitry Andric else if (E->isCall())
957b60736ecSDimitry Andric DemotedCallTargets.insert(RefereeN);
95893c91e39SDimitry Andric };
95993c91e39SDimitry Andric LazyCallGraph::visitReferences(Worklist, Visited, VisitRef);
96093c91e39SDimitry Andric
961cfca06d7SDimitry Andric // Handle new ref edges.
962cfca06d7SDimitry Andric for (Node *RefTarget : NewRefEdges) {
963cfca06d7SDimitry Andric SCC &TargetC = *G.lookupSCC(*RefTarget);
964cfca06d7SDimitry Andric RefSCC &TargetRC = TargetC.getOuterRefSCC();
965cfca06d7SDimitry Andric (void)TargetRC;
966cfca06d7SDimitry Andric // TODO: This only allows trivial edges to be added for now.
967344a3780SDimitry Andric #ifdef EXPENSIVE_CHECKS
968cfca06d7SDimitry Andric assert((RC == &TargetRC ||
969cfca06d7SDimitry Andric RC->isAncestorOf(TargetRC)) && "New ref edge is not trivial!");
970344a3780SDimitry Andric #endif
971cfca06d7SDimitry Andric RC->insertTrivialRefEdge(N, *RefTarget);
972cfca06d7SDimitry Andric }
973cfca06d7SDimitry Andric
974cfca06d7SDimitry Andric // Handle new call edges.
975cfca06d7SDimitry Andric for (Node *CallTarget : NewCallEdges) {
976cfca06d7SDimitry Andric SCC &TargetC = *G.lookupSCC(*CallTarget);
977cfca06d7SDimitry Andric RefSCC &TargetRC = TargetC.getOuterRefSCC();
978cfca06d7SDimitry Andric (void)TargetRC;
979cfca06d7SDimitry Andric // TODO: This only allows trivial edges to be added for now.
980344a3780SDimitry Andric #ifdef EXPENSIVE_CHECKS
981cfca06d7SDimitry Andric assert((RC == &TargetRC ||
982cfca06d7SDimitry Andric RC->isAncestorOf(TargetRC)) && "New call edge is not trivial!");
983344a3780SDimitry Andric #endif
984b60736ecSDimitry Andric // Add a trivial ref edge to be promoted later on alongside
985b60736ecSDimitry Andric // PromotedRefTargets.
986b60736ecSDimitry Andric RC->insertTrivialRefEdge(N, *CallTarget);
987cfca06d7SDimitry Andric }
988cfca06d7SDimitry Andric
98993c91e39SDimitry Andric // Include synthetic reference edges to known, defined lib functions.
990b60736ecSDimitry Andric for (auto *LibFn : G.getLibFunctions())
991044eb2f6SDimitry Andric // While the list of lib functions doesn't have repeats, don't re-visit
992044eb2f6SDimitry Andric // anything handled above.
993b60736ecSDimitry Andric if (!Visited.count(LibFn))
994b60736ecSDimitry Andric VisitRef(*LibFn);
995b915e9e0SDimitry Andric
996b915e9e0SDimitry Andric // First remove all of the edges that are no longer present in this function.
997044eb2f6SDimitry Andric // The first step makes these edges uniformly ref edges and accumulates them
998044eb2f6SDimitry Andric // into a separate data structure so removal doesn't invalidate anything.
999044eb2f6SDimitry Andric SmallVector<Node *, 4> DeadTargets;
1000044eb2f6SDimitry Andric for (Edge &E : *N) {
1001044eb2f6SDimitry Andric if (RetainedEdges.count(&E.getNode()))
1002b915e9e0SDimitry Andric continue;
1003b915e9e0SDimitry Andric
1004044eb2f6SDimitry Andric SCC &TargetC = *G.lookupSCC(E.getNode());
1005044eb2f6SDimitry Andric RefSCC &TargetRC = TargetC.getOuterRefSCC();
1006044eb2f6SDimitry Andric if (&TargetRC == RC && E.isCall()) {
1007b915e9e0SDimitry Andric if (C != &TargetC) {
1008b915e9e0SDimitry Andric // For separate SCCs this is trivial.
1009044eb2f6SDimitry Andric RC->switchTrivialInternalEdgeToRef(N, E.getNode());
1010b915e9e0SDimitry Andric } else {
1011b915e9e0SDimitry Andric // Now update the call graph.
1012044eb2f6SDimitry Andric C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, E.getNode()),
1013044eb2f6SDimitry Andric G, N, C, AM, UR);
1014b915e9e0SDimitry Andric }
1015b915e9e0SDimitry Andric }
1016b915e9e0SDimitry Andric
1017044eb2f6SDimitry Andric // Now that this is ready for actual removal, put it into our list.
1018044eb2f6SDimitry Andric DeadTargets.push_back(&E.getNode());
1019044eb2f6SDimitry Andric }
1020044eb2f6SDimitry Andric // Remove the easy cases quickly and actually pull them out of our list.
1021b60736ecSDimitry Andric llvm::erase_if(DeadTargets, [&](Node *TargetN) {
1022044eb2f6SDimitry Andric SCC &TargetC = *G.lookupSCC(*TargetN);
1023044eb2f6SDimitry Andric RefSCC &TargetRC = TargetC.getOuterRefSCC();
1024044eb2f6SDimitry Andric
1025044eb2f6SDimitry Andric // We can't trivially remove internal targets, so skip
1026044eb2f6SDimitry Andric // those.
1027044eb2f6SDimitry Andric if (&TargetRC == RC)
1028044eb2f6SDimitry Andric return false;
1029044eb2f6SDimitry Andric
1030b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Deleting outgoing edge from '" << N << "' to '"
1031344a3780SDimitry Andric << *TargetN << "'\n");
1032344a3780SDimitry Andric RC->removeOutgoingEdge(N, *TargetN);
1033044eb2f6SDimitry Andric return true;
1034b60736ecSDimitry Andric });
1035044eb2f6SDimitry Andric
1036b915e9e0SDimitry Andric // Next demote all the call edges that are now ref edges. This helps make
1037b915e9e0SDimitry Andric // the SCCs small which should minimize the work below as we don't want to
1038b915e9e0SDimitry Andric // form cycles that this would break.
103971d5a254SDimitry Andric for (Node *RefTarget : DemotedCallTargets) {
104071d5a254SDimitry Andric SCC &TargetC = *G.lookupSCC(*RefTarget);
1041b915e9e0SDimitry Andric RefSCC &TargetRC = TargetC.getOuterRefSCC();
1042b915e9e0SDimitry Andric
1043b915e9e0SDimitry Andric // The easy case is when the target RefSCC is not this RefSCC. This is
1044b915e9e0SDimitry Andric // only supported when the target RefSCC is a child of this RefSCC.
1045b915e9e0SDimitry Andric if (&TargetRC != RC) {
1046344a3780SDimitry Andric #ifdef EXPENSIVE_CHECKS
1047b915e9e0SDimitry Andric assert(RC->isAncestorOf(TargetRC) &&
1048b915e9e0SDimitry Andric "Cannot potentially form RefSCC cycles here!");
1049344a3780SDimitry Andric #endif
105071d5a254SDimitry Andric RC->switchOutgoingEdgeToRef(N, *RefTarget);
1051eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Switch outgoing call edge to a ref edge from '" << N
1052044eb2f6SDimitry Andric << "' to '" << *RefTarget << "'\n");
1053b915e9e0SDimitry Andric continue;
1054b915e9e0SDimitry Andric }
1055b915e9e0SDimitry Andric
1056b915e9e0SDimitry Andric // We are switching an internal call edge to a ref edge. This may split up
1057b915e9e0SDimitry Andric // some SCCs.
1058b915e9e0SDimitry Andric if (C != &TargetC) {
1059b915e9e0SDimitry Andric // For separate SCCs this is trivial.
106071d5a254SDimitry Andric RC->switchTrivialInternalEdgeToRef(N, *RefTarget);
1061b915e9e0SDimitry Andric continue;
1062b915e9e0SDimitry Andric }
1063b915e9e0SDimitry Andric
1064b915e9e0SDimitry Andric // Now update the call graph.
106571d5a254SDimitry Andric C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, *RefTarget), G, N,
1066044eb2f6SDimitry Andric C, AM, UR);
1067b915e9e0SDimitry Andric }
1068b915e9e0SDimitry Andric
1069b60736ecSDimitry Andric // We added a ref edge earlier for new call edges, promote those to call edges
1070b60736ecSDimitry Andric // alongside PromotedRefTargets.
1071b60736ecSDimitry Andric for (Node *E : NewCallEdges)
1072b60736ecSDimitry Andric PromotedRefTargets.insert(E);
1073b60736ecSDimitry Andric
1074b915e9e0SDimitry Andric // Now promote ref edges into call edges.
107571d5a254SDimitry Andric for (Node *CallTarget : PromotedRefTargets) {
107671d5a254SDimitry Andric SCC &TargetC = *G.lookupSCC(*CallTarget);
1077b915e9e0SDimitry Andric RefSCC &TargetRC = TargetC.getOuterRefSCC();
1078b915e9e0SDimitry Andric
1079b915e9e0SDimitry Andric // The easy case is when the target RefSCC is not this RefSCC. This is
1080b915e9e0SDimitry Andric // only supported when the target RefSCC is a child of this RefSCC.
1081b915e9e0SDimitry Andric if (&TargetRC != RC) {
1082344a3780SDimitry Andric #ifdef EXPENSIVE_CHECKS
1083b915e9e0SDimitry Andric assert(RC->isAncestorOf(TargetRC) &&
1084b915e9e0SDimitry Andric "Cannot potentially form RefSCC cycles here!");
1085344a3780SDimitry Andric #endif
108671d5a254SDimitry Andric RC->switchOutgoingEdgeToCall(N, *CallTarget);
1087eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Switch outgoing ref edge to a call edge from '" << N
1088044eb2f6SDimitry Andric << "' to '" << *CallTarget << "'\n");
1089b915e9e0SDimitry Andric continue;
1090b915e9e0SDimitry Andric }
1091eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Switch an internal ref edge to a call edge from '"
1092eb11fae6SDimitry Andric << N << "' to '" << *CallTarget << "'\n");
1093b915e9e0SDimitry Andric
1094b915e9e0SDimitry Andric // Otherwise we are switching an internal ref edge to a call edge. This
1095b915e9e0SDimitry Andric // may merge away some SCCs, and we add those to the UpdateResult. We also
1096b915e9e0SDimitry Andric // need to make sure to update the worklist in the event SCCs have moved
1097ca089b24SDimitry Andric // before the current one in the post-order sequence
1098ca089b24SDimitry Andric bool HasFunctionAnalysisProxy = false;
1099b915e9e0SDimitry Andric auto InitialSCCIndex = RC->find(*C) - RC->begin();
1100ca089b24SDimitry Andric bool FormedCycle = RC->switchInternalEdgeToCall(
1101ca089b24SDimitry Andric N, *CallTarget, [&](ArrayRef<SCC *> MergedSCCs) {
1102ca089b24SDimitry Andric for (SCC *MergedC : MergedSCCs) {
1103ca089b24SDimitry Andric assert(MergedC != &TargetC && "Cannot merge away the target SCC!");
1104ca089b24SDimitry Andric
1105ca089b24SDimitry Andric HasFunctionAnalysisProxy |=
1106ca089b24SDimitry Andric AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(
1107ca089b24SDimitry Andric *MergedC) != nullptr;
1108ca089b24SDimitry Andric
1109ca089b24SDimitry Andric // Mark that this SCC will no longer be valid.
1110ca089b24SDimitry Andric UR.InvalidatedSCCs.insert(MergedC);
1111ca089b24SDimitry Andric
1112ca089b24SDimitry Andric // FIXME: We should really do a 'clear' here to forcibly release
1113ca089b24SDimitry Andric // memory, but we don't have a good way of doing that and
1114ca089b24SDimitry Andric // preserving the function analyses.
1115ca089b24SDimitry Andric auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
1116ca089b24SDimitry Andric PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1117ca089b24SDimitry Andric AM.invalidate(*MergedC, PA);
1118ca089b24SDimitry Andric }
1119ca089b24SDimitry Andric });
1120ca089b24SDimitry Andric
1121ca089b24SDimitry Andric // If we formed a cycle by creating this call, we need to update more data
1122ca089b24SDimitry Andric // structures.
1123ca089b24SDimitry Andric if (FormedCycle) {
1124b915e9e0SDimitry Andric C = &TargetC;
1125b915e9e0SDimitry Andric assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
1126b915e9e0SDimitry Andric
1127ca089b24SDimitry Andric // If one of the invalidated SCCs had a cached proxy to a function
1128ca089b24SDimitry Andric // analysis manager, we need to create a proxy in the new current SCC as
1129eb11fae6SDimitry Andric // the invalidated SCCs had their functions moved.
1130ca089b24SDimitry Andric if (HasFunctionAnalysisProxy)
1131cfca06d7SDimitry Andric AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G).updateFAM(FAM);
1132ca089b24SDimitry Andric
1133b915e9e0SDimitry Andric // Any analyses cached for this SCC are no longer precise as the shape
1134ca089b24SDimitry Andric // has changed by introducing this cycle. However, we have taken care to
1135ca089b24SDimitry Andric // update the proxies so it remains valide.
1136ca089b24SDimitry Andric auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
1137ca089b24SDimitry Andric PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1138ca089b24SDimitry Andric AM.invalidate(*C, PA);
1139b915e9e0SDimitry Andric }
1140b915e9e0SDimitry Andric auto NewSCCIndex = RC->find(*C) - RC->begin();
1141044eb2f6SDimitry Andric // If we have actually moved an SCC to be topologically "below" the current
1142044eb2f6SDimitry Andric // one due to merging, we will need to revisit the current SCC after
1143044eb2f6SDimitry Andric // visiting those moved SCCs.
1144044eb2f6SDimitry Andric //
1145044eb2f6SDimitry Andric // It is critical that we *do not* revisit the current SCC unless we
1146044eb2f6SDimitry Andric // actually move SCCs in the process of merging because otherwise we may
1147044eb2f6SDimitry Andric // form a cycle where an SCC is split apart, merged, split, merged and so
1148044eb2f6SDimitry Andric // on infinitely.
1149b915e9e0SDimitry Andric if (InitialSCCIndex < NewSCCIndex) {
1150b915e9e0SDimitry Andric // Put our current SCC back onto the worklist as we'll visit other SCCs
1151b915e9e0SDimitry Andric // that are now definitively ordered prior to the current one in the
1152b915e9e0SDimitry Andric // post-order sequence, and may end up observing more precise context to
1153b915e9e0SDimitry Andric // optimize the current SCC.
1154b915e9e0SDimitry Andric UR.CWorklist.insert(C);
1155eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist: " << *C
1156044eb2f6SDimitry Andric << "\n");
1157b915e9e0SDimitry Andric // Enqueue in reverse order as we pop off the back of the worklist.
1158044eb2f6SDimitry Andric for (SCC &MovedC : llvm::reverse(make_range(RC->begin() + InitialSCCIndex,
1159b915e9e0SDimitry Andric RC->begin() + NewSCCIndex))) {
1160b915e9e0SDimitry Andric UR.CWorklist.insert(&MovedC);
1161eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Enqueuing a newly earlier in post-order SCC: "
1162044eb2f6SDimitry Andric << MovedC << "\n");
1163b915e9e0SDimitry Andric }
1164b915e9e0SDimitry Andric }
1165b915e9e0SDimitry Andric }
1166b915e9e0SDimitry Andric
1167b915e9e0SDimitry Andric assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
1168b915e9e0SDimitry Andric assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
1169b915e9e0SDimitry Andric
1170145449b1SDimitry Andric // Record the current SCC for higher layers of the CGSCC pass manager now that
1171145449b1SDimitry Andric // all the updates have been applied.
1172b915e9e0SDimitry Andric if (C != &InitialC)
1173b915e9e0SDimitry Andric UR.UpdatedC = C;
1174b915e9e0SDimitry Andric
1175b915e9e0SDimitry Andric return *C;
11765ca98fd9SDimitry Andric }
1177cfca06d7SDimitry Andric
updateCGAndAnalysisManagerForFunctionPass(LazyCallGraph & G,LazyCallGraph::SCC & InitialC,LazyCallGraph::Node & N,CGSCCAnalysisManager & AM,CGSCCUpdateResult & UR,FunctionAnalysisManager & FAM)1178cfca06d7SDimitry Andric LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
1179cfca06d7SDimitry Andric LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
1180cfca06d7SDimitry Andric CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
1181cfca06d7SDimitry Andric FunctionAnalysisManager &FAM) {
1182cfca06d7SDimitry Andric return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM,
1183cfca06d7SDimitry Andric /* FunctionPass */ true);
1184cfca06d7SDimitry Andric }
updateCGAndAnalysisManagerForCGSCCPass(LazyCallGraph & G,LazyCallGraph::SCC & InitialC,LazyCallGraph::Node & N,CGSCCAnalysisManager & AM,CGSCCUpdateResult & UR,FunctionAnalysisManager & FAM)1185cfca06d7SDimitry Andric LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForCGSCCPass(
1186cfca06d7SDimitry Andric LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
1187cfca06d7SDimitry Andric CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
1188cfca06d7SDimitry Andric FunctionAnalysisManager &FAM) {
1189cfca06d7SDimitry Andric return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM,
1190cfca06d7SDimitry Andric /* FunctionPass */ false);
1191cfca06d7SDimitry Andric }
1192