1 //===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #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/IR/PassManagerImpl.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 #include <cassert>
29 #include <iterator>
30 
31 #define DEBUG_TYPE "cgscc"
32 
33 using namespace llvm;
34 
35 // Explicit template instantiations and specialization definitions for core
36 // template typedefs.
37 namespace llvm {
38 
39 // Explicit instantiations for the core proxy templates.
40 template class AllAnalysesOn<LazyCallGraph::SCC>;
41 template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
42 template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
43                            LazyCallGraph &, CGSCCUpdateResult &>;
44 template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
45 template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
46                                          LazyCallGraph::SCC, LazyCallGraph &>;
47 template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
48 
49 /// Explicitly specialize the pass manager run method to handle call graph
50 /// updates.
51 template <>
52 PreservedAnalyses
53 PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
54             CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
55                                       CGSCCAnalysisManager &AM,
56                                       LazyCallGraph &G, CGSCCUpdateResult &UR) {
57   // Request PassInstrumentation from analysis manager, will use it to run
58   // instrumenting callbacks for the passes later.
59   PassInstrumentation PI =
60       AM.getResult<PassInstrumentationAnalysis>(InitialC, G);
61 
62   PreservedAnalyses PA = PreservedAnalyses::all();
63 
64   if (DebugLogging)
65     dbgs() << "Starting CGSCC pass manager run.\n";
66 
67   // The SCC may be refined while we are running passes over it, so set up
68   // a pointer that we can update.
69   LazyCallGraph::SCC *C = &InitialC;
70 
71   for (auto &Pass : Passes) {
72     if (DebugLogging)
73       dbgs() << "Running pass: " << Pass->name() << " on " << *C << "\n";
74 
75     // Check the PassInstrumentation's BeforePass callbacks before running the
76     // pass, skip its execution completely if asked to (callback returns false).
77     if (!PI.runBeforePass(*Pass, *C))
78       continue;
79 
80     PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR);
81 
82     if (UR.InvalidatedSCCs.count(C))
83       PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass);
84     else
85       PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C);
86 
87     // Update the SCC if necessary.
88     C = UR.UpdatedC ? UR.UpdatedC : C;
89 
90     // If the CGSCC pass wasn't able to provide a valid updated SCC, the
91     // current SCC may simply need to be skipped if invalid.
92     if (UR.InvalidatedSCCs.count(C)) {
93       LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
94       break;
95     }
96     // Check that we didn't miss any update scenario.
97     assert(C->begin() != C->end() && "Cannot have an empty SCC!");
98 
99     // Update the analysis manager as each pass runs and potentially
100     // invalidates analyses.
101     AM.invalidate(*C, PassPA);
102 
103     // Finally, we intersect the final preserved analyses to compute the
104     // aggregate preserved set for this pass manager.
105     PA.intersect(std::move(PassPA));
106 
107     // FIXME: Historically, the pass managers all called the LLVM context's
108     // yield function here. We don't have a generic way to acquire the
109     // context and it isn't yet clear what the right pattern is for yielding
110     // in the new pass manager so it is currently omitted.
111     // ...getContext().yield();
112   }
113 
114   // Before we mark all of *this* SCC's analyses as preserved below, intersect
115   // this with the cross-SCC preserved analysis set. This is used to allow
116   // CGSCC passes to mutate ancestor SCCs and still trigger proper invalidation
117   // for them.
118   UR.CrossSCCPA.intersect(PA);
119 
120   // Invalidation was handled after each pass in the above loop for the current
121   // SCC. Therefore, the remaining analysis results in the AnalysisManager are
122   // preserved. We mark this with a set so that we don't need to inspect each
123   // one individually.
124   PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>();
125 
126   if (DebugLogging)
127     dbgs() << "Finished CGSCC pass manager run.\n";
128 
129   return PA;
130 }
131 
132 bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
133     Module &M, const PreservedAnalyses &PA,
134     ModuleAnalysisManager::Invalidator &Inv) {
135   // If literally everything is preserved, we're done.
136   if (PA.areAllPreserved())
137     return false; // This is still a valid proxy.
138 
139   // If this proxy or the call graph is going to be invalidated, we also need
140   // to clear all the keys coming from that analysis.
141   //
142   // We also directly invalidate the FAM's module proxy if necessary, and if
143   // that proxy isn't preserved we can't preserve this proxy either. We rely on
144   // it to handle module -> function analysis invalidation in the face of
145   // structural changes and so if it's unavailable we conservatively clear the
146   // entire SCC layer as well rather than trying to do invalidation ourselves.
147   auto PAC = PA.getChecker<CGSCCAnalysisManagerModuleProxy>();
148   if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>()) ||
149       Inv.invalidate<LazyCallGraphAnalysis>(M, PA) ||
150       Inv.invalidate<FunctionAnalysisManagerModuleProxy>(M, PA)) {
151     InnerAM->clear();
152 
153     // And the proxy itself should be marked as invalid so that we can observe
154     // the new call graph. This isn't strictly necessary because we cheat
155     // above, but is still useful.
156     return true;
157   }
158 
159   // Directly check if the relevant set is preserved so we can short circuit
160   // invalidating SCCs below.
161   bool AreSCCAnalysesPreserved =
162       PA.allAnalysesInSetPreserved<AllAnalysesOn<LazyCallGraph::SCC>>();
163 
164   // Ok, we have a graph, so we can propagate the invalidation down into it.
165   G->buildRefSCCs();
166   for (auto &RC : G->postorder_ref_sccs())
167     for (auto &C : RC) {
168       Optional<PreservedAnalyses> InnerPA;
169 
170       // Check to see whether the preserved set needs to be adjusted based on
171       // module-level analysis invalidation triggering deferred invalidation
172       // for this SCC.
173       if (auto *OuterProxy =
174               InnerAM->getCachedResult<ModuleAnalysisManagerCGSCCProxy>(C))
175         for (const auto &OuterInvalidationPair :
176              OuterProxy->getOuterInvalidations()) {
177           AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
178           const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
179           if (Inv.invalidate(OuterAnalysisID, M, PA)) {
180             if (!InnerPA)
181               InnerPA = PA;
182             for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
183               InnerPA->abandon(InnerAnalysisID);
184           }
185         }
186 
187       // Check if we needed a custom PA set. If so we'll need to run the inner
188       // invalidation.
189       if (InnerPA) {
190         InnerAM->invalidate(C, *InnerPA);
191         continue;
192       }
193 
194       // Otherwise we only need to do invalidation if the original PA set didn't
195       // preserve all SCC analyses.
196       if (!AreSCCAnalysesPreserved)
197         InnerAM->invalidate(C, PA);
198     }
199 
200   // Return false to indicate that this result is still a valid proxy.
201   return false;
202 }
203 
204 template <>
205 CGSCCAnalysisManagerModuleProxy::Result
206 CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM) {
207   // Force the Function analysis manager to also be available so that it can
208   // be accessed in an SCC analysis and proxied onward to function passes.
209   // FIXME: It is pretty awkward to just drop the result here and assert that
210   // we can find it again later.
211   (void)AM.getResult<FunctionAnalysisManagerModuleProxy>(M);
212 
213   return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M));
214 }
215 
216 AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key;
217 
218 FunctionAnalysisManagerCGSCCProxy::Result
219 FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C,
220                                        CGSCCAnalysisManager &AM,
221                                        LazyCallGraph &CG) {
222   // Collect the FunctionAnalysisManager from the Module layer and use that to
223   // build the proxy result.
224   //
225   // This allows us to rely on the FunctionAnalysisMangaerModuleProxy to
226   // invalidate the function analyses.
227   auto &MAM = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG).getManager();
228   Module &M = *C.begin()->getFunction().getParent();
229   auto *FAMProxy = MAM.getCachedResult<FunctionAnalysisManagerModuleProxy>(M);
230   assert(FAMProxy && "The CGSCC pass manager requires that the FAM module "
231                      "proxy is run on the module prior to entering the CGSCC "
232                      "walk.");
233 
234   // Note that we special-case invalidation handling of this proxy in the CGSCC
235   // analysis manager's Module proxy. This avoids the need to do anything
236   // special here to recompute all of this if ever the FAM's module proxy goes
237   // away.
238   return Result(FAMProxy->getManager());
239 }
240 
241 bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate(
242     LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
243     CGSCCAnalysisManager::Invalidator &Inv) {
244   // If literally everything is preserved, we're done.
245   if (PA.areAllPreserved())
246     return false; // This is still a valid proxy.
247 
248   // If this proxy isn't marked as preserved, then even if the result remains
249   // valid, the key itself may no longer be valid, so we clear everything.
250   //
251   // Note that in order to preserve this proxy, a module pass must ensure that
252   // the FAM has been completely updated to handle the deletion of functions.
253   // Specifically, any FAM-cached results for those functions need to have been
254   // forcibly cleared. When preserved, this proxy will only invalidate results
255   // cached on functions *still in the module* at the end of the module pass.
256   auto PAC = PA.getChecker<FunctionAnalysisManagerCGSCCProxy>();
257   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<LazyCallGraph::SCC>>()) {
258     for (LazyCallGraph::Node &N : C)
259       FAM->clear(N.getFunction(), N.getFunction().getName());
260 
261     return true;
262   }
263 
264   // Directly check if the relevant set is preserved.
265   bool AreFunctionAnalysesPreserved =
266       PA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>();
267 
268   // Now walk all the functions to see if any inner analysis invalidation is
269   // necessary.
270   for (LazyCallGraph::Node &N : C) {
271     Function &F = N.getFunction();
272     Optional<PreservedAnalyses> FunctionPA;
273 
274     // Check to see whether the preserved set needs to be pruned based on
275     // SCC-level analysis invalidation that triggers deferred invalidation
276     // registered with the outer analysis manager proxy for this function.
277     if (auto *OuterProxy =
278             FAM->getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F))
279       for (const auto &OuterInvalidationPair :
280            OuterProxy->getOuterInvalidations()) {
281         AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
282         const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
283         if (Inv.invalidate(OuterAnalysisID, C, PA)) {
284           if (!FunctionPA)
285             FunctionPA = PA;
286           for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
287             FunctionPA->abandon(InnerAnalysisID);
288         }
289       }
290 
291     // Check if we needed a custom PA set, and if so we'll need to run the
292     // inner invalidation.
293     if (FunctionPA) {
294       FAM->invalidate(F, *FunctionPA);
295       continue;
296     }
297 
298     // Otherwise we only need to do invalidation if the original PA set didn't
299     // preserve all function analyses.
300     if (!AreFunctionAnalysesPreserved)
301       FAM->invalidate(F, PA);
302   }
303 
304   // Return false to indicate that this result is still a valid proxy.
305   return false;
306 }
307 
308 } // end namespace llvm
309 
310 /// When a new SCC is created for the graph and there might be function
311 /// analysis results cached for the functions now in that SCC two forms of
312 /// updates are required.
313 ///
314 /// First, a proxy from the SCC to the FunctionAnalysisManager needs to be
315 /// created so that any subsequent invalidation events to the SCC are
316 /// propagated to the function analysis results cached for functions within it.
317 ///
318 /// Second, if any of the functions within the SCC have analysis results with
319 /// outer analysis dependencies, then those dependencies would point to the
320 /// *wrong* SCC's analysis result. We forcibly invalidate the necessary
321 /// function analyses so that they don't retain stale handles.
322 static void updateNewSCCFunctionAnalyses(LazyCallGraph::SCC &C,
323                                          LazyCallGraph &G,
324                                          CGSCCAnalysisManager &AM) {
325   // Get the relevant function analysis manager.
326   auto &FAM =
327       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, G).getManager();
328 
329   // Now walk the functions in this SCC and invalidate any function analysis
330   // results that might have outer dependencies on an SCC analysis.
331   for (LazyCallGraph::Node &N : C) {
332     Function &F = N.getFunction();
333 
334     auto *OuterProxy =
335         FAM.getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F);
336     if (!OuterProxy)
337       // No outer analyses were queried, nothing to do.
338       continue;
339 
340     // Forcibly abandon all the inner analyses with dependencies, but
341     // invalidate nothing else.
342     auto PA = PreservedAnalyses::all();
343     for (const auto &OuterInvalidationPair :
344          OuterProxy->getOuterInvalidations()) {
345       const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
346       for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
347         PA.abandon(InnerAnalysisID);
348     }
349 
350     // Now invalidate anything we found.
351     FAM.invalidate(F, PA);
352   }
353 }
354 
355 /// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
356 /// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
357 /// added SCCs.
358 ///
359 /// The range of new SCCs must be in postorder already. The SCC they were split
360 /// out of must be provided as \p C. The current node being mutated and
361 /// triggering updates must be passed as \p N.
362 ///
363 /// This function returns the SCC containing \p N. This will be either \p C if
364 /// no new SCCs have been split out, or it will be the new SCC containing \p N.
365 template <typename SCCRangeT>
366 static LazyCallGraph::SCC *
367 incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
368                        LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
369                        CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
370   using SCC = LazyCallGraph::SCC;
371 
372   if (NewSCCRange.begin() == NewSCCRange.end())
373     return C;
374 
375   // Add the current SCC to the worklist as its shape has changed.
376   UR.CWorklist.insert(C);
377   LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist:" << *C
378                     << "\n");
379 
380   SCC *OldC = C;
381 
382   // Update the current SCC. Note that if we have new SCCs, this must actually
383   // change the SCC.
384   assert(C != &*NewSCCRange.begin() &&
385          "Cannot insert new SCCs without changing current SCC!");
386   C = &*NewSCCRange.begin();
387   assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
388 
389   // If we had a cached FAM proxy originally, we will want to create more of
390   // them for each SCC that was split off.
391   bool NeedFAMProxy =
392       AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*OldC) != nullptr;
393 
394   // We need to propagate an invalidation call to all but the newly current SCC
395   // because the outer pass manager won't do that for us after splitting them.
396   // FIXME: We should accept a PreservedAnalysis from the CG updater so that if
397   // there are preserved analysis we can avoid invalidating them here for
398   // split-off SCCs.
399   // We know however that this will preserve any FAM proxy so go ahead and mark
400   // that.
401   PreservedAnalyses PA;
402   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
403   AM.invalidate(*OldC, PA);
404 
405   // Ensure the now-current SCC's function analyses are updated.
406   if (NeedFAMProxy)
407     updateNewSCCFunctionAnalyses(*C, G, AM);
408 
409   for (SCC &NewC : llvm::reverse(make_range(std::next(NewSCCRange.begin()),
410                                             NewSCCRange.end()))) {
411     assert(C != &NewC && "No need to re-visit the current SCC!");
412     assert(OldC != &NewC && "Already handled the original SCC!");
413     UR.CWorklist.insert(&NewC);
414     LLVM_DEBUG(dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n");
415 
416     // Ensure new SCCs' function analyses are updated.
417     if (NeedFAMProxy)
418       updateNewSCCFunctionAnalyses(NewC, G, AM);
419 
420     // Also propagate a normal invalidation to the new SCC as only the current
421     // will get one from the pass manager infrastructure.
422     AM.invalidate(NewC, PA);
423   }
424   return C;
425 }
426 
427 static LazyCallGraph::SCC &updateCGAndAnalysisManagerForPass(
428     LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
429     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, bool FunctionPass) {
430   using Node = LazyCallGraph::Node;
431   using Edge = LazyCallGraph::Edge;
432   using SCC = LazyCallGraph::SCC;
433   using RefSCC = LazyCallGraph::RefSCC;
434 
435   RefSCC &InitialRC = InitialC.getOuterRefSCC();
436   SCC *C = &InitialC;
437   RefSCC *RC = &InitialRC;
438   Function &F = N.getFunction();
439 
440   // Walk the function body and build up the set of retained, promoted, and
441   // demoted edges.
442   SmallVector<Constant *, 16> Worklist;
443   SmallPtrSet<Constant *, 16> Visited;
444   SmallPtrSet<Node *, 16> RetainedEdges;
445   SmallSetVector<Node *, 4> PromotedRefTargets;
446   SmallSetVector<Node *, 4> DemotedCallTargets;
447   SmallSetVector<Node *, 4> NewCallEdges;
448   SmallSetVector<Node *, 4> NewRefEdges;
449 
450   // First walk the function and handle all called functions. We do this first
451   // because if there is a single call edge, whether there are ref edges is
452   // irrelevant.
453   for (Instruction &I : instructions(F))
454     if (auto CS = CallSite(&I))
455       if (Function *Callee = CS.getCalledFunction())
456         if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
457           Node &CalleeN = *G.lookup(*Callee);
458           Edge *E = N->lookup(CalleeN);
459           assert((E || !FunctionPass) &&
460                  "No function transformations should introduce *new* "
461                  "call edges! Any new calls should be modeled as "
462                  "promoted existing ref edges!");
463           bool Inserted = RetainedEdges.insert(&CalleeN).second;
464           (void)Inserted;
465           assert(Inserted && "We should never visit a function twice.");
466           if (!E)
467             NewCallEdges.insert(&CalleeN);
468           else if (!E->isCall())
469             PromotedRefTargets.insert(&CalleeN);
470         }
471 
472   // Now walk all references.
473   for (Instruction &I : instructions(F))
474     for (Value *Op : I.operand_values())
475       if (auto *C = dyn_cast<Constant>(Op))
476         if (Visited.insert(C).second)
477           Worklist.push_back(C);
478 
479   auto VisitRef = [&](Function &Referee) {
480     Node &RefereeN = *G.lookup(Referee);
481     Edge *E = N->lookup(RefereeN);
482     assert((E || !FunctionPass) &&
483            "No function transformations should introduce *new* ref "
484            "edges! Any new ref edges would require IPO which "
485            "function passes aren't allowed to do!");
486     bool Inserted = RetainedEdges.insert(&RefereeN).second;
487     (void)Inserted;
488     assert(Inserted && "We should never visit a function twice.");
489     if (!E)
490       NewRefEdges.insert(&RefereeN);
491     else if (E->isCall())
492       DemotedCallTargets.insert(&RefereeN);
493   };
494   LazyCallGraph::visitReferences(Worklist, Visited, VisitRef);
495 
496   // Handle new ref edges.
497   for (Node *RefTarget : NewRefEdges) {
498     SCC &TargetC = *G.lookupSCC(*RefTarget);
499     RefSCC &TargetRC = TargetC.getOuterRefSCC();
500     (void)TargetRC;
501     // TODO: This only allows trivial edges to be added for now.
502     assert((RC == &TargetRC ||
503            RC->isAncestorOf(TargetRC)) && "New ref edge is not trivial!");
504     RC->insertTrivialRefEdge(N, *RefTarget);
505   }
506 
507   // Handle new call edges.
508   for (Node *CallTarget : NewCallEdges) {
509     SCC &TargetC = *G.lookupSCC(*CallTarget);
510     RefSCC &TargetRC = TargetC.getOuterRefSCC();
511     (void)TargetRC;
512     // TODO: This only allows trivial edges to be added for now.
513     assert((RC == &TargetRC ||
514            RC->isAncestorOf(TargetRC)) && "New call edge is not trivial!");
515     RC->insertTrivialCallEdge(N, *CallTarget);
516   }
517 
518   // Include synthetic reference edges to known, defined lib functions.
519   for (auto *F : G.getLibFunctions())
520     // While the list of lib functions doesn't have repeats, don't re-visit
521     // anything handled above.
522     if (!Visited.count(F))
523       VisitRef(*F);
524 
525   // First remove all of the edges that are no longer present in this function.
526   // The first step makes these edges uniformly ref edges and accumulates them
527   // into a separate data structure so removal doesn't invalidate anything.
528   SmallVector<Node *, 4> DeadTargets;
529   for (Edge &E : *N) {
530     if (RetainedEdges.count(&E.getNode()))
531       continue;
532 
533     SCC &TargetC = *G.lookupSCC(E.getNode());
534     RefSCC &TargetRC = TargetC.getOuterRefSCC();
535     if (&TargetRC == RC && E.isCall()) {
536       if (C != &TargetC) {
537         // For separate SCCs this is trivial.
538         RC->switchTrivialInternalEdgeToRef(N, E.getNode());
539       } else {
540         // Now update the call graph.
541         C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, E.getNode()),
542                                    G, N, C, AM, UR);
543       }
544     }
545 
546     // Now that this is ready for actual removal, put it into our list.
547     DeadTargets.push_back(&E.getNode());
548   }
549   // Remove the easy cases quickly and actually pull them out of our list.
550   DeadTargets.erase(
551       llvm::remove_if(DeadTargets,
552                       [&](Node *TargetN) {
553                         SCC &TargetC = *G.lookupSCC(*TargetN);
554                         RefSCC &TargetRC = TargetC.getOuterRefSCC();
555 
556                         // We can't trivially remove internal targets, so skip
557                         // those.
558                         if (&TargetRC == RC)
559                           return false;
560 
561                         RC->removeOutgoingEdge(N, *TargetN);
562                         LLVM_DEBUG(dbgs() << "Deleting outgoing edge from '"
563                                           << N << "' to '" << TargetN << "'\n");
564                         return true;
565                       }),
566       DeadTargets.end());
567 
568   // Now do a batch removal of the internal ref edges left.
569   auto NewRefSCCs = RC->removeInternalRefEdge(N, DeadTargets);
570   if (!NewRefSCCs.empty()) {
571     // The old RefSCC is dead, mark it as such.
572     UR.InvalidatedRefSCCs.insert(RC);
573 
574     // Note that we don't bother to invalidate analyses as ref-edge
575     // connectivity is not really observable in any way and is intended
576     // exclusively to be used for ordering of transforms rather than for
577     // analysis conclusions.
578 
579     // Update RC to the "bottom".
580     assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
581     RC = &C->getOuterRefSCC();
582     assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
583 
584     // The RC worklist is in reverse postorder, so we enqueue the new ones in
585     // RPO except for the one which contains the source node as that is the
586     // "bottom" we will continue processing in the bottom-up walk.
587     assert(NewRefSCCs.front() == RC &&
588            "New current RefSCC not first in the returned list!");
589     for (RefSCC *NewRC : llvm::reverse(make_range(std::next(NewRefSCCs.begin()),
590                                                   NewRefSCCs.end()))) {
591       assert(NewRC != RC && "Should not encounter the current RefSCC further "
592                             "in the postorder list of new RefSCCs.");
593       UR.RCWorklist.insert(NewRC);
594       LLVM_DEBUG(dbgs() << "Enqueuing a new RefSCC in the update worklist: "
595                         << *NewRC << "\n");
596     }
597   }
598 
599   // Next demote all the call edges that are now ref edges. This helps make
600   // the SCCs small which should minimize the work below as we don't want to
601   // form cycles that this would break.
602   for (Node *RefTarget : DemotedCallTargets) {
603     SCC &TargetC = *G.lookupSCC(*RefTarget);
604     RefSCC &TargetRC = TargetC.getOuterRefSCC();
605 
606     // The easy case is when the target RefSCC is not this RefSCC. This is
607     // only supported when the target RefSCC is a child of this RefSCC.
608     if (&TargetRC != RC) {
609       assert(RC->isAncestorOf(TargetRC) &&
610              "Cannot potentially form RefSCC cycles here!");
611       RC->switchOutgoingEdgeToRef(N, *RefTarget);
612       LLVM_DEBUG(dbgs() << "Switch outgoing call edge to a ref edge from '" << N
613                         << "' to '" << *RefTarget << "'\n");
614       continue;
615     }
616 
617     // We are switching an internal call edge to a ref edge. This may split up
618     // some SCCs.
619     if (C != &TargetC) {
620       // For separate SCCs this is trivial.
621       RC->switchTrivialInternalEdgeToRef(N, *RefTarget);
622       continue;
623     }
624 
625     // Now update the call graph.
626     C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, *RefTarget), G, N,
627                                C, AM, UR);
628   }
629 
630   // Now promote ref edges into call edges.
631   for (Node *CallTarget : PromotedRefTargets) {
632     SCC &TargetC = *G.lookupSCC(*CallTarget);
633     RefSCC &TargetRC = TargetC.getOuterRefSCC();
634 
635     // The easy case is when the target RefSCC is not this RefSCC. This is
636     // only supported when the target RefSCC is a child of this RefSCC.
637     if (&TargetRC != RC) {
638       assert(RC->isAncestorOf(TargetRC) &&
639              "Cannot potentially form RefSCC cycles here!");
640       RC->switchOutgoingEdgeToCall(N, *CallTarget);
641       LLVM_DEBUG(dbgs() << "Switch outgoing ref edge to a call edge from '" << N
642                         << "' to '" << *CallTarget << "'\n");
643       continue;
644     }
645     LLVM_DEBUG(dbgs() << "Switch an internal ref edge to a call edge from '"
646                       << N << "' to '" << *CallTarget << "'\n");
647 
648     // Otherwise we are switching an internal ref edge to a call edge. This
649     // may merge away some SCCs, and we add those to the UpdateResult. We also
650     // need to make sure to update the worklist in the event SCCs have moved
651     // before the current one in the post-order sequence
652     bool HasFunctionAnalysisProxy = false;
653     auto InitialSCCIndex = RC->find(*C) - RC->begin();
654     bool FormedCycle = RC->switchInternalEdgeToCall(
655         N, *CallTarget, [&](ArrayRef<SCC *> MergedSCCs) {
656           for (SCC *MergedC : MergedSCCs) {
657             assert(MergedC != &TargetC && "Cannot merge away the target SCC!");
658 
659             HasFunctionAnalysisProxy |=
660                 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(
661                     *MergedC) != nullptr;
662 
663             // Mark that this SCC will no longer be valid.
664             UR.InvalidatedSCCs.insert(MergedC);
665 
666             // FIXME: We should really do a 'clear' here to forcibly release
667             // memory, but we don't have a good way of doing that and
668             // preserving the function analyses.
669             auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
670             PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
671             AM.invalidate(*MergedC, PA);
672           }
673         });
674 
675     // If we formed a cycle by creating this call, we need to update more data
676     // structures.
677     if (FormedCycle) {
678       C = &TargetC;
679       assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
680 
681       // If one of the invalidated SCCs had a cached proxy to a function
682       // analysis manager, we need to create a proxy in the new current SCC as
683       // the invalidated SCCs had their functions moved.
684       if (HasFunctionAnalysisProxy)
685         AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G);
686 
687       // Any analyses cached for this SCC are no longer precise as the shape
688       // has changed by introducing this cycle. However, we have taken care to
689       // update the proxies so it remains valide.
690       auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
691       PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
692       AM.invalidate(*C, PA);
693     }
694     auto NewSCCIndex = RC->find(*C) - RC->begin();
695     // If we have actually moved an SCC to be topologically "below" the current
696     // one due to merging, we will need to revisit the current SCC after
697     // visiting those moved SCCs.
698     //
699     // It is critical that we *do not* revisit the current SCC unless we
700     // actually move SCCs in the process of merging because otherwise we may
701     // form a cycle where an SCC is split apart, merged, split, merged and so
702     // on infinitely.
703     if (InitialSCCIndex < NewSCCIndex) {
704       // Put our current SCC back onto the worklist as we'll visit other SCCs
705       // that are now definitively ordered prior to the current one in the
706       // post-order sequence, and may end up observing more precise context to
707       // optimize the current SCC.
708       UR.CWorklist.insert(C);
709       LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist: " << *C
710                         << "\n");
711       // Enqueue in reverse order as we pop off the back of the worklist.
712       for (SCC &MovedC : llvm::reverse(make_range(RC->begin() + InitialSCCIndex,
713                                                   RC->begin() + NewSCCIndex))) {
714         UR.CWorklist.insert(&MovedC);
715         LLVM_DEBUG(dbgs() << "Enqueuing a newly earlier in post-order SCC: "
716                           << MovedC << "\n");
717       }
718     }
719   }
720 
721   assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
722   assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
723   assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
724 
725   // Record the current RefSCC and SCC for higher layers of the CGSCC pass
726   // manager now that all the updates have been applied.
727   if (RC != &InitialRC)
728     UR.UpdatedRC = RC;
729   if (C != &InitialC)
730     UR.UpdatedC = C;
731 
732   return *C;
733 }
734 
735 LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
736     LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
737     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
738   return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR,
739                                            /* FunctionPass */ true);
740 }
741 LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForCGSCCPass(
742     LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
743     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
744   return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR,
745                                            /* FunctionPass */ false);
746 }
747