1 //===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Analysis/CGSCCPassManager.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/Optional.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/SetVector.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/iterator_range.h"
17 #include "llvm/Analysis/LazyCallGraph.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/Constant.h"
20 #include "llvm/IR/InstIterator.h"
21 #include "llvm/IR/Instruction.h"
22 #include "llvm/IR/PassManager.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
30 #define DEBUG_TYPE "cgscc"
34 // Explicit template instantiations and specialization definitions for core
38 // Explicit instantiations for the core proxy templates.
39 template class AllAnalysesOn
<LazyCallGraph::SCC
>;
40 template class AnalysisManager
<LazyCallGraph::SCC
, LazyCallGraph
&>;
41 template class PassManager
<LazyCallGraph::SCC
, CGSCCAnalysisManager
,
42 LazyCallGraph
&, CGSCCUpdateResult
&>;
43 template class InnerAnalysisManagerProxy
<CGSCCAnalysisManager
, Module
>;
44 template class OuterAnalysisManagerProxy
<ModuleAnalysisManager
,
45 LazyCallGraph::SCC
, LazyCallGraph
&>;
46 template class OuterAnalysisManagerProxy
<CGSCCAnalysisManager
, Function
>;
48 /// Explicitly specialize the pass manager run method to handle call graph
52 PassManager
<LazyCallGraph::SCC
, CGSCCAnalysisManager
, LazyCallGraph
&,
53 CGSCCUpdateResult
&>::run(LazyCallGraph::SCC
&InitialC
,
54 CGSCCAnalysisManager
&AM
,
55 LazyCallGraph
&G
, CGSCCUpdateResult
&UR
) {
56 // Request PassInstrumentation from analysis manager, will use it to run
57 // instrumenting callbacks for the passes later.
58 PassInstrumentation PI
=
59 AM
.getResult
<PassInstrumentationAnalysis
>(InitialC
, G
);
61 PreservedAnalyses PA
= PreservedAnalyses::all();
64 dbgs() << "Starting CGSCC pass manager run.\n";
66 // The SCC may be refined while we are running passes over it, so set up
67 // a pointer that we can update.
68 LazyCallGraph::SCC
*C
= &InitialC
;
70 for (auto &Pass
: Passes
) {
72 dbgs() << "Running pass: " << Pass
->name() << " on " << *C
<< "\n";
74 // Check the PassInstrumentation's BeforePass callbacks before running the
75 // pass, skip its execution completely if asked to (callback returns false).
76 if (!PI
.runBeforePass(*Pass
, *C
))
79 PreservedAnalyses PassPA
= Pass
->run(*C
, AM
, G
, UR
);
81 if (UR
.InvalidatedSCCs
.count(C
))
82 PI
.runAfterPassInvalidated
<LazyCallGraph::SCC
>(*Pass
);
84 PI
.runAfterPass
<LazyCallGraph::SCC
>(*Pass
, *C
);
86 // Update the SCC if necessary.
87 C
= UR
.UpdatedC
? UR
.UpdatedC
: C
;
89 // If the CGSCC pass wasn't able to provide a valid updated SCC, the
90 // current SCC may simply need to be skipped if invalid.
91 if (UR
.InvalidatedSCCs
.count(C
)) {
92 LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
95 // Check that we didn't miss any update scenario.
96 assert(C
->begin() != C
->end() && "Cannot have an empty SCC!");
98 // Update the analysis manager as each pass runs and potentially
99 // invalidates analyses.
100 AM
.invalidate(*C
, PassPA
);
102 // Finally, we intersect the final preserved analyses to compute the
103 // aggregate preserved set for this pass manager.
104 PA
.intersect(std::move(PassPA
));
106 // FIXME: Historically, the pass managers all called the LLVM context's
107 // yield function here. We don't have a generic way to acquire the
108 // context and it isn't yet clear what the right pattern is for yielding
109 // in the new pass manager so it is currently omitted.
110 // ...getContext().yield();
113 // Invalidation was handled after each pass in the above loop for the current
114 // SCC. Therefore, the remaining analysis results in the AnalysisManager are
115 // preserved. We mark this with a set so that we don't need to inspect each
117 PA
.preserveSet
<AllAnalysesOn
<LazyCallGraph::SCC
>>();
120 dbgs() << "Finished CGSCC pass manager run.\n";
125 bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
126 Module
&M
, const PreservedAnalyses
&PA
,
127 ModuleAnalysisManager::Invalidator
&Inv
) {
128 // If literally everything is preserved, we're done.
129 if (PA
.areAllPreserved())
130 return false; // This is still a valid proxy.
132 // If this proxy or the call graph is going to be invalidated, we also need
133 // to clear all the keys coming from that analysis.
135 // We also directly invalidate the FAM's module proxy if necessary, and if
136 // that proxy isn't preserved we can't preserve this proxy either. We rely on
137 // it to handle module -> function analysis invalidation in the face of
138 // structural changes and so if it's unavailable we conservatively clear the
139 // entire SCC layer as well rather than trying to do invalidation ourselves.
140 auto PAC
= PA
.getChecker
<CGSCCAnalysisManagerModuleProxy
>();
141 if (!(PAC
.preserved() || PAC
.preservedSet
<AllAnalysesOn
<Module
>>()) ||
142 Inv
.invalidate
<LazyCallGraphAnalysis
>(M
, PA
) ||
143 Inv
.invalidate
<FunctionAnalysisManagerModuleProxy
>(M
, PA
)) {
146 // And the proxy itself should be marked as invalid so that we can observe
147 // the new call graph. This isn't strictly necessary because we cheat
148 // above, but is still useful.
152 // Directly check if the relevant set is preserved so we can short circuit
153 // invalidating SCCs below.
154 bool AreSCCAnalysesPreserved
=
155 PA
.allAnalysesInSetPreserved
<AllAnalysesOn
<LazyCallGraph::SCC
>>();
157 // Ok, we have a graph, so we can propagate the invalidation down into it.
159 for (auto &RC
: G
->postorder_ref_sccs())
161 Optional
<PreservedAnalyses
> InnerPA
;
163 // Check to see whether the preserved set needs to be adjusted based on
164 // module-level analysis invalidation triggering deferred invalidation
166 if (auto *OuterProxy
=
167 InnerAM
->getCachedResult
<ModuleAnalysisManagerCGSCCProxy
>(C
))
168 for (const auto &OuterInvalidationPair
:
169 OuterProxy
->getOuterInvalidations()) {
170 AnalysisKey
*OuterAnalysisID
= OuterInvalidationPair
.first
;
171 const auto &InnerAnalysisIDs
= OuterInvalidationPair
.second
;
172 if (Inv
.invalidate(OuterAnalysisID
, M
, PA
)) {
175 for (AnalysisKey
*InnerAnalysisID
: InnerAnalysisIDs
)
176 InnerPA
->abandon(InnerAnalysisID
);
180 // Check if we needed a custom PA set. If so we'll need to run the inner
183 InnerAM
->invalidate(C
, *InnerPA
);
187 // Otherwise we only need to do invalidation if the original PA set didn't
188 // preserve all SCC analyses.
189 if (!AreSCCAnalysesPreserved
)
190 InnerAM
->invalidate(C
, PA
);
193 // Return false to indicate that this result is still a valid proxy.
198 CGSCCAnalysisManagerModuleProxy::Result
199 CGSCCAnalysisManagerModuleProxy::run(Module
&M
, ModuleAnalysisManager
&AM
) {
200 // Force the Function analysis manager to also be available so that it can
201 // be accessed in an SCC analysis and proxied onward to function passes.
202 // FIXME: It is pretty awkward to just drop the result here and assert that
203 // we can find it again later.
204 (void)AM
.getResult
<FunctionAnalysisManagerModuleProxy
>(M
);
206 return Result(*InnerAM
, AM
.getResult
<LazyCallGraphAnalysis
>(M
));
209 AnalysisKey
FunctionAnalysisManagerCGSCCProxy::Key
;
211 FunctionAnalysisManagerCGSCCProxy::Result
212 FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC
&C
,
213 CGSCCAnalysisManager
&AM
,
215 // Collect the FunctionAnalysisManager from the Module layer and use that to
216 // build the proxy result.
218 // This allows us to rely on the FunctionAnalysisMangaerModuleProxy to
219 // invalidate the function analyses.
220 auto &MAM
= AM
.getResult
<ModuleAnalysisManagerCGSCCProxy
>(C
, CG
).getManager();
221 Module
&M
= *C
.begin()->getFunction().getParent();
222 auto *FAMProxy
= MAM
.getCachedResult
<FunctionAnalysisManagerModuleProxy
>(M
);
223 assert(FAMProxy
&& "The CGSCC pass manager requires that the FAM module "
224 "proxy is run on the module prior to entering the CGSCC "
227 // Note that we special-case invalidation handling of this proxy in the CGSCC
228 // analysis manager's Module proxy. This avoids the need to do anything
229 // special here to recompute all of this if ever the FAM's module proxy goes
231 return Result(FAMProxy
->getManager());
234 bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate(
235 LazyCallGraph::SCC
&C
, const PreservedAnalyses
&PA
,
236 CGSCCAnalysisManager::Invalidator
&Inv
) {
237 // If literally everything is preserved, we're done.
238 if (PA
.areAllPreserved())
239 return false; // This is still a valid proxy.
241 // If this proxy isn't marked as preserved, then even if the result remains
242 // valid, the key itself may no longer be valid, so we clear everything.
244 // Note that in order to preserve this proxy, a module pass must ensure that
245 // the FAM has been completely updated to handle the deletion of functions.
246 // Specifically, any FAM-cached results for those functions need to have been
247 // forcibly cleared. When preserved, this proxy will only invalidate results
248 // cached on functions *still in the module* at the end of the module pass.
249 auto PAC
= PA
.getChecker
<FunctionAnalysisManagerCGSCCProxy
>();
250 if (!PAC
.preserved() && !PAC
.preservedSet
<AllAnalysesOn
<LazyCallGraph::SCC
>>()) {
251 for (LazyCallGraph::Node
&N
: C
)
252 FAM
->clear(N
.getFunction(), N
.getFunction().getName());
257 // Directly check if the relevant set is preserved.
258 bool AreFunctionAnalysesPreserved
=
259 PA
.allAnalysesInSetPreserved
<AllAnalysesOn
<Function
>>();
261 // Now walk all the functions to see if any inner analysis invalidation is
263 for (LazyCallGraph::Node
&N
: C
) {
264 Function
&F
= N
.getFunction();
265 Optional
<PreservedAnalyses
> FunctionPA
;
267 // Check to see whether the preserved set needs to be pruned based on
268 // SCC-level analysis invalidation that triggers deferred invalidation
269 // registered with the outer analysis manager proxy for this function.
270 if (auto *OuterProxy
=
271 FAM
->getCachedResult
<CGSCCAnalysisManagerFunctionProxy
>(F
))
272 for (const auto &OuterInvalidationPair
:
273 OuterProxy
->getOuterInvalidations()) {
274 AnalysisKey
*OuterAnalysisID
= OuterInvalidationPair
.first
;
275 const auto &InnerAnalysisIDs
= OuterInvalidationPair
.second
;
276 if (Inv
.invalidate(OuterAnalysisID
, C
, PA
)) {
279 for (AnalysisKey
*InnerAnalysisID
: InnerAnalysisIDs
)
280 FunctionPA
->abandon(InnerAnalysisID
);
284 // Check if we needed a custom PA set, and if so we'll need to run the
285 // inner invalidation.
287 FAM
->invalidate(F
, *FunctionPA
);
291 // Otherwise we only need to do invalidation if the original PA set didn't
292 // preserve all function analyses.
293 if (!AreFunctionAnalysesPreserved
)
294 FAM
->invalidate(F
, PA
);
297 // Return false to indicate that this result is still a valid proxy.
301 } // end namespace llvm
303 /// When a new SCC is created for the graph and there might be function
304 /// analysis results cached for the functions now in that SCC two forms of
305 /// updates are required.
307 /// First, a proxy from the SCC to the FunctionAnalysisManager needs to be
308 /// created so that any subsequent invalidation events to the SCC are
309 /// propagated to the function analysis results cached for functions within it.
311 /// Second, if any of the functions within the SCC have analysis results with
312 /// outer analysis dependencies, then those dependencies would point to the
313 /// *wrong* SCC's analysis result. We forcibly invalidate the necessary
314 /// function analyses so that they don't retain stale handles.
315 static void updateNewSCCFunctionAnalyses(LazyCallGraph::SCC
&C
,
317 CGSCCAnalysisManager
&AM
) {
318 // Get the relevant function analysis manager.
320 AM
.getResult
<FunctionAnalysisManagerCGSCCProxy
>(C
, G
).getManager();
322 // Now walk the functions in this SCC and invalidate any function analysis
323 // results that might have outer dependencies on an SCC analysis.
324 for (LazyCallGraph::Node
&N
: C
) {
325 Function
&F
= N
.getFunction();
328 FAM
.getCachedResult
<CGSCCAnalysisManagerFunctionProxy
>(F
);
330 // No outer analyses were queried, nothing to do.
333 // Forcibly abandon all the inner analyses with dependencies, but
334 // invalidate nothing else.
335 auto PA
= PreservedAnalyses::all();
336 for (const auto &OuterInvalidationPair
:
337 OuterProxy
->getOuterInvalidations()) {
338 const auto &InnerAnalysisIDs
= OuterInvalidationPair
.second
;
339 for (AnalysisKey
*InnerAnalysisID
: InnerAnalysisIDs
)
340 PA
.abandon(InnerAnalysisID
);
343 // Now invalidate anything we found.
344 FAM
.invalidate(F
, PA
);
348 /// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
349 /// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
352 /// The range of new SCCs must be in postorder already. The SCC they were split
353 /// out of must be provided as \p C. The current node being mutated and
354 /// triggering updates must be passed as \p N.
356 /// This function returns the SCC containing \p N. This will be either \p C if
357 /// no new SCCs have been split out, or it will be the new SCC containing \p N.
358 template <typename SCCRangeT
>
359 static LazyCallGraph::SCC
*
360 incorporateNewSCCRange(const SCCRangeT
&NewSCCRange
, LazyCallGraph
&G
,
361 LazyCallGraph::Node
&N
, LazyCallGraph::SCC
*C
,
362 CGSCCAnalysisManager
&AM
, CGSCCUpdateResult
&UR
) {
363 using SCC
= LazyCallGraph::SCC
;
365 if (NewSCCRange
.begin() == NewSCCRange
.end())
368 // Add the current SCC to the worklist as its shape has changed.
369 UR
.CWorklist
.insert(C
);
370 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist:" << *C
375 // Update the current SCC. Note that if we have new SCCs, this must actually
377 assert(C
!= &*NewSCCRange
.begin() &&
378 "Cannot insert new SCCs without changing current SCC!");
379 C
= &*NewSCCRange
.begin();
380 assert(G
.lookupSCC(N
) == C
&& "Failed to update current SCC!");
382 // If we had a cached FAM proxy originally, we will want to create more of
383 // them for each SCC that was split off.
385 AM
.getCachedResult
<FunctionAnalysisManagerCGSCCProxy
>(*OldC
) != nullptr;
387 // We need to propagate an invalidation call to all but the newly current SCC
388 // because the outer pass manager won't do that for us after splitting them.
389 // FIXME: We should accept a PreservedAnalysis from the CG updater so that if
390 // there are preserved analysis we can avoid invalidating them here for
392 // We know however that this will preserve any FAM proxy so go ahead and mark
394 PreservedAnalyses PA
;
395 PA
.preserve
<FunctionAnalysisManagerCGSCCProxy
>();
396 AM
.invalidate(*OldC
, PA
);
398 // Ensure the now-current SCC's function analyses are updated.
400 updateNewSCCFunctionAnalyses(*C
, G
, AM
);
402 for (SCC
&NewC
: llvm::reverse(make_range(std::next(NewSCCRange
.begin()),
403 NewSCCRange
.end()))) {
404 assert(C
!= &NewC
&& "No need to re-visit the current SCC!");
405 assert(OldC
!= &NewC
&& "Already handled the original SCC!");
406 UR
.CWorklist
.insert(&NewC
);
407 LLVM_DEBUG(dbgs() << "Enqueuing a newly formed SCC:" << NewC
<< "\n");
409 // Ensure new SCCs' function analyses are updated.
411 updateNewSCCFunctionAnalyses(NewC
, G
, AM
);
413 // Also propagate a normal invalidation to the new SCC as only the current
414 // will get one from the pass manager infrastructure.
415 AM
.invalidate(NewC
, PA
);
420 LazyCallGraph::SCC
&llvm::updateCGAndAnalysisManagerForFunctionPass(
421 LazyCallGraph
&G
, LazyCallGraph::SCC
&InitialC
, LazyCallGraph::Node
&N
,
422 CGSCCAnalysisManager
&AM
, CGSCCUpdateResult
&UR
) {
423 using Node
= LazyCallGraph::Node
;
424 using Edge
= LazyCallGraph::Edge
;
425 using SCC
= LazyCallGraph::SCC
;
426 using RefSCC
= LazyCallGraph::RefSCC
;
428 RefSCC
&InitialRC
= InitialC
.getOuterRefSCC();
430 RefSCC
*RC
= &InitialRC
;
431 Function
&F
= N
.getFunction();
433 // Walk the function body and build up the set of retained, promoted, and
435 SmallVector
<Constant
*, 16> Worklist
;
436 SmallPtrSet
<Constant
*, 16> Visited
;
437 SmallPtrSet
<Node
*, 16> RetainedEdges
;
438 SmallSetVector
<Node
*, 4> PromotedRefTargets
;
439 SmallSetVector
<Node
*, 4> DemotedCallTargets
;
441 // First walk the function and handle all called functions. We do this first
442 // because if there is a single call edge, whether there are ref edges is
444 for (Instruction
&I
: instructions(F
))
445 if (auto CS
= CallSite(&I
))
446 if (Function
*Callee
= CS
.getCalledFunction())
447 if (Visited
.insert(Callee
).second
&& !Callee
->isDeclaration()) {
448 Node
&CalleeN
= *G
.lookup(*Callee
);
449 Edge
*E
= N
->lookup(CalleeN
);
450 // FIXME: We should really handle adding new calls. While it will
451 // make downstream usage more complex, there is no fundamental
452 // limitation and it will allow passes within the CGSCC to be a bit
453 // more flexible in what transforms they can do. Until then, we
454 // verify that new calls haven't been introduced.
455 assert(E
&& "No function transformations should introduce *new* "
456 "call edges! Any new calls should be modeled as "
457 "promoted existing ref edges!");
458 bool Inserted
= RetainedEdges
.insert(&CalleeN
).second
;
460 assert(Inserted
&& "We should never visit a function twice.");
462 PromotedRefTargets
.insert(&CalleeN
);
465 // Now walk all references.
466 for (Instruction
&I
: instructions(F
))
467 for (Value
*Op
: I
.operand_values())
468 if (auto *C
= dyn_cast
<Constant
>(Op
))
469 if (Visited
.insert(C
).second
)
470 Worklist
.push_back(C
);
472 auto VisitRef
= [&](Function
&Referee
) {
473 Node
&RefereeN
= *G
.lookup(Referee
);
474 Edge
*E
= N
->lookup(RefereeN
);
475 // FIXME: Similarly to new calls, we also currently preclude
476 // introducing new references. See above for details.
477 assert(E
&& "No function transformations should introduce *new* ref "
478 "edges! Any new ref edges would require IPO which "
479 "function passes aren't allowed to do!");
480 bool Inserted
= RetainedEdges
.insert(&RefereeN
).second
;
482 assert(Inserted
&& "We should never visit a function twice.");
484 DemotedCallTargets
.insert(&RefereeN
);
486 LazyCallGraph::visitReferences(Worklist
, Visited
, VisitRef
);
488 // Include synthetic reference edges to known, defined lib functions.
489 for (auto *F
: G
.getLibFunctions())
490 // While the list of lib functions doesn't have repeats, don't re-visit
491 // anything handled above.
492 if (!Visited
.count(F
))
495 // First remove all of the edges that are no longer present in this function.
496 // The first step makes these edges uniformly ref edges and accumulates them
497 // into a separate data structure so removal doesn't invalidate anything.
498 SmallVector
<Node
*, 4> DeadTargets
;
500 if (RetainedEdges
.count(&E
.getNode()))
503 SCC
&TargetC
= *G
.lookupSCC(E
.getNode());
504 RefSCC
&TargetRC
= TargetC
.getOuterRefSCC();
505 if (&TargetRC
== RC
&& E
.isCall()) {
507 // For separate SCCs this is trivial.
508 RC
->switchTrivialInternalEdgeToRef(N
, E
.getNode());
510 // Now update the call graph.
511 C
= incorporateNewSCCRange(RC
->switchInternalEdgeToRef(N
, E
.getNode()),
516 // Now that this is ready for actual removal, put it into our list.
517 DeadTargets
.push_back(&E
.getNode());
519 // Remove the easy cases quickly and actually pull them out of our list.
521 llvm::remove_if(DeadTargets
,
523 SCC
&TargetC
= *G
.lookupSCC(*TargetN
);
524 RefSCC
&TargetRC
= TargetC
.getOuterRefSCC();
526 // We can't trivially remove internal targets, so skip
531 RC
->removeOutgoingEdge(N
, *TargetN
);
532 LLVM_DEBUG(dbgs() << "Deleting outgoing edge from '"
533 << N
<< "' to '" << TargetN
<< "'\n");
538 // Now do a batch removal of the internal ref edges left.
539 auto NewRefSCCs
= RC
->removeInternalRefEdge(N
, DeadTargets
);
540 if (!NewRefSCCs
.empty()) {
541 // The old RefSCC is dead, mark it as such.
542 UR
.InvalidatedRefSCCs
.insert(RC
);
544 // Note that we don't bother to invalidate analyses as ref-edge
545 // connectivity is not really observable in any way and is intended
546 // exclusively to be used for ordering of transforms rather than for
547 // analysis conclusions.
549 // Update RC to the "bottom".
550 assert(G
.lookupSCC(N
) == C
&& "Changed the SCC when splitting RefSCCs!");
551 RC
= &C
->getOuterRefSCC();
552 assert(G
.lookupRefSCC(N
) == RC
&& "Failed to update current RefSCC!");
554 // The RC worklist is in reverse postorder, so we enqueue the new ones in
555 // RPO except for the one which contains the source node as that is the
556 // "bottom" we will continue processing in the bottom-up walk.
557 assert(NewRefSCCs
.front() == RC
&&
558 "New current RefSCC not first in the returned list!");
559 for (RefSCC
*NewRC
: llvm::reverse(make_range(std::next(NewRefSCCs
.begin()),
560 NewRefSCCs
.end()))) {
561 assert(NewRC
!= RC
&& "Should not encounter the current RefSCC further "
562 "in the postorder list of new RefSCCs.");
563 UR
.RCWorklist
.insert(NewRC
);
564 LLVM_DEBUG(dbgs() << "Enqueuing a new RefSCC in the update worklist: "
569 // Next demote all the call edges that are now ref edges. This helps make
570 // the SCCs small which should minimize the work below as we don't want to
571 // form cycles that this would break.
572 for (Node
*RefTarget
: DemotedCallTargets
) {
573 SCC
&TargetC
= *G
.lookupSCC(*RefTarget
);
574 RefSCC
&TargetRC
= TargetC
.getOuterRefSCC();
576 // The easy case is when the target RefSCC is not this RefSCC. This is
577 // only supported when the target RefSCC is a child of this RefSCC.
578 if (&TargetRC
!= RC
) {
579 assert(RC
->isAncestorOf(TargetRC
) &&
580 "Cannot potentially form RefSCC cycles here!");
581 RC
->switchOutgoingEdgeToRef(N
, *RefTarget
);
582 LLVM_DEBUG(dbgs() << "Switch outgoing call edge to a ref edge from '" << N
583 << "' to '" << *RefTarget
<< "'\n");
587 // We are switching an internal call edge to a ref edge. This may split up
590 // For separate SCCs this is trivial.
591 RC
->switchTrivialInternalEdgeToRef(N
, *RefTarget
);
595 // Now update the call graph.
596 C
= incorporateNewSCCRange(RC
->switchInternalEdgeToRef(N
, *RefTarget
), G
, N
,
600 // Now promote ref edges into call edges.
601 for (Node
*CallTarget
: PromotedRefTargets
) {
602 SCC
&TargetC
= *G
.lookupSCC(*CallTarget
);
603 RefSCC
&TargetRC
= TargetC
.getOuterRefSCC();
605 // The easy case is when the target RefSCC is not this RefSCC. This is
606 // only supported when the target RefSCC is a child of this RefSCC.
607 if (&TargetRC
!= RC
) {
608 assert(RC
->isAncestorOf(TargetRC
) &&
609 "Cannot potentially form RefSCC cycles here!");
610 RC
->switchOutgoingEdgeToCall(N
, *CallTarget
);
611 LLVM_DEBUG(dbgs() << "Switch outgoing ref edge to a call edge from '" << N
612 << "' to '" << *CallTarget
<< "'\n");
615 LLVM_DEBUG(dbgs() << "Switch an internal ref edge to a call edge from '"
616 << N
<< "' to '" << *CallTarget
<< "'\n");
618 // Otherwise we are switching an internal ref edge to a call edge. This
619 // may merge away some SCCs, and we add those to the UpdateResult. We also
620 // need to make sure to update the worklist in the event SCCs have moved
621 // before the current one in the post-order sequence
622 bool HasFunctionAnalysisProxy
= false;
623 auto InitialSCCIndex
= RC
->find(*C
) - RC
->begin();
624 bool FormedCycle
= RC
->switchInternalEdgeToCall(
625 N
, *CallTarget
, [&](ArrayRef
<SCC
*> MergedSCCs
) {
626 for (SCC
*MergedC
: MergedSCCs
) {
627 assert(MergedC
!= &TargetC
&& "Cannot merge away the target SCC!");
629 HasFunctionAnalysisProxy
|=
630 AM
.getCachedResult
<FunctionAnalysisManagerCGSCCProxy
>(
631 *MergedC
) != nullptr;
633 // Mark that this SCC will no longer be valid.
634 UR
.InvalidatedSCCs
.insert(MergedC
);
636 // FIXME: We should really do a 'clear' here to forcibly release
637 // memory, but we don't have a good way of doing that and
638 // preserving the function analyses.
639 auto PA
= PreservedAnalyses::allInSet
<AllAnalysesOn
<Function
>>();
640 PA
.preserve
<FunctionAnalysisManagerCGSCCProxy
>();
641 AM
.invalidate(*MergedC
, PA
);
645 // If we formed a cycle by creating this call, we need to update more data
649 assert(G
.lookupSCC(N
) == C
&& "Failed to update current SCC!");
651 // If one of the invalidated SCCs had a cached proxy to a function
652 // analysis manager, we need to create a proxy in the new current SCC as
653 // the invalidated SCCs had their functions moved.
654 if (HasFunctionAnalysisProxy
)
655 AM
.getResult
<FunctionAnalysisManagerCGSCCProxy
>(*C
, G
);
657 // Any analyses cached for this SCC are no longer precise as the shape
658 // has changed by introducing this cycle. However, we have taken care to
659 // update the proxies so it remains valide.
660 auto PA
= PreservedAnalyses::allInSet
<AllAnalysesOn
<Function
>>();
661 PA
.preserve
<FunctionAnalysisManagerCGSCCProxy
>();
662 AM
.invalidate(*C
, PA
);
664 auto NewSCCIndex
= RC
->find(*C
) - RC
->begin();
665 // If we have actually moved an SCC to be topologically "below" the current
666 // one due to merging, we will need to revisit the current SCC after
667 // visiting those moved SCCs.
669 // It is critical that we *do not* revisit the current SCC unless we
670 // actually move SCCs in the process of merging because otherwise we may
671 // form a cycle where an SCC is split apart, merged, split, merged and so
673 if (InitialSCCIndex
< NewSCCIndex
) {
674 // Put our current SCC back onto the worklist as we'll visit other SCCs
675 // that are now definitively ordered prior to the current one in the
676 // post-order sequence, and may end up observing more precise context to
677 // optimize the current SCC.
678 UR
.CWorklist
.insert(C
);
679 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist: " << *C
681 // Enqueue in reverse order as we pop off the back of the worklist.
682 for (SCC
&MovedC
: llvm::reverse(make_range(RC
->begin() + InitialSCCIndex
,
683 RC
->begin() + NewSCCIndex
))) {
684 UR
.CWorklist
.insert(&MovedC
);
685 LLVM_DEBUG(dbgs() << "Enqueuing a newly earlier in post-order SCC: "
691 assert(!UR
.InvalidatedSCCs
.count(C
) && "Invalidated the current SCC!");
692 assert(!UR
.InvalidatedRefSCCs
.count(RC
) && "Invalidated the current RefSCC!");
693 assert(&C
->getOuterRefSCC() == RC
&& "Current SCC not in current RefSCC!");
695 // Record the current RefSCC and SCC for higher layers of the CGSCC pass
696 // manager now that all the updates have been applied.
697 if (RC
!= &InitialRC
)