LLVM 19.0.0git
CGSCCPassManager.cpp
Go to the documentation of this file.
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
10#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/SetVector.h"
18#include "llvm/IR/Constant.h"
20#include "llvm/IR/Instruction.h"
21#include "llvm/IR/PassManager.h"
23#include "llvm/IR/ValueHandle.h"
26#include "llvm/Support/Debug.h"
30#include <cassert>
31#include <iterator>
32#include <optional>
33
34#define DEBUG_TYPE "cgscc"
35
36using namespace llvm;
37
38// Explicit template instantiations and specialization definitions for core
39// template typedefs.
40namespace llvm {
42 "abort-on-max-devirt-iterations-reached",
43 cl::desc("Abort when the max iterations for devirtualization CGSCC repeat "
44 "pass is reached"));
45
47
48// Explicit instantiations for the core proxy templates.
57
58/// Explicitly specialize the pass manager run method to handle call graph
59/// updates.
60template <>
66 // Request PassInstrumentation from analysis manager, will use it to run
67 // instrumenting callbacks for the passes later.
70
72
73 // The SCC may be refined while we are running passes over it, so set up
74 // a pointer that we can update.
75 LazyCallGraph::SCC *C = &InitialC;
76
77 // Get Function analysis manager from its proxy.
80
81 for (auto &Pass : Passes) {
82 // Check the PassInstrumentation's BeforePass callbacks before running the
83 // pass, skip its execution completely if asked to (callback returns false).
84 if (!PI.runBeforePass(*Pass, *C))
85 continue;
86
87 PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR);
88
89 // Update the SCC if necessary.
90 C = UR.UpdatedC ? UR.UpdatedC : C;
91 if (UR.UpdatedC) {
92 // If C is updated, also create a proxy and update FAM inside the result.
93 auto *ResultFAMCP =
95 ResultFAMCP->updateFAM(FAM);
96 }
97
98 // Intersect the final preserved analyses to compute the aggregate
99 // preserved set for this pass manager.
100 PA.intersect(PassPA);
101
102 // If the CGSCC pass wasn't able to provide a valid updated SCC, the
103 // current SCC may simply need to be skipped if invalid.
104 if (UR.InvalidatedSCCs.count(C)) {
106 LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
107 break;
108 }
109
110 // Check that we didn't miss any update scenario.
111 assert(C->begin() != C->end() && "Cannot have an empty SCC!");
112
113 // Update the analysis manager as each pass runs and potentially
114 // invalidates analyses.
115 AM.invalidate(*C, PassPA);
116
117 PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C, PassPA);
118 }
119
120 // Before we mark all of *this* SCC's analyses as preserved below, intersect
121 // this with the cross-SCC preserved analysis set. This is used to allow
122 // CGSCC passes to mutate ancestor SCCs and still trigger proper invalidation
123 // for them.
124 UR.CrossSCCPA.intersect(PA);
125
126 // Invalidation was handled after each pass in the above loop for the current
127 // SCC. Therefore, the remaining analysis results in the AnalysisManager are
128 // preserved. We mark this with a set so that we don't need to inspect each
129 // one individually.
130 PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>();
131
132 return PA;
133}
134
137 // Setup the CGSCC analysis manager from its proxy.
139 AM.getResult<CGSCCAnalysisManagerModuleProxy>(M).getManager();
140
141 // Get the call graph for this module.
143
144 // Get Function analysis manager from its proxy.
147
148 // We keep worklists to allow us to push more work onto the pass manager as
149 // the passes are run.
152
153 // Keep sets for invalidated SCCs and RefSCCs that should be skipped when
154 // iterating off the worklists.
157
159 InlinedInternalEdges;
160
161 SmallVector<Function *, 4> DeadFunctions;
162
163 CGSCCUpdateResult UR = {CWorklist,
164 InvalidRefSCCSet,
165 InvalidSCCSet,
166 nullptr,
168 InlinedInternalEdges,
169 DeadFunctions,
170 {}};
171
172 // Request PassInstrumentation from analysis manager, will use it to run
173 // instrumenting callbacks for the passes later.
175
177 CG.buildRefSCCs();
178 for (LazyCallGraph::RefSCC &RC :
180 assert(RCWorklist.empty() &&
181 "Should always start with an empty RefSCC worklist");
182 // The postorder_ref_sccs range we are walking is lazily constructed, so
183 // we only push the first one onto the worklist. The worklist allows us
184 // to capture *new* RefSCCs created during transformations.
185 //
186 // We really want to form RefSCCs lazily because that makes them cheaper
187 // to update as the program is simplified and allows us to have greater
188 // cache locality as forming a RefSCC touches all the parts of all the
189 // functions within that RefSCC.
190 //
191 // We also eagerly increment the iterator to the next position because
192 // the CGSCC passes below may delete the current RefSCC.
193 RCWorklist.insert(&RC);
194
195 do {
196 LazyCallGraph::RefSCC *RC = RCWorklist.pop_back_val();
197 if (InvalidRefSCCSet.count(RC)) {
198 LLVM_DEBUG(dbgs() << "Skipping an invalid RefSCC...\n");
199 continue;
200 }
201
202 assert(CWorklist.empty() &&
203 "Should always start with an empty SCC worklist");
204
205 LLVM_DEBUG(dbgs() << "Running an SCC pass across the RefSCC: " << *RC
206 << "\n");
207
208 // The top of the worklist may *also* be the same SCC we just ran over
209 // (and invalidated for). Keep track of that last SCC we processed due
210 // to SCC update to avoid redundant processing when an SCC is both just
211 // updated itself and at the top of the worklist.
212 LazyCallGraph::SCC *LastUpdatedC = nullptr;
213
214 // Push the initial SCCs in reverse post-order as we'll pop off the
215 // back and so see this in post-order.
217 CWorklist.insert(&C);
218
219 do {
220 LazyCallGraph::SCC *C = CWorklist.pop_back_val();
221 // Due to call graph mutations, we may have invalid SCCs or SCCs from
222 // other RefSCCs in the worklist. The invalid ones are dead and the
223 // other RefSCCs should be queued above, so we just need to skip both
224 // scenarios here.
225 if (InvalidSCCSet.count(C)) {
226 LLVM_DEBUG(dbgs() << "Skipping an invalid SCC...\n");
227 continue;
228 }
229 if (LastUpdatedC == C) {
230 LLVM_DEBUG(dbgs() << "Skipping redundant run on SCC: " << *C << "\n");
231 continue;
232 }
233 // We used to also check if the current SCC is part of the current
234 // RefSCC and bail if it wasn't, since it should be in RCWorklist.
235 // However, this can cause compile time explosions in some cases on
236 // modules with a huge RefSCC. If a non-trivial amount of SCCs in the
237 // huge RefSCC can become their own child RefSCC, we create one child
238 // RefSCC, bail on the current RefSCC, visit the child RefSCC, revisit
239 // the huge RefSCC, and repeat. By visiting all SCCs in the original
240 // RefSCC we create all the child RefSCCs in one pass of the RefSCC,
241 // rather one pass of the RefSCC creating one child RefSCC at a time.
242
243 // Ensure we can proxy analysis updates from the CGSCC analysis manager
244 // into the Function analysis manager by getting a proxy here.
245 // This also needs to update the FunctionAnalysisManager, as this may be
246 // the first time we see this SCC.
248 FAM);
249
250 // Each time we visit a new SCC pulled off the worklist,
251 // a transformation of a child SCC may have also modified this parent
252 // and invalidated analyses. So we invalidate using the update record's
253 // cross-SCC preserved set. This preserved set is intersected by any
254 // CGSCC pass that handles invalidation (primarily pass managers) prior
255 // to marking its SCC as preserved. That lets us track everything that
256 // might need invalidation across SCCs without excessive invalidations
257 // on a single SCC.
258 //
259 // This essentially allows SCC passes to freely invalidate analyses
260 // of any ancestor SCC. If this becomes detrimental to successfully
261 // caching analyses, we could force each SCC pass to manually
262 // invalidate the analyses for any SCCs other than themselves which
263 // are mutated. However, that seems to lose the robustness of the
264 // pass-manager driven invalidation scheme.
266
267 do {
268 // Check that we didn't miss any update scenario.
269 assert(!InvalidSCCSet.count(C) && "Processing an invalid SCC!");
270 assert(C->begin() != C->end() && "Cannot have an empty SCC!");
271
272 LastUpdatedC = UR.UpdatedC;
273 UR.UpdatedC = nullptr;
274
275 // Check the PassInstrumentation's BeforePass callbacks before
276 // running the pass, skip its execution completely if asked to
277 // (callback returns false).
279 continue;
280
281 PreservedAnalyses PassPA = Pass->run(*C, CGAM, CG, UR);
282
283 // Update the SCC and RefSCC if necessary.
284 C = UR.UpdatedC ? UR.UpdatedC : C;
285
286 if (UR.UpdatedC) {
287 // If we're updating the SCC, also update the FAM inside the proxy's
288 // result.
290 FAM);
291 }
292
293 // Intersect with the cross-SCC preserved set to capture any
294 // cross-SCC invalidation.
295 UR.CrossSCCPA.intersect(PassPA);
296 // Intersect the preserved set so that invalidation of module
297 // analyses will eventually occur when the module pass completes.
298 PA.intersect(PassPA);
299
300 // If the CGSCC pass wasn't able to provide a valid updated SCC,
301 // the current SCC may simply need to be skipped if invalid.
302 if (UR.InvalidatedSCCs.count(C)) {
304 LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
305 break;
306 }
307
308 // Check that we didn't miss any update scenario.
309 assert(C->begin() != C->end() && "Cannot have an empty SCC!");
310
311 // We handle invalidating the CGSCC analysis manager's information
312 // for the (potentially updated) SCC here. Note that any other SCCs
313 // whose structure has changed should have been invalidated by
314 // whatever was updating the call graph. This SCC gets invalidated
315 // late as it contains the nodes that were actively being
316 // processed.
317 CGAM.invalidate(*C, PassPA);
318
319 PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C, PassPA);
320
321 // The pass may have restructured the call graph and refined the
322 // current SCC and/or RefSCC. We need to update our current SCC and
323 // RefSCC pointers to follow these. Also, when the current SCC is
324 // refined, re-run the SCC pass over the newly refined SCC in order
325 // to observe the most precise SCC model available. This inherently
326 // cannot cycle excessively as it only happens when we split SCCs
327 // apart, at most converging on a DAG of single nodes.
328 // FIXME: If we ever start having RefSCC passes, we'll want to
329 // iterate there too.
330 if (UR.UpdatedC)
332 << "Re-running SCC passes after a refinement of the "
333 "current SCC: "
334 << *UR.UpdatedC << "\n");
335
336 // Note that both `C` and `RC` may at this point refer to deleted,
337 // invalid SCC and RefSCCs respectively. But we will short circuit
338 // the processing when we check them in the loop above.
339 } while (UR.UpdatedC);
340 } while (!CWorklist.empty());
341
342 // We only need to keep internal inlined edge information within
343 // a RefSCC, clear it to save on space and let the next time we visit
344 // any of these functions have a fresh start.
345 InlinedInternalEdges.clear();
346 } while (!RCWorklist.empty());
347 }
348
349 CG.removeDeadFunctions(DeadFunctions);
350 for (Function *DeadF : DeadFunctions)
351 DeadF->eraseFromParent();
352
353#if defined(EXPENSIVE_CHECKS)
354 // Verify that the call graph is still valid.
355 CG.verify();
356#endif
357
358 // By definition we preserve the call garph, all SCC analyses, and the
359 // analysis proxies by handling them above and in any nested pass managers.
360 PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>();
361 PA.preserve<LazyCallGraphAnalysis>();
362 PA.preserve<CGSCCAnalysisManagerModuleProxy>();
364 return PA;
365}
366
369 LazyCallGraph &CG,
370 CGSCCUpdateResult &UR) {
373 AM.getResult<PassInstrumentationAnalysis>(InitialC, CG);
374
375 // The SCC may be refined while we are running passes over it, so set up
376 // a pointer that we can update.
377 LazyCallGraph::SCC *C = &InitialC;
378
379 // Struct to track the counts of direct and indirect calls in each function
380 // of the SCC.
381 struct CallCount {
382 int Direct;
383 int Indirect;
384 };
385
386 // Put value handles on all of the indirect calls and return the number of
387 // direct calls for each function in the SCC.
388 auto ScanSCC = [](LazyCallGraph::SCC &C,
390 assert(CallHandles.empty() && "Must start with a clear set of handles.");
391
393 CallCount CountLocal = {0, 0};
394 for (LazyCallGraph::Node &N : C) {
395 CallCount &Count =
396 CallCounts.insert(std::make_pair(&N.getFunction(), CountLocal))
397 .first->second;
398 for (Instruction &I : instructions(N.getFunction()))
399 if (auto *CB = dyn_cast<CallBase>(&I)) {
400 if (CB->getCalledFunction()) {
401 ++Count.Direct;
402 } else {
403 ++Count.Indirect;
404 CallHandles.insert({CB, WeakTrackingVH(CB)});
405 }
406 }
407 }
408
409 return CallCounts;
410 };
411
412 UR.IndirectVHs.clear();
413 // Populate the initial call handles and get the initial call counts.
414 auto CallCounts = ScanSCC(*C, UR.IndirectVHs);
415
416 for (int Iteration = 0;; ++Iteration) {
418 continue;
419
420 PreservedAnalyses PassPA = Pass->run(*C, AM, CG, UR);
421
422 PA.intersect(PassPA);
423
424 // If the CGSCC pass wasn't able to provide a valid updated SCC, the
425 // current SCC may simply need to be skipped if invalid.
426 if (UR.InvalidatedSCCs.count(C)) {
428 LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n");
429 break;
430 }
431
432 // Update the analysis manager with each run and intersect the total set
433 // of preserved analyses so we're ready to iterate.
434 AM.invalidate(*C, PassPA);
435
436 PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C, PassPA);
437
438 // If the SCC structure has changed, bail immediately and let the outer
439 // CGSCC layer handle any iteration to reflect the refined structure.
440 if (UR.UpdatedC && UR.UpdatedC != C)
441 break;
442
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 break;
487 }
488
489 // Otherwise, if we've already hit our max, we're done.
490 if (Iteration >= MaxIterations) {
492 report_fatal_error("Max devirtualization iterations reached");
494 dbgs() << "Found another devirtualization after hitting the max "
495 "number of repetitions ("
496 << MaxIterations << ") on SCC: " << *C << "\n");
497 break;
498 }
499
501 dbgs() << "Repeating an SCC pass after finding a devirtualization in: "
502 << *C << "\n");
503
504 // Move over the new call counts in preparation for iterating.
505 CallCounts = std::move(NewCallCounts);
506 }
507
508 // Note that we don't add any preserved entries here unlike a more normal
509 // "pass manager" because we only handle invalidation *between* iterations,
510 // not after the last iteration.
511 return PA;
512}
513
516 LazyCallGraph &CG,
517 CGSCCUpdateResult &UR) {
518 // Setup the function analysis manager from its proxy.
520 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
521
523 for (LazyCallGraph::Node &N : C)
524 Nodes.push_back(&N);
525
526 // The SCC may get split while we are optimizing functions due to deleting
527 // edges. If this happens, the current SCC can shift, so keep track of
528 // a pointer we can overwrite.
529 LazyCallGraph::SCC *CurrentC = &C;
530
531 LLVM_DEBUG(dbgs() << "Running function passes across an SCC: " << C << "\n");
532
534 for (LazyCallGraph::Node *N : Nodes) {
535 // Skip nodes from other SCCs. These may have been split out during
536 // processing. We'll eventually visit those SCCs and pick up the nodes
537 // there.
538 if (CG.lookupSCC(*N) != CurrentC)
539 continue;
540
541 Function &F = N->getFunction();
542
544 continue;
545
547 if (!PI.runBeforePass<Function>(*Pass, F))
548 continue;
549
550 PreservedAnalyses PassPA = Pass->run(F, FAM);
551
552 // We know that the function pass couldn't have invalidated any other
553 // function's analyses (that's the contract of a function pass), so
554 // directly handle the function analysis manager's invalidation here.
555 FAM.invalidate(F, EagerlyInvalidate ? PreservedAnalyses::none() : PassPA);
556
557 PI.runAfterPass<Function>(*Pass, F, PassPA);
558
559 // Then intersect the preserved set so that invalidation of module
560 // analyses will eventually occur when the module pass completes.
561 PA.intersect(std::move(PassPA));
562
563 // If the call graph hasn't been preserved, update it based on this
564 // function pass. This may also update the current SCC to point to
565 // a smaller, more refined SCC.
566 auto PAC = PA.getChecker<LazyCallGraphAnalysis>();
567 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Module>>()) {
568 CurrentC = &updateCGAndAnalysisManagerForFunctionPass(CG, *CurrentC, *N,
569 AM, UR, FAM);
570 assert(CG.lookupSCC(*N) == CurrentC &&
571 "Current SCC not updated to the SCC containing the current node!");
572 }
573 }
574
575 // By definition we preserve the proxy. And we preserve all analyses on
576 // Functions. This precludes *any* invalidation of function analyses by the
577 // proxy, but that's OK because we've taken care to invalidate analyses in
578 // the function analysis manager incrementally above.
581
582 // We've also ensured that we updated the call graph along the way.
584
585 return PA;
586}
587
588bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
589 Module &M, const PreservedAnalyses &PA,
591 // If literally everything is preserved, we're done.
592 if (PA.areAllPreserved())
593 return false; // This is still a valid proxy.
594
595 // If this proxy or the call graph is going to be invalidated, we also need
596 // to clear all the keys coming from that analysis.
597 //
598 // We also directly invalidate the FAM's module proxy if necessary, and if
599 // that proxy isn't preserved we can't preserve this proxy either. We rely on
600 // it to handle module -> function analysis invalidation in the face of
601 // structural changes and so if it's unavailable we conservatively clear the
602 // entire SCC layer as well rather than trying to do invalidation ourselves.
604 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>()) ||
605 Inv.invalidate<LazyCallGraphAnalysis>(M, PA) ||
607 InnerAM->clear();
608
609 // And the proxy itself should be marked as invalid so that we can observe
610 // the new call graph. This isn't strictly necessary because we cheat
611 // above, but is still useful.
612 return true;
613 }
614
615 // Directly check if the relevant set is preserved so we can short circuit
616 // invalidating SCCs below.
617 bool AreSCCAnalysesPreserved =
619
620 // Ok, we have a graph, so we can propagate the invalidation down into it.
621 G->buildRefSCCs();
622 for (auto &RC : G->postorder_ref_sccs())
623 for (auto &C : RC) {
624 std::optional<PreservedAnalyses> InnerPA;
625
626 // Check to see whether the preserved set needs to be adjusted based on
627 // module-level analysis invalidation triggering deferred invalidation
628 // for this SCC.
629 if (auto *OuterProxy =
630 InnerAM->getCachedResult<ModuleAnalysisManagerCGSCCProxy>(C))
631 for (const auto &OuterInvalidationPair :
632 OuterProxy->getOuterInvalidations()) {
633 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
634 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
635 if (Inv.invalidate(OuterAnalysisID, M, PA)) {
636 if (!InnerPA)
637 InnerPA = PA;
638 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
639 InnerPA->abandon(InnerAnalysisID);
640 }
641 }
642
643 // Check if we needed a custom PA set. If so we'll need to run the inner
644 // invalidation.
645 if (InnerPA) {
646 InnerAM->invalidate(C, *InnerPA);
647 continue;
648 }
649
650 // Otherwise we only need to do invalidation if the original PA set didn't
651 // preserve all SCC analyses.
652 if (!AreSCCAnalysesPreserved)
653 InnerAM->invalidate(C, PA);
654 }
655
656 // Return false to indicate that this result is still a valid proxy.
657 return false;
658}
659
660template <>
663 // Force the Function analysis manager to also be available so that it can
664 // be accessed in an SCC analysis and proxied onward to function passes.
665 // FIXME: It is pretty awkward to just drop the result here and assert that
666 // we can find it again later.
668
669 return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M));
670}
671
672AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key;
673
677 LazyCallGraph &CG) {
678 // Note: unconditionally getting checking that the proxy exists may get it at
679 // this point. There are cases when this is being run unnecessarily, but
680 // it is cheap and having the assertion in place is more valuable.
681 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG);
682 Module &M = *C.begin()->getFunction().getParent();
683 bool ProxyExists =
684 MAMProxy.cachedResultExists<FunctionAnalysisManagerModuleProxy>(M);
685 assert(ProxyExists &&
686 "The CGSCC pass manager requires that the FAM module proxy is run "
687 "on the module prior to entering the CGSCC walk");
688 (void)ProxyExists;
689
690 // We just return an empty result. The caller will use the updateFAM interface
691 // to correctly register the relevant FunctionAnalysisManager based on the
692 // context in which this proxy is run.
693 return Result();
694}
695
699 // If literally everything is preserved, we're done.
700 if (PA.areAllPreserved())
701 return false; // This is still a valid proxy.
702
703 // All updates to preserve valid results are done below, so we don't need to
704 // invalidate this proxy.
705 //
706 // Note that in order to preserve this proxy, a module pass must ensure that
707 // the FAM has been completely updated to handle the deletion of functions.
708 // Specifically, any FAM-cached results for those functions need to have been
709 // forcibly cleared. When preserved, this proxy will only invalidate results
710 // cached on functions *still in the module* at the end of the module pass.
712 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<LazyCallGraph::SCC>>()) {
713 for (LazyCallGraph::Node &N : C)
714 FAM->invalidate(N.getFunction(), PA);
715
716 return false;
717 }
718
719 // Directly check if the relevant set is preserved.
720 bool AreFunctionAnalysesPreserved =
722
723 // Now walk all the functions to see if any inner analysis invalidation is
724 // necessary.
725 for (LazyCallGraph::Node &N : C) {
726 Function &F = N.getFunction();
727 std::optional<PreservedAnalyses> FunctionPA;
728
729 // Check to see whether the preserved set needs to be pruned based on
730 // SCC-level analysis invalidation that triggers deferred invalidation
731 // registered with the outer analysis manager proxy for this function.
732 if (auto *OuterProxy =
734 for (const auto &OuterInvalidationPair :
735 OuterProxy->getOuterInvalidations()) {
736 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
737 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
738 if (Inv.invalidate(OuterAnalysisID, C, PA)) {
739 if (!FunctionPA)
740 FunctionPA = PA;
741 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
742 FunctionPA->abandon(InnerAnalysisID);
743 }
744 }
745
746 // Check if we needed a custom PA set, and if so we'll need to run the
747 // inner invalidation.
748 if (FunctionPA) {
749 FAM->invalidate(F, *FunctionPA);
750 continue;
751 }
752
753 // Otherwise we only need to do invalidation if the original PA set didn't
754 // preserve all function analyses.
755 if (!AreFunctionAnalysesPreserved)
756 FAM->invalidate(F, PA);
757 }
758
759 // Return false to indicate that this result is still a valid proxy.
760 return false;
761}
762
763} // end namespace llvm
764
765/// When a new SCC is created for the graph we first update the
766/// FunctionAnalysisManager in the Proxy's result.
767/// As there might be function analysis results cached for the functions now in
768/// that SCC, two forms of updates are required.
769///
770/// First, a proxy from the SCC to the FunctionAnalysisManager needs to be
771/// created so that any subsequent invalidation events to the SCC are
772/// propagated to the function analysis results cached for functions within it.
773///
774/// Second, if any of the functions within the SCC have analysis results with
775/// outer analysis dependencies, then those dependencies would point to the
776/// *wrong* SCC's analysis result. We forcibly invalidate the necessary
777/// function analyses so that they don't retain stale handles.
783
784 // Now walk the functions in this SCC and invalidate any function analysis
785 // results that might have outer dependencies on an SCC analysis.
786 for (LazyCallGraph::Node &N : C) {
787 Function &F = N.getFunction();
788
789 auto *OuterProxy =
791 if (!OuterProxy)
792 // No outer analyses were queried, nothing to do.
793 continue;
794
795 // Forcibly abandon all the inner analyses with dependencies, but
796 // invalidate nothing else.
797 auto PA = PreservedAnalyses::all();
798 for (const auto &OuterInvalidationPair :
799 OuterProxy->getOuterInvalidations()) {
800 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
801 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
802 PA.abandon(InnerAnalysisID);
803 }
804
805 // Now invalidate anything we found.
806 FAM.invalidate(F, PA);
807 }
808}
809
810/// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
811/// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
812/// added SCCs.
813///
814/// The range of new SCCs must be in postorder already. The SCC they were split
815/// out of must be provided as \p C. The current node being mutated and
816/// triggering updates must be passed as \p N.
817///
818/// This function returns the SCC containing \p N. This will be either \p C if
819/// no new SCCs have been split out, or it will be the new SCC containing \p N.
820template <typename SCCRangeT>
821static LazyCallGraph::SCC *
822incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
825 using SCC = LazyCallGraph::SCC;
826
827 if (NewSCCRange.empty())
828 return C;
829
830 // Add the current SCC to the worklist as its shape has changed.
831 UR.CWorklist.insert(C);
832 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist:" << *C
833 << "\n");
834
835 SCC *OldC = C;
836
837 // Update the current SCC. Note that if we have new SCCs, this must actually
838 // change the SCC.
839 assert(C != &*NewSCCRange.begin() &&
840 "Cannot insert new SCCs without changing current SCC!");
841 C = &*NewSCCRange.begin();
842 assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
843
844 // If we had a cached FAM proxy originally, we will want to create more of
845 // them for each SCC that was split off.
846 FunctionAnalysisManager *FAM = nullptr;
847 if (auto *FAMProxy =
849 FAM = &FAMProxy->getManager();
850
851 // We need to propagate an invalidation call to all but the newly current SCC
852 // because the outer pass manager won't do that for us after splitting them.
853 // FIXME: We should accept a PreservedAnalysis from the CG updater so that if
854 // there are preserved analysis we can avoid invalidating them here for
855 // split-off SCCs.
856 // We know however that this will preserve any FAM proxy so go ahead and mark
857 // that.
858 auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
860 AM.invalidate(*OldC, PA);
861
862 // Ensure the now-current SCC's function analyses are updated.
863 if (FAM)
865
866 for (SCC &NewC : llvm::reverse(llvm::drop_begin(NewSCCRange))) {
867 assert(C != &NewC && "No need to re-visit the current SCC!");
868 assert(OldC != &NewC && "Already handled the original SCC!");
869 UR.CWorklist.insert(&NewC);
870 LLVM_DEBUG(dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n");
871
872 // Ensure new SCCs' function analyses are updated.
873 if (FAM)
875
876 // Also propagate a normal invalidation to the new SCC as only the current
877 // will get one from the pass manager infrastructure.
878 AM.invalidate(NewC, PA);
879 }
880 return C;
881}
882
888 using Edge = LazyCallGraph::Edge;
889 using SCC = LazyCallGraph::SCC;
890 using RefSCC = LazyCallGraph::RefSCC;
891
892 RefSCC &InitialRC = InitialC.getOuterRefSCC();
893 SCC *C = &InitialC;
894 RefSCC *RC = &InitialRC;
895 Function &F = N.getFunction();
896
897 // Walk the function body and build up the set of retained, promoted, and
898 // demoted edges.
901 SmallPtrSet<Node *, 16> RetainedEdges;
902 SmallSetVector<Node *, 4> PromotedRefTargets;
903 SmallSetVector<Node *, 4> DemotedCallTargets;
904 SmallSetVector<Node *, 4> NewCallEdges;
905 SmallSetVector<Node *, 4> NewRefEdges;
906
907 // First walk the function and handle all called functions. We do this first
908 // because if there is a single call edge, whether there are ref edges is
909 // irrelevant.
910 for (Instruction &I : instructions(F)) {
911 if (auto *CB = dyn_cast<CallBase>(&I)) {
912 if (Function *Callee = CB->getCalledFunction()) {
913 if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
914 Node *CalleeN = G.lookup(*Callee);
915 assert(CalleeN &&
916 "Visited function should already have an associated node");
917 Edge *E = N->lookup(*CalleeN);
918 assert((E || !FunctionPass) &&
919 "No function transformations should introduce *new* "
920 "call edges! Any new calls should be modeled as "
921 "promoted existing ref edges!");
922 bool Inserted = RetainedEdges.insert(CalleeN).second;
923 (void)Inserted;
924 assert(Inserted && "We should never visit a function twice.");
925 if (!E)
926 NewCallEdges.insert(CalleeN);
927 else if (!E->isCall())
928 PromotedRefTargets.insert(CalleeN);
929 }
930 } else {
931 // We can miss devirtualization if an indirect call is created then
932 // promoted before updateCGAndAnalysisManagerForPass runs.
933 auto *Entry = UR.IndirectVHs.find(CB);
934 if (Entry == UR.IndirectVHs.end())
935 UR.IndirectVHs.insert({CB, WeakTrackingVH(CB)});
936 else if (!Entry->second)
937 Entry->second = WeakTrackingVH(CB);
938 }
939 }
940 }
941
942 // Now walk all references.
943 for (Instruction &I : instructions(F))
944 for (Value *Op : I.operand_values())
945 if (auto *OpC = dyn_cast<Constant>(Op))
946 if (Visited.insert(OpC).second)
947 Worklist.push_back(OpC);
948
949 auto VisitRef = [&](Function &Referee) {
950 Node *RefereeN = G.lookup(Referee);
951 assert(RefereeN &&
952 "Visited function should already have an associated node");
953 Edge *E = N->lookup(*RefereeN);
954 assert((E || !FunctionPass) &&
955 "No function transformations should introduce *new* ref "
956 "edges! Any new ref edges would require IPO which "
957 "function passes aren't allowed to do!");
958 bool Inserted = RetainedEdges.insert(RefereeN).second;
959 (void)Inserted;
960 assert(Inserted && "We should never visit a function twice.");
961 if (!E)
962 NewRefEdges.insert(RefereeN);
963 else if (E->isCall())
964 DemotedCallTargets.insert(RefereeN);
965 };
966 LazyCallGraph::visitReferences(Worklist, Visited, VisitRef);
967
968 // Handle new ref edges.
969 for (Node *RefTarget : NewRefEdges) {
970 SCC &TargetC = *G.lookupSCC(*RefTarget);
971 RefSCC &TargetRC = TargetC.getOuterRefSCC();
972 (void)TargetRC;
973 // TODO: This only allows trivial edges to be added for now.
974#ifdef EXPENSIVE_CHECKS
975 assert((RC == &TargetRC ||
976 RC->isAncestorOf(TargetRC)) && "New ref edge is not trivial!");
977#endif
978 RC->insertTrivialRefEdge(N, *RefTarget);
979 }
980
981 // Handle new call edges.
982 for (Node *CallTarget : NewCallEdges) {
983 SCC &TargetC = *G.lookupSCC(*CallTarget);
984 RefSCC &TargetRC = TargetC.getOuterRefSCC();
985 (void)TargetRC;
986 // TODO: This only allows trivial edges to be added for now.
987#ifdef EXPENSIVE_CHECKS
988 assert((RC == &TargetRC ||
989 RC->isAncestorOf(TargetRC)) && "New call edge is not trivial!");
990#endif
991 // Add a trivial ref edge to be promoted later on alongside
992 // PromotedRefTargets.
993 RC->insertTrivialRefEdge(N, *CallTarget);
994 }
995
996 // Include synthetic reference edges to known, defined lib functions.
997 for (auto *LibFn : G.getLibFunctions())
998 // While the list of lib functions doesn't have repeats, don't re-visit
999 // anything handled above.
1000 if (!Visited.count(LibFn))
1001 VisitRef(*LibFn);
1002
1003 // First remove all of the edges that are no longer present in this function.
1004 // The first step makes these edges uniformly ref edges and accumulates them
1005 // into a separate data structure so removal doesn't invalidate anything.
1006 SmallVector<Node *, 4> DeadTargets;
1007 for (Edge &E : *N) {
1008 if (RetainedEdges.count(&E.getNode()))
1009 continue;
1010
1011 SCC &TargetC = *G.lookupSCC(E.getNode());
1012 RefSCC &TargetRC = TargetC.getOuterRefSCC();
1013 if (&TargetRC == RC && E.isCall()) {
1014 if (C != &TargetC) {
1015 // For separate SCCs this is trivial.
1016 RC->switchTrivialInternalEdgeToRef(N, E.getNode());
1017 } else {
1018 // Now update the call graph.
1019 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, E.getNode()),
1020 G, N, C, AM, UR);
1021 }
1022 }
1023
1024 // Now that this is ready for actual removal, put it into our list.
1025 DeadTargets.push_back(&E.getNode());
1026 }
1027 // Remove the easy cases quickly and actually pull them out of our list.
1028 llvm::erase_if(DeadTargets, [&](Node *TargetN) {
1029 SCC &TargetC = *G.lookupSCC(*TargetN);
1030 RefSCC &TargetRC = TargetC.getOuterRefSCC();
1031
1032 // We can't trivially remove internal targets, so skip
1033 // those.
1034 if (&TargetRC == RC)
1035 return false;
1036
1037 LLVM_DEBUG(dbgs() << "Deleting outgoing edge from '" << N << "' to '"
1038 << *TargetN << "'\n");
1039 RC->removeOutgoingEdge(N, *TargetN);
1040 return true;
1041 });
1042
1043 // Next demote all the call edges that are now ref edges. This helps make
1044 // the SCCs small which should minimize the work below as we don't want to
1045 // form cycles that this would break.
1046 for (Node *RefTarget : DemotedCallTargets) {
1047 SCC &TargetC = *G.lookupSCC(*RefTarget);
1048 RefSCC &TargetRC = TargetC.getOuterRefSCC();
1049
1050 // The easy case is when the target RefSCC is not this RefSCC. This is
1051 // only supported when the target RefSCC is a child of this RefSCC.
1052 if (&TargetRC != RC) {
1053#ifdef EXPENSIVE_CHECKS
1054 assert(RC->isAncestorOf(TargetRC) &&
1055 "Cannot potentially form RefSCC cycles here!");
1056#endif
1057 RC->switchOutgoingEdgeToRef(N, *RefTarget);
1058 LLVM_DEBUG(dbgs() << "Switch outgoing call edge to a ref edge from '" << N
1059 << "' to '" << *RefTarget << "'\n");
1060 continue;
1061 }
1062
1063 // We are switching an internal call edge to a ref edge. This may split up
1064 // some SCCs.
1065 if (C != &TargetC) {
1066 // For separate SCCs this is trivial.
1067 RC->switchTrivialInternalEdgeToRef(N, *RefTarget);
1068 continue;
1069 }
1070
1071 // Now update the call graph.
1072 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, *RefTarget), G, N,
1073 C, AM, UR);
1074 }
1075
1076 // We added a ref edge earlier for new call edges, promote those to call edges
1077 // alongside PromotedRefTargets.
1078 for (Node *E : NewCallEdges)
1079 PromotedRefTargets.insert(E);
1080
1081 // Now promote ref edges into call edges.
1082 for (Node *CallTarget : PromotedRefTargets) {
1083 SCC &TargetC = *G.lookupSCC(*CallTarget);
1084 RefSCC &TargetRC = TargetC.getOuterRefSCC();
1085
1086 // The easy case is when the target RefSCC is not this RefSCC. This is
1087 // only supported when the target RefSCC is a child of this RefSCC.
1088 if (&TargetRC != RC) {
1089#ifdef EXPENSIVE_CHECKS
1090 assert(RC->isAncestorOf(TargetRC) &&
1091 "Cannot potentially form RefSCC cycles here!");
1092#endif
1093 RC->switchOutgoingEdgeToCall(N, *CallTarget);
1094 LLVM_DEBUG(dbgs() << "Switch outgoing ref edge to a call edge from '" << N
1095 << "' to '" << *CallTarget << "'\n");
1096 continue;
1097 }
1098 LLVM_DEBUG(dbgs() << "Switch an internal ref edge to a call edge from '"
1099 << N << "' to '" << *CallTarget << "'\n");
1100
1101 // Otherwise we are switching an internal ref edge to a call edge. This
1102 // may merge away some SCCs, and we add those to the UpdateResult. We also
1103 // need to make sure to update the worklist in the event SCCs have moved
1104 // before the current one in the post-order sequence
1105 bool HasFunctionAnalysisProxy = false;
1106 auto InitialSCCIndex = RC->find(*C) - RC->begin();
1107 bool FormedCycle = RC->switchInternalEdgeToCall(
1108 N, *CallTarget, [&](ArrayRef<SCC *> MergedSCCs) {
1109 for (SCC *MergedC : MergedSCCs) {
1110 assert(MergedC != &TargetC && "Cannot merge away the target SCC!");
1111
1112 HasFunctionAnalysisProxy |=
1114 *MergedC) != nullptr;
1115
1116 // Mark that this SCC will no longer be valid.
1117 UR.InvalidatedSCCs.insert(MergedC);
1118
1119 // FIXME: We should really do a 'clear' here to forcibly release
1120 // memory, but we don't have a good way of doing that and
1121 // preserving the function analyses.
1122 auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
1123 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1124 AM.invalidate(*MergedC, PA);
1125 }
1126 });
1127
1128 // If we formed a cycle by creating this call, we need to update more data
1129 // structures.
1130 if (FormedCycle) {
1131 C = &TargetC;
1132 assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
1133
1134 // If one of the invalidated SCCs had a cached proxy to a function
1135 // analysis manager, we need to create a proxy in the new current SCC as
1136 // the invalidated SCCs had their functions moved.
1137 if (HasFunctionAnalysisProxy)
1139
1140 // Any analyses cached for this SCC are no longer precise as the shape
1141 // has changed by introducing this cycle. However, we have taken care to
1142 // update the proxies so it remains valide.
1143 auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
1144 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1145 AM.invalidate(*C, PA);
1146 }
1147 auto NewSCCIndex = RC->find(*C) - RC->begin();
1148 // If we have actually moved an SCC to be topologically "below" the current
1149 // one due to merging, we will need to revisit the current SCC after
1150 // visiting those moved SCCs.
1151 //
1152 // It is critical that we *do not* revisit the current SCC unless we
1153 // actually move SCCs in the process of merging because otherwise we may
1154 // form a cycle where an SCC is split apart, merged, split, merged and so
1155 // on infinitely.
1156 if (InitialSCCIndex < NewSCCIndex) {
1157 // Put our current SCC back onto the worklist as we'll visit other SCCs
1158 // that are now definitively ordered prior to the current one in the
1159 // post-order sequence, and may end up observing more precise context to
1160 // optimize the current SCC.
1161 UR.CWorklist.insert(C);
1162 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist: " << *C
1163 << "\n");
1164 // Enqueue in reverse order as we pop off the back of the worklist.
1165 for (SCC &MovedC : llvm::reverse(make_range(RC->begin() + InitialSCCIndex,
1166 RC->begin() + NewSCCIndex))) {
1167 UR.CWorklist.insert(&MovedC);
1168 LLVM_DEBUG(dbgs() << "Enqueuing a newly earlier in post-order SCC: "
1169 << MovedC << "\n");
1170 }
1171 }
1172 }
1173
1174 assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
1175 assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
1176 assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
1177
1178 // Record the current SCC for higher layers of the CGSCC pass manager now that
1179 // all the updates have been applied.
1180 if (C != &InitialC)
1181 UR.UpdatedC = C;
1182
1183 return *C;
1184}
1185
1190 return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM,
1191 /* FunctionPass */ true);
1192}
1197 return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM,
1198 /* FunctionPass */ false);
1199}
Expand Atomic instructions
static LazyCallGraph::SCC & updateCGAndAnalysisManagerForPass(LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, FunctionAnalysisManager &FAM, bool FunctionPass)
static LazyCallGraph::SCC * incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G, LazyCallGraph::Node &N, LazyCallGraph::SCC *C, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR)
Helper function to update both the CGSCCAnalysisManager AM and the CGSCCPassManager's CGSCCUpdateResu...
static void updateNewSCCFunctionAnalyses(LazyCallGraph::SCC &C, LazyCallGraph &G, CGSCCAnalysisManager &AM, FunctionAnalysisManager &FAM)
When a new SCC is created for the graph we first update the FunctionAnalysisManager in the Proxy's re...
This header provides classes for managing passes over SCCs of the call graph.
#define LLVM_DEBUG(X)
Definition: Debug.h:101
Implements a lazy call graph analysis and related passes for the new pass manager.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
#define P(N)
CGSCCAnalysisManager CGAM
FunctionAnalysisManager FAM
const char * Passes
Provides implementations for PassManager and AnalysisManager template methods.
This header defines various interfaces for pass management in LLVM.
This file provides a priority worklist.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This templated class represents "all analyses that operate over <a particular IR unit>" (e....
Definition: Analysis.h:49
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:292
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Trigger the invalidation of some other analysis pass if not already handled and return whether it was...
Definition: PassManager.h:310
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:424
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
We need a specialized result for the CGSCCAnalysisManagerModuleProxy so it can have access to the cal...
PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
Runs the function pass across every function in the module.
This class represents an Operation in the Expression.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
PreservedAnalyses run(LazyCallGraph::SCC &InitialC, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
Runs the wrapped pass up to MaxIterations on the SCC, iterating whenever an indirect call is refined.
bool invalidate(LazyCallGraph::SCC &C, const PreservedAnalyses &PA, CGSCCAnalysisManager::Invalidator &Inv)
A proxy from a FunctionAnalysisManager to an SCC.
Result run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &)
Computes the FunctionAnalysisManager and stores it in the result proxy.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:563
Result run(IRUnitT &IR, AnalysisManager< IRUnitT, ExtraArgTs... > &AM, ExtraArgTs...)
Run the analysis pass and create our proxy result object.
Definition: PassManager.h:624
An analysis pass which computes the call graph for a module.
A class used to represent edges in the call graph.
A node in the call graph.
A RefSCC of the call graph.
An SCC of the call graph.
RefSCC & getOuterRefSCC() const
A lazily constructed view of the call graph of a module.
static void visitReferences(SmallVectorImpl< Constant * > &Worklist, SmallPtrSetImpl< Constant * > &Visited, function_ref< void(Function &)> Callback)
Recursively visits the defined functions whose address is reachable from every constant in the Workli...
void removeDeadFunctions(ArrayRef< Function * > DeadFs)
Remove dead functions from the call graph.
SCC * lookupSCC(Node &N) const
Lookup a function's SCC in the graph.
iterator_range< postorder_ref_scc_iterator > postorder_ref_sccs()
void verify()
Verify that every RefSCC is valid.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Runs the CGSCC pass across every SCC in the module.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
Definition: PassManager.h:688
Pseudo-analysis pass that exposes the PassInstrumentation to pass managers.
This class provides instrumentation entry points for the Pass Manager, doing calls to callbacks regis...
void runAfterPassInvalidated(const PassT &Pass, const PreservedAnalyses &PA) const
AfterPassInvalidated instrumentation point - takes Pass instance that has just been executed.
void runAfterPass(const PassT &Pass, const IRUnitT &IR, const PreservedAnalyses &PA) const
AfterPass instrumentation point - takes Pass instance that has just been executed and constant refere...
bool runBeforePass(const PassT &Pass, const IRUnitT &IR) const
BeforePass instrumentation point - takes Pass instance to be executed and constant reference to IR it...
Manages a sequence of passes over a particular unit of IR.
Definition: PassManager.h:162
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
bool areAllPreserved() const
Test whether all analyses are preserved (and none are abandoned).
Definition: Analysis.h:281
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
bool allAnalysesInSetPreserved() const
Directly test whether a set of analyses is preserved.
Definition: Analysis.h:289
void intersect(const PreservedAnalyses &Arg)
Intersect this set with another in place.
Definition: Analysis.h:182
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:146
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition: Analysis.h:264
void abandon()
Mark an analysis as abandoned.
Definition: Analysis.h:164
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:131
bool empty() const
Determine if the PriorityWorklist is empty or not.
bool insert(const T &X)
Insert a new element into the PriorityWorklist.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:290
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:412
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:344
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:479
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
LLVM Value Representation.
Definition: Value.h:74
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:204
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
LazyCallGraph::SCC & updateCGAndAnalysisManagerForFunctionPass(LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, FunctionAnalysisManager &FAM)
Helper to update the call graph after running a function pass.
LazyCallGraph::SCC & updateCGAndAnalysisManagerForCGSCCPass(LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, FunctionAnalysisManager &FAM)
Helper to update the call graph after running a CGSCC pass.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:656
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition: STLExtras.h:2051
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition: MIRParser.h:38
static cl::opt< bool > AbortOnMaxDevirtIterationsReached("abort-on-max-devirt-iterations-reached", cl::desc("Abort when the max iterations for devirtualization CGSCC repeat " "pass is reached"))
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:28
Support structure for SCC passes to communicate updates the call graph back to the CGSCC pass manager...
SmallMapVector< Value *, WeakTrackingVH, 16 > IndirectVHs
Weak VHs to keep track of indirect calls for the purposes of detecting devirtualization.
SmallPriorityWorklist< LazyCallGraph::SCC *, 1 > & CWorklist
Worklist of the SCCs queued for processing.
SmallPtrSetImpl< LazyCallGraph::SCC * > & InvalidatedSCCs
The set of invalidated SCCs which should be skipped if they are found in CWorklist.
SmallPtrSetImpl< LazyCallGraph::RefSCC * > & InvalidatedRefSCCs
The set of invalidated RefSCCs which should be skipped if they are found in RCWorklist.
LazyCallGraph::SCC * UpdatedC
If non-null, the updated current SCC being processed.
PreservedAnalyses CrossSCCPA
Preserved analyses across SCCs.
A MapVector that performs no allocations if smaller than a certain size.
Definition: MapVector.h:254