LLVM 22.0.0git
LoopPassManager.cpp
Go to the documentation of this file.
1//===- LoopPassManager.cpp - Loop pass management -------------------------===//
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
16
17using namespace llvm;
18
19namespace llvm {
20
21/// Explicitly specialize the pass manager's run method to handle loop nest
22/// structure updates.
25 LPMUpdater &>::run(Loop &L, LoopAnalysisManager &AM,
27 // Runs loop-nest passes only when the current loop is a top-level one.
28 PreservedAnalyses PA = (L.isOutermost() && !LoopNestPasses.empty())
29 ? runWithLoopNestPasses(L, AM, AR, U)
30 : runWithoutLoopNestPasses(L, AM, AR, U);
31
32 // Invalidation for the current loop should be handled above, and other loop
33 // analysis results shouldn't be impacted by runs over this loop. Therefore,
34 // the remaining analysis results in the AnalysisManager are preserved. We
35 // mark this with a set so that we don't need to inspect each one
36 // individually.
37 // FIXME: This isn't correct! This loop and all nested loops' analyses should
38 // be preserved, but unrolling should invalidate the parent loop's analyses.
40
41 return PA;
42}
43
45 LPMUpdater &>::printPipeline(raw_ostream &OS,
47 MapClassName2PassName) {
48 assert(LoopPasses.size() + LoopNestPasses.size() == IsLoopNestPass.size());
49
50 unsigned IdxLP = 0, IdxLNP = 0;
51 for (unsigned Idx = 0, Size = IsLoopNestPass.size(); Idx != Size; ++Idx) {
52 if (IsLoopNestPass[Idx]) {
53 auto *P = LoopNestPasses[IdxLNP++].get();
54 P->printPipeline(OS, MapClassName2PassName);
55 } else {
56 auto *P = LoopPasses[IdxLP++].get();
57 P->printPipeline(OS, MapClassName2PassName);
58 }
59 if (Idx + 1 < Size)
60 OS << ',';
61 }
62}
63
64// Run both loop passes and loop-nest passes on top-level loop \p L.
66LoopPassManager::runWithLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
68 LPMUpdater &U) {
69 assert(L.isOutermost() &&
70 "Loop-nest passes should only run on top-level loops.");
71 PreservedAnalyses PA = PreservedAnalyses::all();
72
73 // Request PassInstrumentation from analysis manager, will use it to run
74 // instrumenting callbacks for the passes later.
75 PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR);
76
77 unsigned LoopPassIndex = 0, LoopNestPassIndex = 0;
78
79 // `LoopNestPtr` points to the `LoopNest` object for the current top-level
80 // loop and `IsLoopNestPtrValid` indicates whether the pointer is still valid.
81 // The `LoopNest` object will have to be re-constructed if the pointer is
82 // invalid when encountering a loop-nest pass.
83 std::unique_ptr<LoopNest> LoopNestPtr;
84 bool IsLoopNestPtrValid = false;
85 Loop *OuterMostLoop = &L;
86
87 for (size_t I = 0, E = IsLoopNestPass.size(); I != E; ++I) {
88 std::optional<PreservedAnalyses> PassPA;
89 if (!IsLoopNestPass[I]) {
90 // The `I`-th pass is a loop pass.
91 auto &Pass = LoopPasses[LoopPassIndex++];
92 PassPA = runSinglePass(L, Pass, AM, AR, U, PI);
93 } else {
94 // The `I`-th pass is a loop-nest pass.
95 auto &Pass = LoopNestPasses[LoopNestPassIndex++];
96
97 // If the loop-nest object calculated before is no longer valid,
98 // re-calculate it here before running the loop-nest pass.
99 //
100 // FIXME: PreservedAnalysis should not be abused to tell if the
101 // status of loopnest has been changed. We should use and only
102 // use LPMUpdater for this purpose.
103 if (!IsLoopNestPtrValid || U.isLoopNestChanged()) {
104 while (auto *ParentLoop = OuterMostLoop->getParentLoop())
105 OuterMostLoop = ParentLoop;
106 LoopNestPtr = LoopNest::getLoopNest(*OuterMostLoop, AR.SE);
107 IsLoopNestPtrValid = true;
108 U.markLoopNestChanged(false);
109 }
110
111 PassPA = runSinglePass(*LoopNestPtr, Pass, AM, AR, U, PI);
112 }
113
114 // `PassPA` is `None` means that the before-pass callbacks in
115 // `PassInstrumentation` return false. The pass does not run in this case,
116 // so we can skip the following procedure.
117 if (!PassPA)
118 continue;
119
120 // If the loop was deleted, abort the run and return to the outer walk.
121 if (U.skipCurrentLoop()) {
122 PA.intersect(std::move(*PassPA));
123 break;
124 }
125
126 // Update the analysis manager as each pass runs and potentially
127 // invalidates analyses.
128 AM.invalidate(IsLoopNestPass[I] ? *OuterMostLoop : L, *PassPA);
129
130 // Finally, we intersect the final preserved analyses to compute the
131 // aggregate preserved set for this pass manager.
132 PA.intersect(std::move(*PassPA));
133
134 // Check if the current pass preserved the loop-nest object or not.
135 IsLoopNestPtrValid &= PassPA->getChecker<LoopNestAnalysis>().preserved();
136
137 // After running the loop pass, the parent loop might change and we need to
138 // notify the updater, otherwise U.ParentL might gets outdated and triggers
139 // assertion failures in addSiblingLoops and addChildLoops.
140 U.setParentLoop((IsLoopNestPass[I] ? *OuterMostLoop : L).getParentLoop());
141 }
142 return PA;
143}
144
145// Run all loop passes on loop \p L. Loop-nest passes don't run either because
146// \p L is not a top-level one or simply because there are no loop-nest passes
147// in the pass manager at all.
149LoopPassManager::runWithoutLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
151 LPMUpdater &U) {
152 PreservedAnalyses PA = PreservedAnalyses::all();
153
154 // Request PassInstrumentation from analysis manager, will use it to run
155 // instrumenting callbacks for the passes later.
156 PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR);
157 for (auto &Pass : LoopPasses) {
158 std::optional<PreservedAnalyses> PassPA =
159 runSinglePass(L, Pass, AM, AR, U, PI);
160
161 // `PassPA` is `None` means that the before-pass callbacks in
162 // `PassInstrumentation` return false. The pass does not run in this case,
163 // so we can skip the following procedure.
164 if (!PassPA)
165 continue;
166
167 // If the loop was deleted, abort the run and return to the outer walk.
168 if (U.skipCurrentLoop()) {
169 PA.intersect(std::move(*PassPA));
170 break;
171 }
172
173 // Update the analysis manager as each pass runs and potentially
174 // invalidates analyses.
175 AM.invalidate(L, *PassPA);
176
177 // Finally, we intersect the final preserved analyses to compute the
178 // aggregate preserved set for this pass manager.
179 PA.intersect(std::move(*PassPA));
180
181 // After running the loop pass, the parent loop might change and we need to
182 // notify the updater, otherwise U.ParentL might gets outdated and triggers
183 // assertion failures in addSiblingLoops and addChildLoops.
184 U.setParentLoop(L.getParentLoop());
185 }
186 return PA;
187}
188} // namespace llvm
189
191 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
192 OS << (UseMemorySSA ? "loop-mssa(" : "loop(");
193 Pass->printPipeline(OS, MapClassName2PassName);
194 OS << ')';
195}
198 // Before we even compute any loop analyses, first run a miniature function
199 // pass pipeline to put loops into their canonical form. Note that we can
200 // directly build up function analyses after this as the function pass
201 // manager handles all the invalidation at that layer.
203
205 // Check the PassInstrumentation's BeforePass callbacks before running the
206 // canonicalization pipeline.
207 if (PI.runBeforePass<Function>(LoopCanonicalizationFPM, F)) {
208 PA = LoopCanonicalizationFPM.run(F, AM);
209 PI.runAfterPass<Function>(LoopCanonicalizationFPM, F, PA);
210 }
211
212 // Get the loop structure for this function
213 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
214
215 // If there are no loops, there is nothing to do here.
216 if (LI.empty())
217 return PA;
218
219 // Get the analysis results needed by loop passes.
220 MemorySSA *MSSA =
221 UseMemorySSA ? (&AM.getResult<MemorySSAAnalysis>(F).getMSSA()) : nullptr;
222 BlockFrequencyInfo *BFI = UseBlockFrequencyInfo && F.hasProfileData()
224 : nullptr;
232 BFI,
233 MSSA};
234
235 // Setup the loop analysis manager from its proxy. It is important that
236 // this is only done when there are loops to process and we have built the
237 // LoopStandardAnalysisResults object. The loop analyses cached in this
238 // manager have access to those analysis results and so it must invalidate
239 // itself when they go away.
240 auto &LAMFP = AM.getResult<LoopAnalysisManagerFunctionProxy>(F);
241 if (UseMemorySSA)
242 LAMFP.markMSSAUsed();
243 LoopAnalysisManager &LAM = LAMFP.getManager();
244
245 // A postorder worklist of loops to process.
247
248 // Register the worklist and loop analysis manager so that loop passes can
249 // update them when they mutate the loop nest structure.
250 LPMUpdater Updater(Worklist, LAM, LoopNestMode);
251
252 // Add the loop nests in the reverse order of LoopInfo. See method
253 // declaration.
254 if (!LoopNestMode) {
255 appendLoopsToWorklist(LI, Worklist);
256 } else {
257 for (Loop *L : LI)
258 Worklist.insert(L);
259 }
260
261#ifndef NDEBUG
262 PI.pushBeforeNonSkippedPassCallback([&LAR, &LI](StringRef PassID, Any IR) {
263 if (isSpecialPass(PassID, {"PassManager"}))
264 return;
266 const Loop **LPtr = llvm::any_cast<const Loop *>(&IR);
267 const Loop *L = LPtr ? *LPtr : nullptr;
268 assert(L && "Loop should be valid for printing");
269
270 // Verify the loop structure and LCSSA form before visiting the loop.
271 L->verifyLoop();
272 assert(L->isRecursivelyLCSSAForm(LAR.DT, LI) &&
273 "Loops must remain in LCSSA form!");
274 });
275#endif
276
277 do {
278 Loop *L = Worklist.pop_back_val();
279 assert(!(LoopNestMode && L->getParentLoop()) &&
280 "L should be a top-level loop in loop-nest mode.");
281
282 // Reset the update structure for this loop.
283 Updater.CurrentL = L;
284 Updater.SkipCurrentLoop = false;
285
286#if LLVM_ENABLE_ABI_BREAKING_CHECKS
287 // Save a parent loop pointer for asserts.
288 Updater.ParentL = L->getParentLoop();
289#endif
290 // Check the PassInstrumentation's BeforePass callbacks before running the
291 // pass, skip its execution completely if asked to (callback returns
292 // false).
293 if (!PI.runBeforePass<Loop>(*Pass, *L))
294 continue;
295
296 PreservedAnalyses PassPA = Pass->run(*L, LAM, LAR, Updater);
297
298 // Do not pass deleted Loop into the instrumentation.
299 if (Updater.skipCurrentLoop())
300 PI.runAfterPassInvalidated<Loop>(*Pass, PassPA);
301 else
302 PI.runAfterPass<Loop>(*Pass, *L, PassPA);
303
304 if (LAR.MSSA && !PassPA.getChecker<MemorySSAAnalysis>().preserved())
305 reportFatalUsageError("Loop pass manager using MemorySSA contains a pass "
306 "that does not preserve MemorySSA");
307
308#ifndef NDEBUG
309 // LoopAnalysisResults should always be valid.
310 if (VerifyDomInfo)
311 LAR.DT.verify();
312 if (VerifyLoopInfo)
313 LAR.LI.verify(LAR.DT);
314 if (VerifySCEV)
315 LAR.SE.verify();
316 if (LAR.MSSA && VerifyMemorySSA)
317 LAR.MSSA->verifyMemorySSA();
318#endif
319
320 // If the loop hasn't been deleted, we need to handle invalidation here.
321 if (!Updater.skipCurrentLoop())
322 // We know that the loop pass couldn't have invalidated any other
323 // loop's analyses (that's the contract of a loop pass), so directly
324 // handle the loop analysis manager's invalidation here.
325 LAM.invalidate(*L, PassPA);
326
327 // Then intersect the preserved set so that invalidation of module
328 // analyses will eventually occur when the module pass completes.
329 PA.intersect(std::move(PassPA));
330 } while (!Worklist.empty());
331
332#ifndef NDEBUG
334#endif
335
336 // By definition we preserve the proxy. We also preserve all analyses on
337 // Loops. This precludes *any* invalidation of loop analyses by the proxy,
338 // but that's OK because we've taken care to invalidate analyses in the
339 // loop analysis manager incrementally above.
340 PA.preserveSet<AllAnalysesOn<Loop>>();
341 PA.preserve<LoopAnalysisManagerFunctionProxy>();
342 // We also preserve the set of standard analyses.
343 PA.preserve<DominatorTreeAnalysis>();
344 PA.preserve<LoopAnalysis>();
345 PA.preserve<ScalarEvolutionAnalysis>();
346 if (UseMemorySSA)
347 PA.preserve<MemorySSAAnalysis>();
348 return PA;
349}
350
352PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner)
353 : OS(OS), Banner(Banner) {}
354
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:80
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define P(N)
LoopAnalysisManager LAM
Shrink Wrap Pass
This pass exposes codegen information to IR-level passes.
A manager for alias analyses.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis pass which computes a DominatorTree.
Definition Dominators.h:284
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Runs the loop passes across every loop in the function.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
bool skipCurrentLoop() const
This can be queried by loop passes which run other loop passes (like pass managers) to know whether t...
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:569
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
static std::unique_ptr< LoopNest > getLoopNest(Loop &Root, ScalarEvolution &SE)
Construct a LoopNest object.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:936
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
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 pushBeforeNonSkippedPassCallback(CallableT C)
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.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
void intersect(const PreservedAnalyses &Arg)
Intersect this set with another in place.
Definition Analysis.h:193
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &, LoopStandardAnalysisResults &, LPMUpdater &)
bool empty() const
Determine if the PriorityWorklist is empty or not.
bool insert(const T &X)
Insert a new element into the PriorityWorklist.
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI void verify() const
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
T any_cast(const Any &Value)
Definition Any.h:137
LLVM_ABI bool VerifySCEV
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_TEMPLATE_ABI void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
LLVM_ABI bool isSpecialPass(StringRef PassID, const std::vector< StringRef > &Specials)
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
Definition LoopInfo.cpp:51
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:84
LLVM_ABI bool VerifyDomInfo
Enables verification of dominator trees.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
Definition LoopInfo.cpp:989
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:180
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...