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