Bug Summary

File:llvm/lib/Analysis/CGSCCPassManager.cpp
Warning:line 241, column 11
Forming reference to null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGSCCPassManager.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/lib/Analysis -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-04-14-063029-18377-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp

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" "cgscc"
35
36using namespace llvm;
37
38// Explicit template instantiations and specialization definitions for core
39// template typedefs.
40namespace llvm {
41
42static 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.
48template class AllAnalysesOn<LazyCallGraph::SCC>;
49template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
50template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
51 LazyCallGraph &, CGSCCUpdateResult &>;
52template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
53template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
54 LazyCallGraph::SCC, LazyCallGraph &>;
55template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
56
57/// Explicitly specialize the pass manager run method to handle call graph
58/// updates.
59template <>
60PreservedAnalyses
61PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
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")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Skipping invalidated root or island SCC!\n"
; } } while (false)
;
113 break;
114 }
115 // Check that we didn't miss any update scenario.
116 assert(C->begin() != C->end() && "Cannot have an empty SCC!")((C->begin() != C->end() && "Cannot have an empty SCC!"
) ? static_cast<void> (0) : __assert_fail ("C->begin() != C->end() && \"Cannot have an empty SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 116, __PRETTY_FUNCTION__))
;
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
151PreservedAnalyses
152ModuleToPostOrderCGSCCPassAdaptor::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(),
1
Loop condition is true. Entering loop body
189 RCE = CG.postorder_ref_scc_end();
190 RCI != RCE;) {
191 assert(RCWorklist.empty() &&((RCWorklist.empty() && "Should always start with an empty RefSCC worklist"
) ? static_cast<void> (0) : __assert_fail ("RCWorklist.empty() && \"Should always start with an empty RefSCC worklist\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 192, __PRETTY_FUNCTION__))
2
'?' condition is true
192 "Should always start with an empty RefSCC worklist")((RCWorklist.empty() && "Should always start with an empty RefSCC worklist"
) ? static_cast<void> (0) : __assert_fail ("RCWorklist.empty() && \"Should always start with an empty RefSCC worklist\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 192, __PRETTY_FUNCTION__))
;
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)) {
3
Assuming the condition is false
4
Taking false branch
209 LLVM_DEBUG(dbgs() << "Skipping an invalid RefSCC...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Skipping an invalid RefSCC...\n"
; } } while (false)
;
210 continue;
211 }
212
213 assert(CWorklist.empty() &&((CWorklist.empty() && "Should always start with an empty SCC worklist"
) ? static_cast<void> (0) : __assert_fail ("CWorklist.empty() && \"Should always start with an empty SCC worklist\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 214, __PRETTY_FUNCTION__))
5
'?' condition is true
214 "Should always start with an empty SCC worklist")((CWorklist.empty() && "Should always start with an empty SCC worklist"
) ? static_cast<void> (0) : __assert_fail ("CWorklist.empty() && \"Should always start with an empty SCC worklist\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 214, __PRETTY_FUNCTION__))
;
215
216 LLVM_DEBUG(dbgs() << "Running an SCC pass across the RefSCC: " << *RCdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Running an SCC pass across the RefSCC: "
<< *RC << "\n"; } } while (false)
6
Assuming 'DebugFlag' is false
7
Loop condition is false. Exiting loop
217 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Running an SCC pass across the RefSCC: "
<< *RC << "\n"; } } while (false)
;
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();
8
Calling 'PriorityWorklist::pop_back_val'
15
Returning from 'PriorityWorklist::pop_back_val'
16
'C' initialized here
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)) {
17
Assuming the condition is false
18
Taking false branch
237 LLVM_DEBUG(dbgs() << "Skipping an invalid SCC...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Skipping an invalid SCC...\n"; }
} while (false)
;
238 continue;
239 }
240 if (LastUpdatedC == C) {
19
Assuming 'LastUpdatedC' is equal to 'C'
20
Taking true branch
241 LLVM_DEBUG(dbgs() << "Skipping redundant run on SCC: " << *C << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Skipping redundant run on SCC: "
<< *C << "\n"; } } while (false)
;
21
Assuming 'DebugFlag' is true
22
Assuming the condition is true
23
Taking true branch
24
Forming reference to null pointer
242 continue;
243 }
244 if (&C->getOuterRefSCC() != RC) {
245 LLVM_DEBUG(dbgs() << "Skipping an SCC that is now part of some other "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Skipping an SCC that is now part of some other "
"RefSCC...\n"; } } while (false)
246 "RefSCC...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Skipping an SCC that is now part of some other "
"RefSCC...\n"; } } while (false)
;
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!")((!InvalidSCCSet.count(C) && "Processing an invalid SCC!"
) ? static_cast<void> (0) : __assert_fail ("!InvalidSCCSet.count(C) && \"Processing an invalid SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 276, __PRETTY_FUNCTION__))
;
277 assert(C->begin() != C->end() && "Cannot have an empty SCC!")((C->begin() != C->end() && "Cannot have an empty SCC!"
) ? static_cast<void> (0) : __assert_fail ("C->begin() != C->end() && \"Cannot have an empty SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 277, __PRETTY_FUNCTION__))
;
278 assert(&C->getOuterRefSCC() == RC &&((&C->getOuterRefSCC() == RC && "Processing an SCC in a different RefSCC!"
) ? static_cast<void> (0) : __assert_fail ("&C->getOuterRefSCC() == RC && \"Processing an SCC in a different RefSCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 279, __PRETTY_FUNCTION__))
279 "Processing an SCC in a different RefSCC!")((&C->getOuterRefSCC() == RC && "Processing an SCC in a different RefSCC!"
) ? static_cast<void> (0) : __assert_fail ("&C->getOuterRefSCC() == RC && \"Processing an SCC in a different RefSCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 279, __PRETTY_FUNCTION__))
;
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")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Skipping invalidated root or island SCC!\n"
; } } while (false)
;
317 break;
318 }
319 // Check that we didn't miss any update scenario.
320 assert(C->begin() != C->end() && "Cannot have an empty SCC!")((C->begin() != C->end() && "Cannot have an empty SCC!"
) ? static_cast<void> (0) : __assert_fail ("C->begin() != C->end() && \"Cannot have an empty SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 320, __PRETTY_FUNCTION__))
;
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()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Re-running SCC passes after a refinement of the "
"current SCC: " << *UR.UpdatedC << "\n"; } } while
(false)
348 << "Re-running SCC passes after a refinement of the "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Re-running SCC passes after a refinement of the "
"current SCC: " << *UR.UpdatedC << "\n"; } } while
(false)
349 "current SCC: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Re-running SCC passes after a refinement of the "
"current SCC: " << *UR.UpdatedC << "\n"; } } while
(false)
350 << *UR.UpdatedC << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Re-running SCC passes after a refinement of the "
"current SCC: " << *UR.UpdatedC << "\n"; } } while
(false)
;
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
374PreservedAnalyses 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.")((CallHandles.empty() && "Must start with a clear set of handles."
) ? static_cast<void> (0) : __assert_fail ("CallHandles.empty() && \"Must start with a clear set of handles.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 397, __PRETTY_FUNCTION__))
;
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!")((!UR.InvalidatedSCCs.count(C) && "Processing an invalid SCC!"
) ? static_cast<void> (0) : __assert_fail ("!UR.InvalidatedSCCs.count(C) && \"Processing an invalid SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 442, __PRETTY_FUNCTION__))
;
443 assert(C->begin() != C->end() && "Cannot have an empty SCC!")((C->begin() != C->end() && "Cannot have an empty SCC!"
) ? static_cast<void> (0) : __assert_fail ("C->begin() != C->end() && \"Cannot have an empty SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 443, __PRETTY_FUNCTION__))
;
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")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Found devirtualized call: " <<
*CB << "\n"; } } while (false)
;
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 if (AbortOnMaxDevirtIterationsReached)
493 report_fatal_error("Max devirtualization iterations reached");
494 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Found another devirtualization after hitting the max "
"number of repetitions (" << MaxIterations << ") on SCC: "
<< *C << "\n"; } } while (false)
495 dbgs() << "Found another devirtualization after hitting the max "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Found another devirtualization after hitting the max "
"number of repetitions (" << MaxIterations << ") on SCC: "
<< *C << "\n"; } } while (false)
496 "number of repetitions ("do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Found another devirtualization after hitting the max "
"number of repetitions (" << MaxIterations << ") on SCC: "
<< *C << "\n"; } } while (false)
497 << MaxIterations << ") on SCC: " << *C << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Found another devirtualization after hitting the max "
"number of repetitions (" << MaxIterations << ") on SCC: "
<< *C << "\n"; } } while (false)
;
498 PA.intersect(std::move(PassPA));
499 break;
500 }
501
502 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Repeating an SCC pass after finding a devirtualization in: "
<< *C << "\n"; } } while (false)
503 dbgs() << "Repeating an SCC pass after finding a devirtualization in: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Repeating an SCC pass after finding a devirtualization in: "
<< *C << "\n"; } } while (false)
504 << *C << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Repeating an SCC pass after finding a devirtualization in: "
<< *C << "\n"; } } while (false)
;
505
506 // Move over the new call counts in preparation for iterating.
507 CallCounts = std::move(NewCallCounts);
508
509 // Update the analysis manager with each run and intersect the total set
510 // of preserved analyses so we're ready to iterate.
511 AM.invalidate(*C, PassPA);
512
513 PA.intersect(std::move(PassPA));
514 }
515
516 // Note that we don't add any preserved entries here unlike a more normal
517 // "pass manager" because we only handle invalidation *between* iterations,
518 // not after the last iteration.
519 return PA;
520}
521
522PreservedAnalyses CGSCCToFunctionPassAdaptor::run(LazyCallGraph::SCC &C,
523 CGSCCAnalysisManager &AM,
524 LazyCallGraph &CG,
525 CGSCCUpdateResult &UR) {
526 // Setup the function analysis manager from its proxy.
527 FunctionAnalysisManager &FAM =
528 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
529
530 SmallVector<LazyCallGraph::Node *, 4> Nodes;
531 for (LazyCallGraph::Node &N : C)
532 Nodes.push_back(&N);
533
534 // The SCC may get split while we are optimizing functions due to deleting
535 // edges. If this happens, the current SCC can shift, so keep track of
536 // a pointer we can overwrite.
537 LazyCallGraph::SCC *CurrentC = &C;
538
539 LLVM_DEBUG(dbgs() << "Running function passes across an SCC: " << C << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Running function passes across an SCC: "
<< C << "\n"; } } while (false)
;
540
541 PreservedAnalyses PA = PreservedAnalyses::all();
542 for (LazyCallGraph::Node *N : Nodes) {
543 // Skip nodes from other SCCs. These may have been split out during
544 // processing. We'll eventually visit those SCCs and pick up the nodes
545 // there.
546 if (CG.lookupSCC(*N) != CurrentC)
547 continue;
548
549 Function &F = N->getFunction();
550
551 PassInstrumentation PI = FAM.getResult<PassInstrumentationAnalysis>(F);
552 if (!PI.runBeforePass<Function>(*Pass, F))
553 continue;
554
555 PreservedAnalyses PassPA;
556 {
557 TimeTraceScope TimeScope(Pass->name());
558 PassPA = Pass->run(F, FAM);
559 }
560
561 PI.runAfterPass<Function>(*Pass, F, PassPA);
562
563 // We know that the function pass couldn't have invalidated any other
564 // function's analyses (that's the contract of a function pass), so
565 // directly handle the function analysis manager's invalidation here.
566 FAM.invalidate(F, PassPA);
567
568 // Then intersect the preserved set so that invalidation of module
569 // analyses will eventually occur when the module pass completes.
570 PA.intersect(std::move(PassPA));
571
572 // If the call graph hasn't been preserved, update it based on this
573 // function pass. This may also update the current SCC to point to
574 // a smaller, more refined SCC.
575 auto PAC = PA.getChecker<LazyCallGraphAnalysis>();
576 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Module>>()) {
577 CurrentC = &updateCGAndAnalysisManagerForFunctionPass(CG, *CurrentC, *N,
578 AM, UR, FAM);
579 assert(CG.lookupSCC(*N) == CurrentC &&((CG.lookupSCC(*N) == CurrentC && "Current SCC not updated to the SCC containing the current node!"
) ? static_cast<void> (0) : __assert_fail ("CG.lookupSCC(*N) == CurrentC && \"Current SCC not updated to the SCC containing the current node!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 580, __PRETTY_FUNCTION__))
580 "Current SCC not updated to the SCC containing the current node!")((CG.lookupSCC(*N) == CurrentC && "Current SCC not updated to the SCC containing the current node!"
) ? static_cast<void> (0) : __assert_fail ("CG.lookupSCC(*N) == CurrentC && \"Current SCC not updated to the SCC containing the current node!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 580, __PRETTY_FUNCTION__))
;
581 }
582 }
583
584 // By definition we preserve the proxy. And we preserve all analyses on
585 // Functions. This precludes *any* invalidation of function analyses by the
586 // proxy, but that's OK because we've taken care to invalidate analyses in
587 // the function analysis manager incrementally above.
588 PA.preserveSet<AllAnalysesOn<Function>>();
589 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
590
591 // We've also ensured that we updated the call graph along the way.
592 PA.preserve<LazyCallGraphAnalysis>();
593
594 return PA;
595}
596
597bool CGSCCAnalysisManagerModuleProxy::Result::invalidate(
598 Module &M, const PreservedAnalyses &PA,
599 ModuleAnalysisManager::Invalidator &Inv) {
600 // If literally everything is preserved, we're done.
601 if (PA.areAllPreserved())
602 return false; // This is still a valid proxy.
603
604 // If this proxy or the call graph is going to be invalidated, we also need
605 // to clear all the keys coming from that analysis.
606 //
607 // We also directly invalidate the FAM's module proxy if necessary, and if
608 // that proxy isn't preserved we can't preserve this proxy either. We rely on
609 // it to handle module -> function analysis invalidation in the face of
610 // structural changes and so if it's unavailable we conservatively clear the
611 // entire SCC layer as well rather than trying to do invalidation ourselves.
612 auto PAC = PA.getChecker<CGSCCAnalysisManagerModuleProxy>();
613 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>()) ||
614 Inv.invalidate<LazyCallGraphAnalysis>(M, PA) ||
615 Inv.invalidate<FunctionAnalysisManagerModuleProxy>(M, PA)) {
616 InnerAM->clear();
617
618 // And the proxy itself should be marked as invalid so that we can observe
619 // the new call graph. This isn't strictly necessary because we cheat
620 // above, but is still useful.
621 return true;
622 }
623
624 // Directly check if the relevant set is preserved so we can short circuit
625 // invalidating SCCs below.
626 bool AreSCCAnalysesPreserved =
627 PA.allAnalysesInSetPreserved<AllAnalysesOn<LazyCallGraph::SCC>>();
628
629 // Ok, we have a graph, so we can propagate the invalidation down into it.
630 G->buildRefSCCs();
631 for (auto &RC : G->postorder_ref_sccs())
632 for (auto &C : RC) {
633 Optional<PreservedAnalyses> InnerPA;
634
635 // Check to see whether the preserved set needs to be adjusted based on
636 // module-level analysis invalidation triggering deferred invalidation
637 // for this SCC.
638 if (auto *OuterProxy =
639 InnerAM->getCachedResult<ModuleAnalysisManagerCGSCCProxy>(C))
640 for (const auto &OuterInvalidationPair :
641 OuterProxy->getOuterInvalidations()) {
642 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
643 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
644 if (Inv.invalidate(OuterAnalysisID, M, PA)) {
645 if (!InnerPA)
646 InnerPA = PA;
647 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
648 InnerPA->abandon(InnerAnalysisID);
649 }
650 }
651
652 // Check if we needed a custom PA set. If so we'll need to run the inner
653 // invalidation.
654 if (InnerPA) {
655 InnerAM->invalidate(C, *InnerPA);
656 continue;
657 }
658
659 // Otherwise we only need to do invalidation if the original PA set didn't
660 // preserve all SCC analyses.
661 if (!AreSCCAnalysesPreserved)
662 InnerAM->invalidate(C, PA);
663 }
664
665 // Return false to indicate that this result is still a valid proxy.
666 return false;
667}
668
669template <>
670CGSCCAnalysisManagerModuleProxy::Result
671CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM) {
672 // Force the Function analysis manager to also be available so that it can
673 // be accessed in an SCC analysis and proxied onward to function passes.
674 // FIXME: It is pretty awkward to just drop the result here and assert that
675 // we can find it again later.
676 (void)AM.getResult<FunctionAnalysisManagerModuleProxy>(M);
677
678 return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M));
679}
680
681AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key;
682
683FunctionAnalysisManagerCGSCCProxy::Result
684FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C,
685 CGSCCAnalysisManager &AM,
686 LazyCallGraph &CG) {
687 // Note: unconditionally getting checking that the proxy exists may get it at
688 // this point. There are cases when this is being run unnecessarily, but
689 // it is cheap and having the assertion in place is more valuable.
690 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG);
691 Module &M = *C.begin()->getFunction().getParent();
692 bool ProxyExists =
693 MAMProxy.cachedResultExists<FunctionAnalysisManagerModuleProxy>(M);
694 assert(ProxyExists &&((ProxyExists && "The CGSCC pass manager requires that the FAM module proxy is run "
"on the module prior to entering the CGSCC walk") ? static_cast
<void> (0) : __assert_fail ("ProxyExists && \"The CGSCC pass manager requires that the FAM module proxy is run \" \"on the module prior to entering the CGSCC walk\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 696, __PRETTY_FUNCTION__))
695 "The CGSCC pass manager requires that the FAM module proxy is run "((ProxyExists && "The CGSCC pass manager requires that the FAM module proxy is run "
"on the module prior to entering the CGSCC walk") ? static_cast
<void> (0) : __assert_fail ("ProxyExists && \"The CGSCC pass manager requires that the FAM module proxy is run \" \"on the module prior to entering the CGSCC walk\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 696, __PRETTY_FUNCTION__))
696 "on the module prior to entering the CGSCC walk")((ProxyExists && "The CGSCC pass manager requires that the FAM module proxy is run "
"on the module prior to entering the CGSCC walk") ? static_cast
<void> (0) : __assert_fail ("ProxyExists && \"The CGSCC pass manager requires that the FAM module proxy is run \" \"on the module prior to entering the CGSCC walk\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 696, __PRETTY_FUNCTION__))
;
697 (void)ProxyExists;
698
699 // We just return an empty result. The caller will use the updateFAM interface
700 // to correctly register the relevant FunctionAnalysisManager based on the
701 // context in which this proxy is run.
702 return Result();
703}
704
705bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate(
706 LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
707 CGSCCAnalysisManager::Invalidator &Inv) {
708 // If literally everything is preserved, we're done.
709 if (PA.areAllPreserved())
710 return false; // This is still a valid proxy.
711
712 // All updates to preserve valid results are done below, so we don't need to
713 // invalidate this proxy.
714 //
715 // Note that in order to preserve this proxy, a module pass must ensure that
716 // the FAM has been completely updated to handle the deletion of functions.
717 // Specifically, any FAM-cached results for those functions need to have been
718 // forcibly cleared. When preserved, this proxy will only invalidate results
719 // cached on functions *still in the module* at the end of the module pass.
720 auto PAC = PA.getChecker<FunctionAnalysisManagerCGSCCProxy>();
721 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<LazyCallGraph::SCC>>()) {
722 for (LazyCallGraph::Node &N : C)
723 FAM->invalidate(N.getFunction(), PA);
724
725 return false;
726 }
727
728 // Directly check if the relevant set is preserved.
729 bool AreFunctionAnalysesPreserved =
730 PA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>();
731
732 // Now walk all the functions to see if any inner analysis invalidation is
733 // necessary.
734 for (LazyCallGraph::Node &N : C) {
735 Function &F = N.getFunction();
736 Optional<PreservedAnalyses> FunctionPA;
737
738 // Check to see whether the preserved set needs to be pruned based on
739 // SCC-level analysis invalidation that triggers deferred invalidation
740 // registered with the outer analysis manager proxy for this function.
741 if (auto *OuterProxy =
742 FAM->getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F))
743 for (const auto &OuterInvalidationPair :
744 OuterProxy->getOuterInvalidations()) {
745 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first;
746 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
747 if (Inv.invalidate(OuterAnalysisID, C, PA)) {
748 if (!FunctionPA)
749 FunctionPA = PA;
750 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
751 FunctionPA->abandon(InnerAnalysisID);
752 }
753 }
754
755 // Check if we needed a custom PA set, and if so we'll need to run the
756 // inner invalidation.
757 if (FunctionPA) {
758 FAM->invalidate(F, *FunctionPA);
759 continue;
760 }
761
762 // Otherwise we only need to do invalidation if the original PA set didn't
763 // preserve all function analyses.
764 if (!AreFunctionAnalysesPreserved)
765 FAM->invalidate(F, PA);
766 }
767
768 // Return false to indicate that this result is still a valid proxy.
769 return false;
770}
771
772} // end namespace llvm
773
774/// When a new SCC is created for the graph we first update the
775/// FunctionAnalysisManager in the Proxy's result.
776/// As there might be function analysis results cached for the functions now in
777/// that SCC, two forms of updates are required.
778///
779/// First, a proxy from the SCC to the FunctionAnalysisManager needs to be
780/// created so that any subsequent invalidation events to the SCC are
781/// propagated to the function analysis results cached for functions within it.
782///
783/// Second, if any of the functions within the SCC have analysis results with
784/// outer analysis dependencies, then those dependencies would point to the
785/// *wrong* SCC's analysis result. We forcibly invalidate the necessary
786/// function analyses so that they don't retain stale handles.
787static void updateNewSCCFunctionAnalyses(LazyCallGraph::SCC &C,
788 LazyCallGraph &G,
789 CGSCCAnalysisManager &AM,
790 FunctionAnalysisManager &FAM) {
791 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, G).updateFAM(FAM);
792
793 // Now walk the functions in this SCC and invalidate any function analysis
794 // results that might have outer dependencies on an SCC analysis.
795 for (LazyCallGraph::Node &N : C) {
796 Function &F = N.getFunction();
797
798 auto *OuterProxy =
799 FAM.getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F);
800 if (!OuterProxy)
801 // No outer analyses were queried, nothing to do.
802 continue;
803
804 // Forcibly abandon all the inner analyses with dependencies, but
805 // invalidate nothing else.
806 auto PA = PreservedAnalyses::all();
807 for (const auto &OuterInvalidationPair :
808 OuterProxy->getOuterInvalidations()) {
809 const auto &InnerAnalysisIDs = OuterInvalidationPair.second;
810 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs)
811 PA.abandon(InnerAnalysisID);
812 }
813
814 // Now invalidate anything we found.
815 FAM.invalidate(F, PA);
816 }
817}
818
819/// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
820/// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
821/// added SCCs.
822///
823/// The range of new SCCs must be in postorder already. The SCC they were split
824/// out of must be provided as \p C. The current node being mutated and
825/// triggering updates must be passed as \p N.
826///
827/// This function returns the SCC containing \p N. This will be either \p C if
828/// no new SCCs have been split out, or it will be the new SCC containing \p N.
829template <typename SCCRangeT>
830static LazyCallGraph::SCC *
831incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
832 LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
833 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
834 using SCC = LazyCallGraph::SCC;
835
836 if (NewSCCRange.empty())
837 return C;
838
839 // Add the current SCC to the worklist as its shape has changed.
840 UR.CWorklist.insert(C);
841 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist:" << *Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Enqueuing the existing SCC in the worklist:"
<< *C << "\n"; } } while (false)
842 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Enqueuing the existing SCC in the worklist:"
<< *C << "\n"; } } while (false)
;
843
844 SCC *OldC = C;
845
846 // Update the current SCC. Note that if we have new SCCs, this must actually
847 // change the SCC.
848 assert(C != &*NewSCCRange.begin() &&((C != &*NewSCCRange.begin() && "Cannot insert new SCCs without changing current SCC!"
) ? static_cast<void> (0) : __assert_fail ("C != &*NewSCCRange.begin() && \"Cannot insert new SCCs without changing current SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 849, __PRETTY_FUNCTION__))
849 "Cannot insert new SCCs without changing current SCC!")((C != &*NewSCCRange.begin() && "Cannot insert new SCCs without changing current SCC!"
) ? static_cast<void> (0) : __assert_fail ("C != &*NewSCCRange.begin() && \"Cannot insert new SCCs without changing current SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 849, __PRETTY_FUNCTION__))
;
850 C = &*NewSCCRange.begin();
851 assert(G.lookupSCC(N) == C && "Failed to update current SCC!")((G.lookupSCC(N) == C && "Failed to update current SCC!"
) ? static_cast<void> (0) : __assert_fail ("G.lookupSCC(N) == C && \"Failed to update current SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 851, __PRETTY_FUNCTION__))
;
852
853 // If we had a cached FAM proxy originally, we will want to create more of
854 // them for each SCC that was split off.
855 FunctionAnalysisManager *FAM = nullptr;
856 if (auto *FAMProxy =
857 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*OldC))
858 FAM = &FAMProxy->getManager();
859
860 // We need to propagate an invalidation call to all but the newly current SCC
861 // because the outer pass manager won't do that for us after splitting them.
862 // FIXME: We should accept a PreservedAnalysis from the CG updater so that if
863 // there are preserved analysis we can avoid invalidating them here for
864 // split-off SCCs.
865 // We know however that this will preserve any FAM proxy so go ahead and mark
866 // that.
867 PreservedAnalyses PA;
868 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
869 AM.invalidate(*OldC, PA);
870
871 // Ensure the now-current SCC's function analyses are updated.
872 if (FAM)
873 updateNewSCCFunctionAnalyses(*C, G, AM, *FAM);
874
875 for (SCC &NewC : llvm::reverse(llvm::drop_begin(NewSCCRange))) {
876 assert(C != &NewC && "No need to re-visit the current SCC!")((C != &NewC && "No need to re-visit the current SCC!"
) ? static_cast<void> (0) : __assert_fail ("C != &NewC && \"No need to re-visit the current SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 876, __PRETTY_FUNCTION__))
;
877 assert(OldC != &NewC && "Already handled the original SCC!")((OldC != &NewC && "Already handled the original SCC!"
) ? static_cast<void> (0) : __assert_fail ("OldC != &NewC && \"Already handled the original SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 877, __PRETTY_FUNCTION__))
;
878 UR.CWorklist.insert(&NewC);
879 LLVM_DEBUG(dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Enqueuing a newly formed SCC:" <<
NewC << "\n"; } } while (false)
;
880
881 // Ensure new SCCs' function analyses are updated.
882 if (FAM)
883 updateNewSCCFunctionAnalyses(NewC, G, AM, *FAM);
884
885 // Also propagate a normal invalidation to the new SCC as only the current
886 // will get one from the pass manager infrastructure.
887 AM.invalidate(NewC, PA);
888 }
889 return C;
890}
891
892static LazyCallGraph::SCC &updateCGAndAnalysisManagerForPass(
893 LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
894 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
895 FunctionAnalysisManager &FAM, bool FunctionPass) {
896 using Node = LazyCallGraph::Node;
897 using Edge = LazyCallGraph::Edge;
898 using SCC = LazyCallGraph::SCC;
899 using RefSCC = LazyCallGraph::RefSCC;
900
901 RefSCC &InitialRC = InitialC.getOuterRefSCC();
902 SCC *C = &InitialC;
903 RefSCC *RC = &InitialRC;
904 Function &F = N.getFunction();
905
906 // Walk the function body and build up the set of retained, promoted, and
907 // demoted edges.
908 SmallVector<Constant *, 16> Worklist;
909 SmallPtrSet<Constant *, 16> Visited;
910 SmallPtrSet<Node *, 16> RetainedEdges;
911 SmallSetVector<Node *, 4> PromotedRefTargets;
912 SmallSetVector<Node *, 4> DemotedCallTargets;
913 SmallSetVector<Node *, 4> NewCallEdges;
914 SmallSetVector<Node *, 4> NewRefEdges;
915
916 // First walk the function and handle all called functions. We do this first
917 // because if there is a single call edge, whether there are ref edges is
918 // irrelevant.
919 for (Instruction &I : instructions(F)) {
920 if (auto *CB = dyn_cast<CallBase>(&I)) {
921 if (Function *Callee = CB->getCalledFunction()) {
922 if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
923 Node *CalleeN = G.lookup(*Callee);
924 assert(CalleeN &&((CalleeN && "Visited function should already have an associated node"
) ? static_cast<void> (0) : __assert_fail ("CalleeN && \"Visited function should already have an associated node\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 925, __PRETTY_FUNCTION__))
925 "Visited function should already have an associated node")((CalleeN && "Visited function should already have an associated node"
) ? static_cast<void> (0) : __assert_fail ("CalleeN && \"Visited function should already have an associated node\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 925, __PRETTY_FUNCTION__))
;
926 Edge *E = N->lookup(*CalleeN);
927 assert((E || !FunctionPass) &&(((E || !FunctionPass) && "No function transformations should introduce *new* "
"call edges! Any new calls should be modeled as " "promoted existing ref edges!"
) ? static_cast<void> (0) : __assert_fail ("(E || !FunctionPass) && \"No function transformations should introduce *new* \" \"call edges! Any new calls should be modeled as \" \"promoted existing ref edges!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 930, __PRETTY_FUNCTION__))
928 "No function transformations should introduce *new* "(((E || !FunctionPass) && "No function transformations should introduce *new* "
"call edges! Any new calls should be modeled as " "promoted existing ref edges!"
) ? static_cast<void> (0) : __assert_fail ("(E || !FunctionPass) && \"No function transformations should introduce *new* \" \"call edges! Any new calls should be modeled as \" \"promoted existing ref edges!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 930, __PRETTY_FUNCTION__))
929 "call edges! Any new calls should be modeled as "(((E || !FunctionPass) && "No function transformations should introduce *new* "
"call edges! Any new calls should be modeled as " "promoted existing ref edges!"
) ? static_cast<void> (0) : __assert_fail ("(E || !FunctionPass) && \"No function transformations should introduce *new* \" \"call edges! Any new calls should be modeled as \" \"promoted existing ref edges!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 930, __PRETTY_FUNCTION__))
930 "promoted existing ref edges!")(((E || !FunctionPass) && "No function transformations should introduce *new* "
"call edges! Any new calls should be modeled as " "promoted existing ref edges!"
) ? static_cast<void> (0) : __assert_fail ("(E || !FunctionPass) && \"No function transformations should introduce *new* \" \"call edges! Any new calls should be modeled as \" \"promoted existing ref edges!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 930, __PRETTY_FUNCTION__))
;
931 bool Inserted = RetainedEdges.insert(CalleeN).second;
932 (void)Inserted;
933 assert(Inserted && "We should never visit a function twice.")((Inserted && "We should never visit a function twice."
) ? static_cast<void> (0) : __assert_fail ("Inserted && \"We should never visit a function twice.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 933, __PRETTY_FUNCTION__))
;
934 if (!E)
935 NewCallEdges.insert(CalleeN);
936 else if (!E->isCall())
937 PromotedRefTargets.insert(CalleeN);
938 }
939 } else {
940 // We can miss devirtualization if an indirect call is created then
941 // promoted before updateCGAndAnalysisManagerForPass runs.
942 auto *Entry = UR.IndirectVHs.find(CB);
943 if (Entry == UR.IndirectVHs.end())
944 UR.IndirectVHs.insert({CB, WeakTrackingVH(CB)});
945 else if (!Entry->second)
946 Entry->second = WeakTrackingVH(CB);
947 }
948 }
949 }
950
951 // Now walk all references.
952 for (Instruction &I : instructions(F))
953 for (Value *Op : I.operand_values())
954 if (auto *OpC = dyn_cast<Constant>(Op))
955 if (Visited.insert(OpC).second)
956 Worklist.push_back(OpC);
957
958 auto VisitRef = [&](Function &Referee) {
959 Node *RefereeN = G.lookup(Referee);
960 assert(RefereeN &&((RefereeN && "Visited function should already have an associated node"
) ? static_cast<void> (0) : __assert_fail ("RefereeN && \"Visited function should already have an associated node\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 961, __PRETTY_FUNCTION__))
961 "Visited function should already have an associated node")((RefereeN && "Visited function should already have an associated node"
) ? static_cast<void> (0) : __assert_fail ("RefereeN && \"Visited function should already have an associated node\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 961, __PRETTY_FUNCTION__))
;
962 Edge *E = N->lookup(*RefereeN);
963 assert((E || !FunctionPass) &&(((E || !FunctionPass) && "No function transformations should introduce *new* ref "
"edges! Any new ref edges would require IPO which " "function passes aren't allowed to do!"
) ? static_cast<void> (0) : __assert_fail ("(E || !FunctionPass) && \"No function transformations should introduce *new* ref \" \"edges! Any new ref edges would require IPO which \" \"function passes aren't allowed to do!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 966, __PRETTY_FUNCTION__))
964 "No function transformations should introduce *new* ref "(((E || !FunctionPass) && "No function transformations should introduce *new* ref "
"edges! Any new ref edges would require IPO which " "function passes aren't allowed to do!"
) ? static_cast<void> (0) : __assert_fail ("(E || !FunctionPass) && \"No function transformations should introduce *new* ref \" \"edges! Any new ref edges would require IPO which \" \"function passes aren't allowed to do!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 966, __PRETTY_FUNCTION__))
965 "edges! Any new ref edges would require IPO which "(((E || !FunctionPass) && "No function transformations should introduce *new* ref "
"edges! Any new ref edges would require IPO which " "function passes aren't allowed to do!"
) ? static_cast<void> (0) : __assert_fail ("(E || !FunctionPass) && \"No function transformations should introduce *new* ref \" \"edges! Any new ref edges would require IPO which \" \"function passes aren't allowed to do!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 966, __PRETTY_FUNCTION__))
966 "function passes aren't allowed to do!")(((E || !FunctionPass) && "No function transformations should introduce *new* ref "
"edges! Any new ref edges would require IPO which " "function passes aren't allowed to do!"
) ? static_cast<void> (0) : __assert_fail ("(E || !FunctionPass) && \"No function transformations should introduce *new* ref \" \"edges! Any new ref edges would require IPO which \" \"function passes aren't allowed to do!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 966, __PRETTY_FUNCTION__))
;
967 bool Inserted = RetainedEdges.insert(RefereeN).second;
968 (void)Inserted;
969 assert(Inserted && "We should never visit a function twice.")((Inserted && "We should never visit a function twice."
) ? static_cast<void> (0) : __assert_fail ("Inserted && \"We should never visit a function twice.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 969, __PRETTY_FUNCTION__))
;
970 if (!E)
971 NewRefEdges.insert(RefereeN);
972 else if (E->isCall())
973 DemotedCallTargets.insert(RefereeN);
974 };
975 LazyCallGraph::visitReferences(Worklist, Visited, VisitRef);
976
977 // Handle new ref edges.
978 for (Node *RefTarget : NewRefEdges) {
979 SCC &TargetC = *G.lookupSCC(*RefTarget);
980 RefSCC &TargetRC = TargetC.getOuterRefSCC();
981 (void)TargetRC;
982 // TODO: This only allows trivial edges to be added for now.
983#ifdef EXPENSIVE_CHECKS
984 assert((RC == &TargetRC ||(((RC == &TargetRC || RC->isAncestorOf(TargetRC)) &&
"New ref edge is not trivial!") ? static_cast<void> (0
) : __assert_fail ("(RC == &TargetRC || RC->isAncestorOf(TargetRC)) && \"New ref edge is not trivial!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 985, __PRETTY_FUNCTION__))
985 RC->isAncestorOf(TargetRC)) && "New ref edge is not trivial!")(((RC == &TargetRC || RC->isAncestorOf(TargetRC)) &&
"New ref edge is not trivial!") ? static_cast<void> (0
) : __assert_fail ("(RC == &TargetRC || RC->isAncestorOf(TargetRC)) && \"New ref edge is not trivial!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 985, __PRETTY_FUNCTION__))
;
986#endif
987 RC->insertTrivialRefEdge(N, *RefTarget);
988 }
989
990 // Handle new call edges.
991 for (Node *CallTarget : NewCallEdges) {
992 SCC &TargetC = *G.lookupSCC(*CallTarget);
993 RefSCC &TargetRC = TargetC.getOuterRefSCC();
994 (void)TargetRC;
995 // TODO: This only allows trivial edges to be added for now.
996#ifdef EXPENSIVE_CHECKS
997 assert((RC == &TargetRC ||(((RC == &TargetRC || RC->isAncestorOf(TargetRC)) &&
"New call edge is not trivial!") ? static_cast<void> (
0) : __assert_fail ("(RC == &TargetRC || RC->isAncestorOf(TargetRC)) && \"New call edge is not trivial!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 998, __PRETTY_FUNCTION__))
998 RC->isAncestorOf(TargetRC)) && "New call edge is not trivial!")(((RC == &TargetRC || RC->isAncestorOf(TargetRC)) &&
"New call edge is not trivial!") ? static_cast<void> (
0) : __assert_fail ("(RC == &TargetRC || RC->isAncestorOf(TargetRC)) && \"New call edge is not trivial!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 998, __PRETTY_FUNCTION__))
;
999#endif
1000 // Add a trivial ref edge to be promoted later on alongside
1001 // PromotedRefTargets.
1002 RC->insertTrivialRefEdge(N, *CallTarget);
1003 }
1004
1005 // Include synthetic reference edges to known, defined lib functions.
1006 for (auto *LibFn : G.getLibFunctions())
1007 // While the list of lib functions doesn't have repeats, don't re-visit
1008 // anything handled above.
1009 if (!Visited.count(LibFn))
1010 VisitRef(*LibFn);
1011
1012 // First remove all of the edges that are no longer present in this function.
1013 // The first step makes these edges uniformly ref edges and accumulates them
1014 // into a separate data structure so removal doesn't invalidate anything.
1015 SmallVector<Node *, 4> DeadTargets;
1016 for (Edge &E : *N) {
1017 if (RetainedEdges.count(&E.getNode()))
1018 continue;
1019
1020 SCC &TargetC = *G.lookupSCC(E.getNode());
1021 RefSCC &TargetRC = TargetC.getOuterRefSCC();
1022 if (&TargetRC == RC && E.isCall()) {
1023 if (C != &TargetC) {
1024 // For separate SCCs this is trivial.
1025 RC->switchTrivialInternalEdgeToRef(N, E.getNode());
1026 } else {
1027 // Now update the call graph.
1028 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, E.getNode()),
1029 G, N, C, AM, UR);
1030 }
1031 }
1032
1033 // Now that this is ready for actual removal, put it into our list.
1034 DeadTargets.push_back(&E.getNode());
1035 }
1036 // Remove the easy cases quickly and actually pull them out of our list.
1037 llvm::erase_if(DeadTargets, [&](Node *TargetN) {
1038 SCC &TargetC = *G.lookupSCC(*TargetN);
1039 RefSCC &TargetRC = TargetC.getOuterRefSCC();
1040
1041 // We can't trivially remove internal targets, so skip
1042 // those.
1043 if (&TargetRC == RC)
1044 return false;
1045
1046 LLVM_DEBUG(dbgs() << "Deleting outgoing edge from '" << N << "' to '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Deleting outgoing edge from '" <<
N << "' to '" << *TargetN << "'\n"; } } while
(false)
1047 << *TargetN << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Deleting outgoing edge from '" <<
N << "' to '" << *TargetN << "'\n"; } } while
(false)
;
1048 RC->removeOutgoingEdge(N, *TargetN);
1049 return true;
1050 });
1051
1052 // Now do a batch removal of the internal ref edges left.
1053 auto NewRefSCCs = RC->removeInternalRefEdge(N, DeadTargets);
1054 if (!NewRefSCCs.empty()) {
1055 // The old RefSCC is dead, mark it as such.
1056 UR.InvalidatedRefSCCs.insert(RC);
1057
1058 // Note that we don't bother to invalidate analyses as ref-edge
1059 // connectivity is not really observable in any way and is intended
1060 // exclusively to be used for ordering of transforms rather than for
1061 // analysis conclusions.
1062
1063 // Update RC to the "bottom".
1064 assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!")((G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!"
) ? static_cast<void> (0) : __assert_fail ("G.lookupSCC(N) == C && \"Changed the SCC when splitting RefSCCs!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1064, __PRETTY_FUNCTION__))
;
1065 RC = &C->getOuterRefSCC();
1066 assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!")((G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!"
) ? static_cast<void> (0) : __assert_fail ("G.lookupRefSCC(N) == RC && \"Failed to update current RefSCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1066, __PRETTY_FUNCTION__))
;
1067
1068 // The RC worklist is in reverse postorder, so we enqueue the new ones in
1069 // RPO except for the one which contains the source node as that is the
1070 // "bottom" we will continue processing in the bottom-up walk.
1071 assert(NewRefSCCs.front() == RC &&((NewRefSCCs.front() == RC && "New current RefSCC not first in the returned list!"
) ? static_cast<void> (0) : __assert_fail ("NewRefSCCs.front() == RC && \"New current RefSCC not first in the returned list!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1072, __PRETTY_FUNCTION__))
1072 "New current RefSCC not first in the returned list!")((NewRefSCCs.front() == RC && "New current RefSCC not first in the returned list!"
) ? static_cast<void> (0) : __assert_fail ("NewRefSCCs.front() == RC && \"New current RefSCC not first in the returned list!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1072, __PRETTY_FUNCTION__))
;
1073 for (RefSCC *NewRC : llvm::reverse(llvm::drop_begin(NewRefSCCs))) {
1074 assert(NewRC != RC && "Should not encounter the current RefSCC further "((NewRC != RC && "Should not encounter the current RefSCC further "
"in the postorder list of new RefSCCs.") ? static_cast<void
> (0) : __assert_fail ("NewRC != RC && \"Should not encounter the current RefSCC further \" \"in the postorder list of new RefSCCs.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1075, __PRETTY_FUNCTION__))
1075 "in the postorder list of new RefSCCs.")((NewRC != RC && "Should not encounter the current RefSCC further "
"in the postorder list of new RefSCCs.") ? static_cast<void
> (0) : __assert_fail ("NewRC != RC && \"Should not encounter the current RefSCC further \" \"in the postorder list of new RefSCCs.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1075, __PRETTY_FUNCTION__))
;
1076 UR.RCWorklist.insert(NewRC);
1077 LLVM_DEBUG(dbgs() << "Enqueuing a new RefSCC in the update worklist: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Enqueuing a new RefSCC in the update worklist: "
<< *NewRC << "\n"; } } while (false)
1078 << *NewRC << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Enqueuing a new RefSCC in the update worklist: "
<< *NewRC << "\n"; } } while (false)
;
1079 }
1080 }
1081
1082 // Next demote all the call edges that are now ref edges. This helps make
1083 // the SCCs small which should minimize the work below as we don't want to
1084 // form cycles that this would break.
1085 for (Node *RefTarget : DemotedCallTargets) {
1086 SCC &TargetC = *G.lookupSCC(*RefTarget);
1087 RefSCC &TargetRC = TargetC.getOuterRefSCC();
1088
1089 // The easy case is when the target RefSCC is not this RefSCC. This is
1090 // only supported when the target RefSCC is a child of this RefSCC.
1091 if (&TargetRC != RC) {
1092#ifdef EXPENSIVE_CHECKS
1093 assert(RC->isAncestorOf(TargetRC) &&((RC->isAncestorOf(TargetRC) && "Cannot potentially form RefSCC cycles here!"
) ? static_cast<void> (0) : __assert_fail ("RC->isAncestorOf(TargetRC) && \"Cannot potentially form RefSCC cycles here!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1094, __PRETTY_FUNCTION__))
1094 "Cannot potentially form RefSCC cycles here!")((RC->isAncestorOf(TargetRC) && "Cannot potentially form RefSCC cycles here!"
) ? static_cast<void> (0) : __assert_fail ("RC->isAncestorOf(TargetRC) && \"Cannot potentially form RefSCC cycles here!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1094, __PRETTY_FUNCTION__))
;
1095#endif
1096 RC->switchOutgoingEdgeToRef(N, *RefTarget);
1097 LLVM_DEBUG(dbgs() << "Switch outgoing call edge to a ref edge from '" << Ndo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Switch outgoing call edge to a ref edge from '"
<< N << "' to '" << *RefTarget << "'\n"
; } } while (false)
1098 << "' to '" << *RefTarget << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Switch outgoing call edge to a ref edge from '"
<< N << "' to '" << *RefTarget << "'\n"
; } } while (false)
;
1099 continue;
1100 }
1101
1102 // We are switching an internal call edge to a ref edge. This may split up
1103 // some SCCs.
1104 if (C != &TargetC) {
1105 // For separate SCCs this is trivial.
1106 RC->switchTrivialInternalEdgeToRef(N, *RefTarget);
1107 continue;
1108 }
1109
1110 // Now update the call graph.
1111 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, *RefTarget), G, N,
1112 C, AM, UR);
1113 }
1114
1115 // We added a ref edge earlier for new call edges, promote those to call edges
1116 // alongside PromotedRefTargets.
1117 for (Node *E : NewCallEdges)
1118 PromotedRefTargets.insert(E);
1119
1120 // Now promote ref edges into call edges.
1121 for (Node *CallTarget : PromotedRefTargets) {
1122 SCC &TargetC = *G.lookupSCC(*CallTarget);
1123 RefSCC &TargetRC = TargetC.getOuterRefSCC();
1124
1125 // The easy case is when the target RefSCC is not this RefSCC. This is
1126 // only supported when the target RefSCC is a child of this RefSCC.
1127 if (&TargetRC != RC) {
1128#ifdef EXPENSIVE_CHECKS
1129 assert(RC->isAncestorOf(TargetRC) &&((RC->isAncestorOf(TargetRC) && "Cannot potentially form RefSCC cycles here!"
) ? static_cast<void> (0) : __assert_fail ("RC->isAncestorOf(TargetRC) && \"Cannot potentially form RefSCC cycles here!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1130, __PRETTY_FUNCTION__))
1130 "Cannot potentially form RefSCC cycles here!")((RC->isAncestorOf(TargetRC) && "Cannot potentially form RefSCC cycles here!"
) ? static_cast<void> (0) : __assert_fail ("RC->isAncestorOf(TargetRC) && \"Cannot potentially form RefSCC cycles here!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1130, __PRETTY_FUNCTION__))
;
1131#endif
1132 RC->switchOutgoingEdgeToCall(N, *CallTarget);
1133 LLVM_DEBUG(dbgs() << "Switch outgoing ref edge to a call edge from '" << Ndo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Switch outgoing ref edge to a call edge from '"
<< N << "' to '" << *CallTarget << "'\n"
; } } while (false)
1134 << "' to '" << *CallTarget << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Switch outgoing ref edge to a call edge from '"
<< N << "' to '" << *CallTarget << "'\n"
; } } while (false)
;
1135 continue;
1136 }
1137 LLVM_DEBUG(dbgs() << "Switch an internal ref edge to a call edge from '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Switch an internal ref edge to a call edge from '"
<< N << "' to '" << *CallTarget << "'\n"
; } } while (false)
1138 << N << "' to '" << *CallTarget << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Switch an internal ref edge to a call edge from '"
<< N << "' to '" << *CallTarget << "'\n"
; } } while (false)
;
1139
1140 // Otherwise we are switching an internal ref edge to a call edge. This
1141 // may merge away some SCCs, and we add those to the UpdateResult. We also
1142 // need to make sure to update the worklist in the event SCCs have moved
1143 // before the current one in the post-order sequence
1144 bool HasFunctionAnalysisProxy = false;
1145 auto InitialSCCIndex = RC->find(*C) - RC->begin();
1146 bool FormedCycle = RC->switchInternalEdgeToCall(
1147 N, *CallTarget, [&](ArrayRef<SCC *> MergedSCCs) {
1148 for (SCC *MergedC : MergedSCCs) {
1149 assert(MergedC != &TargetC && "Cannot merge away the target SCC!")((MergedC != &TargetC && "Cannot merge away the target SCC!"
) ? static_cast<void> (0) : __assert_fail ("MergedC != &TargetC && \"Cannot merge away the target SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1149, __PRETTY_FUNCTION__))
;
1150
1151 HasFunctionAnalysisProxy |=
1152 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(
1153 *MergedC) != nullptr;
1154
1155 // Mark that this SCC will no longer be valid.
1156 UR.InvalidatedSCCs.insert(MergedC);
1157
1158 // FIXME: We should really do a 'clear' here to forcibly release
1159 // memory, but we don't have a good way of doing that and
1160 // preserving the function analyses.
1161 auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
1162 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1163 AM.invalidate(*MergedC, PA);
1164 }
1165 });
1166
1167 // If we formed a cycle by creating this call, we need to update more data
1168 // structures.
1169 if (FormedCycle) {
1170 C = &TargetC;
1171 assert(G.lookupSCC(N) == C && "Failed to update current SCC!")((G.lookupSCC(N) == C && "Failed to update current SCC!"
) ? static_cast<void> (0) : __assert_fail ("G.lookupSCC(N) == C && \"Failed to update current SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1171, __PRETTY_FUNCTION__))
;
1172
1173 // If one of the invalidated SCCs had a cached proxy to a function
1174 // analysis manager, we need to create a proxy in the new current SCC as
1175 // the invalidated SCCs had their functions moved.
1176 if (HasFunctionAnalysisProxy)
1177 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G).updateFAM(FAM);
1178
1179 // Any analyses cached for this SCC are no longer precise as the shape
1180 // has changed by introducing this cycle. However, we have taken care to
1181 // update the proxies so it remains valide.
1182 auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>();
1183 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1184 AM.invalidate(*C, PA);
1185 }
1186 auto NewSCCIndex = RC->find(*C) - RC->begin();
1187 // If we have actually moved an SCC to be topologically "below" the current
1188 // one due to merging, we will need to revisit the current SCC after
1189 // visiting those moved SCCs.
1190 //
1191 // It is critical that we *do not* revisit the current SCC unless we
1192 // actually move SCCs in the process of merging because otherwise we may
1193 // form a cycle where an SCC is split apart, merged, split, merged and so
1194 // on infinitely.
1195 if (InitialSCCIndex < NewSCCIndex) {
1196 // Put our current SCC back onto the worklist as we'll visit other SCCs
1197 // that are now definitively ordered prior to the current one in the
1198 // post-order sequence, and may end up observing more precise context to
1199 // optimize the current SCC.
1200 UR.CWorklist.insert(C);
1201 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist: " << *Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Enqueuing the existing SCC in the worklist: "
<< *C << "\n"; } } while (false)
1202 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Enqueuing the existing SCC in the worklist: "
<< *C << "\n"; } } while (false)
;
1203 // Enqueue in reverse order as we pop off the back of the worklist.
1204 for (SCC &MovedC : llvm::reverse(make_range(RC->begin() + InitialSCCIndex,
1205 RC->begin() + NewSCCIndex))) {
1206 UR.CWorklist.insert(&MovedC);
1207 LLVM_DEBUG(dbgs() << "Enqueuing a newly earlier in post-order SCC: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Enqueuing a newly earlier in post-order SCC: "
<< MovedC << "\n"; } } while (false)
1208 << MovedC << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("cgscc")) { dbgs() << "Enqueuing a newly earlier in post-order SCC: "
<< MovedC << "\n"; } } while (false)
;
1209 }
1210 }
1211 }
1212
1213 assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!")((!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!"
) ? static_cast<void> (0) : __assert_fail ("!UR.InvalidatedSCCs.count(C) && \"Invalidated the current SCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1213, __PRETTY_FUNCTION__))
;
1214 assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!")((!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!"
) ? static_cast<void> (0) : __assert_fail ("!UR.InvalidatedRefSCCs.count(RC) && \"Invalidated the current RefSCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1214, __PRETTY_FUNCTION__))
;
1215 assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!")((&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!"
) ? static_cast<void> (0) : __assert_fail ("&C->getOuterRefSCC() == RC && \"Current SCC not in current RefSCC!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Analysis/CGSCCPassManager.cpp"
, 1215, __PRETTY_FUNCTION__))
;
1216
1217 // Record the current RefSCC and SCC for higher layers of the CGSCC pass
1218 // manager now that all the updates have been applied.
1219 if (RC != &InitialRC)
1220 UR.UpdatedRC = RC;
1221 if (C != &InitialC)
1222 UR.UpdatedC = C;
1223
1224 return *C;
1225}
1226
1227LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
1228 LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
1229 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
1230 FunctionAnalysisManager &FAM) {
1231 return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM,
1232 /* FunctionPass */ true);
1233}
1234LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForCGSCCPass(
1235 LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
1236 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
1237 FunctionAnalysisManager &FAM) {
1238 return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM,
1239 /* FunctionPass */ false);
1240}

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/PriorityWorklist.h

1//===- PriorityWorklist.h - Worklist with insertion priority ----*- C++ -*-===//
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/// \file
10///
11/// This file provides a priority worklist. See the class comments for details.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_PRIORITYWORKLIST_H
16#define LLVM_ADT_PRIORITYWORKLIST_H
17
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/Support/Compiler.h"
22#include <algorithm>
23#include <cassert>
24#include <cstddef>
25#include <iterator>
26#include <type_traits>
27#include <vector>
28
29namespace llvm {
30
31/// A FILO worklist that prioritizes on re-insertion without duplication.
32///
33/// This is very similar to a \c SetVector with the primary difference that
34/// while re-insertion does not create a duplicate, it does adjust the
35/// visitation order to respect the last insertion point. This can be useful
36/// when the visit order needs to be prioritized based on insertion point
37/// without actually having duplicate visits.
38///
39/// Note that this doesn't prevent re-insertion of elements which have been
40/// visited -- if you need to break cycles, a set will still be necessary.
41///
42/// The type \c T must be default constructable to a null value that will be
43/// ignored. It is an error to insert such a value, and popping elements will
44/// never produce such a value. It is expected to be used with common nullable
45/// types like pointers or optionals.
46///
47/// Internally this uses a vector to store the worklist and a map to identify
48/// existing elements in the worklist. Both of these may be customized, but the
49/// map must support the basic DenseMap API for mapping from a T to an integer
50/// index into the vector.
51///
52/// A partial specialization is provided to automatically select a SmallVector
53/// and a SmallDenseMap if custom data structures are not provided.
54template <typename T, typename VectorT = std::vector<T>,
55 typename MapT = DenseMap<T, ptrdiff_t>>
56class PriorityWorklist {
57public:
58 using value_type = T;
59 using key_type = T;
60 using reference = T&;
61 using const_reference = const T&;
62 using size_type = typename MapT::size_type;
63
64 /// Construct an empty PriorityWorklist
65 PriorityWorklist() = default;
66
67 /// Determine if the PriorityWorklist is empty or not.
68 bool empty() const {
69 return V.empty();
70 }
71
72 /// Returns the number of elements in the worklist.
73 size_type size() const {
74 return M.size();
75 }
76
77 /// Count the number of elements of a given key in the PriorityWorklist.
78 /// \returns 0 if the element is not in the PriorityWorklist, 1 if it is.
79 size_type count(const key_type &key) const {
80 return M.count(key);
81 }
82
83 /// Return the last element of the PriorityWorklist.
84 const T &back() const {
85 assert(!empty() && "Cannot call back() on empty PriorityWorklist!")((!empty() && "Cannot call back() on empty PriorityWorklist!"
) ? static_cast<void> (0) : __assert_fail ("!empty() && \"Cannot call back() on empty PriorityWorklist!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/PriorityWorklist.h"
, 85, __PRETTY_FUNCTION__))
;
10
'?' condition is true
86 return V.back();
11
Returning pointer
87 }
88
89 /// Insert a new element into the PriorityWorklist.
90 /// \returns true if the element was inserted into the PriorityWorklist.
91 bool insert(const T &X) {
92 assert(X != T() && "Cannot insert a null (default constructed) value!")((X != T() && "Cannot insert a null (default constructed) value!"
) ? static_cast<void> (0) : __assert_fail ("X != T() && \"Cannot insert a null (default constructed) value!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/PriorityWorklist.h"
, 92, __PRETTY_FUNCTION__))
;
93 auto InsertResult = M.insert({X, V.size()});
94 if (InsertResult.second) {
95 // Fresh value, just append it to the vector.
96 V.push_back(X);
97 return true;
98 }
99
100 auto &Index = InsertResult.first->second;
101 assert(V[Index] == X && "Value not actually at index in map!")((V[Index] == X && "Value not actually at index in map!"
) ? static_cast<void> (0) : __assert_fail ("V[Index] == X && \"Value not actually at index in map!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/PriorityWorklist.h"
, 101, __PRETTY_FUNCTION__))
;
102 if (Index != (ptrdiff_t)(V.size() - 1)) {
103 // If the element isn't at the back, null it out and append a fresh one.
104 V[Index] = T();
105 Index = (ptrdiff_t)V.size();
106 V.push_back(X);
107 }
108 return false;
109 }
110
111 /// Insert a sequence of new elements into the PriorityWorklist.
112 template <typename SequenceT>
113 std::enable_if_t<!std::is_convertible<SequenceT, T>::value>
114 insert(SequenceT &&Input) {
115 if (std::begin(Input) == std::end(Input))
116 // Nothing to do for an empty input sequence.
117 return;
118
119 // First pull the input sequence into the vector as a bulk append
120 // operation.
121 ptrdiff_t StartIndex = V.size();
122 V.insert(V.end(), std::begin(Input), std::end(Input));
123 // Now walk backwards fixing up the index map and deleting any duplicates.
124 for (ptrdiff_t i = V.size() - 1; i >= StartIndex; --i) {
125 auto InsertResult = M.insert({V[i], i});
126 if (InsertResult.second)
127 continue;
128
129 // If the existing index is before this insert's start, nuke that one and
130 // move it up.
131 ptrdiff_t &Index = InsertResult.first->second;
132 if (Index < StartIndex) {
133 V[Index] = T();
134 Index = i;
135 continue;
136 }
137
138 // Otherwise the existing one comes first so just clear out the value in
139 // this slot.
140 V[i] = T();
141 }
142 }
143
144 /// Remove the last element of the PriorityWorklist.
145 void pop_back() {
146 assert(!empty() && "Cannot remove an element when empty!")((!empty() && "Cannot remove an element when empty!")
? static_cast<void> (0) : __assert_fail ("!empty() && \"Cannot remove an element when empty!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/PriorityWorklist.h"
, 146, __PRETTY_FUNCTION__))
;
147 assert(back() != T() && "Cannot have a null element at the back!")((back() != T() && "Cannot have a null element at the back!"
) ? static_cast<void> (0) : __assert_fail ("back() != T() && \"Cannot have a null element at the back!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/PriorityWorklist.h"
, 147, __PRETTY_FUNCTION__))
;
148 M.erase(back());
149 do {
150 V.pop_back();
151 } while (!V.empty() && V.back() == T());
152 }
153
154 LLVM_NODISCARD[[clang::warn_unused_result]] T pop_back_val() {
155 T Ret = back();
9
Calling 'PriorityWorklist::back'
12
Returning from 'PriorityWorklist::back'
13
'Ret' initialized here
156 pop_back();
157 return Ret;
14
Returning pointer (loaded from 'Ret')
158 }
159
160 /// Erase an item from the worklist.
161 ///
162 /// Note that this is constant time due to the nature of the worklist implementation.
163 bool erase(const T& X) {
164 auto I = M.find(X);
165 if (I == M.end())
166 return false;
167
168 assert(V[I->second] == X && "Value not actually at index in map!")((V[I->second] == X && "Value not actually at index in map!"
) ? static_cast<void> (0) : __assert_fail ("V[I->second] == X && \"Value not actually at index in map!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/PriorityWorklist.h"
, 168, __PRETTY_FUNCTION__))
;
169 if (I->second == (ptrdiff_t)(V.size() - 1)) {
170 do {
171 V.pop_back();
172 } while (!V.empty() && V.back() == T());
173 } else {
174 V[I->second] = T();
175 }
176 M.erase(I);
177 return true;
178 }
179
180 /// Erase items from the set vector based on a predicate function.
181 ///
182 /// This is intended to be equivalent to the following code, if we could
183 /// write it:
184 ///
185 /// \code
186 /// V.erase(remove_if(V, P), V.end());
187 /// \endcode
188 ///
189 /// However, PriorityWorklist doesn't expose non-const iterators, making any
190 /// algorithm like remove_if impossible to use.
191 ///
192 /// \returns true if any element is removed.
193 template <typename UnaryPredicate>
194 bool erase_if(UnaryPredicate P) {
195 typename VectorT::iterator E =
196 remove_if(V, TestAndEraseFromMap<UnaryPredicate>(P, M));
197 if (E == V.end())
198 return false;
199 for (auto I = V.begin(); I != E; ++I)
200 if (*I != T())
201 M[*I] = I - V.begin();
202 V.erase(E, V.end());
203 return true;
204 }
205
206 /// Reverse the items in the PriorityWorklist.
207 ///
208 /// This does an in-place reversal. Other kinds of reverse aren't easy to
209 /// support in the face of the worklist semantics.
210
211 /// Completely clear the PriorityWorklist
212 void clear() {
213 M.clear();
214 V.clear();
215 }
216
217private:
218 /// A wrapper predicate designed for use with std::remove_if.
219 ///
220 /// This predicate wraps a predicate suitable for use with std::remove_if to
221 /// call M.erase(x) on each element which is slated for removal. This just
222 /// allows the predicate to be move only which we can't do with lambdas
223 /// today.
224 template <typename UnaryPredicateT>
225 class TestAndEraseFromMap {
226 UnaryPredicateT P;
227 MapT &M;
228
229 public:
230 TestAndEraseFromMap(UnaryPredicateT P, MapT &M)
231 : P(std::move(P)), M(M) {}
232
233 bool operator()(const T &Arg) {
234 if (Arg == T())
235 // Skip null values in the PriorityWorklist.
236 return false;
237
238 if (P(Arg)) {
239 M.erase(Arg);
240 return true;
241 }
242 return false;
243 }
244 };
245
246 /// The map from value to index in the vector.
247 MapT M;
248
249 /// The vector of elements in insertion order.
250 VectorT V;
251};
252
253/// A version of \c PriorityWorklist that selects small size optimized data
254/// structures for the vector and map.
255template <typename T, unsigned N>
256class SmallPriorityWorklist
257 : public PriorityWorklist<T, SmallVector<T, N>,
258 SmallDenseMap<T, ptrdiff_t>> {
259public:
260 SmallPriorityWorklist() = default;
261};
262
263} // end namespace llvm
264
265#endif // LLVM_ADT_PRIORITYWORKLIST_H