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