LLVM 24.0.0git
LoopPassManager.h
Go to the documentation of this file.
1//===- LoopPassManager.h - Loop pass management -----------------*- 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/// \file
9///
10/// This header provides classes for managing a pipeline of passes over loops
11/// in LLVM IR.
12///
13/// The primary loop pass pipeline is managed in a very particular way to
14/// provide a set of core guarantees:
15/// 1) Loops are, where possible, in simplified form.
16/// 2) Loops are *always* in LCSSA form.
17/// 3) A collection of Loop-specific analysis results are available:
18/// - LoopInfo
19/// - DominatorTree
20/// - ScalarEvolution
21/// - AAManager
22/// 4) All loop passes preserve #1 (where possible), #2, and #3.
23/// 5) Loop passes run over each loop in the loop nest from the innermost to
24/// the outermost. Specifically, all inner loops are processed before
25/// passes run over outer loops. When running the pipeline across an inner
26/// loop creates new inner loops, those are added and processed in this
27/// order as well.
28///
29/// This process is designed to facilitate transformations which simplify,
30/// reduce, and remove loops. For passes which are more oriented towards
31/// optimizing loops, especially optimizing loop *nests* instead of single
32/// loops in isolation, this framework is less interesting.
33///
34//===----------------------------------------------------------------------===//
35
36#ifndef LLVM_TRANSFORMS_SCALAR_LOOPPASSMANAGER_H
37#define LLVM_TRANSFORMS_SCALAR_LOOPPASSMANAGER_H
38
44#include "llvm/IR/PassManager.h"
49#include <memory>
50
51namespace llvm {
52
53// Forward declarations of an update tracking API used in the pass manager.
54class LPMUpdater;
56
57namespace {
58
59template <typename PassT>
60using HasRunOnLoopT = decltype(std::declval<PassT>().run(
61 std::declval<Loop &>(), std::declval<LoopAnalysisManager &>(),
62 std::declval<LoopStandardAnalysisResults &>(),
63 std::declval<LPMUpdater &>()));
64
65} // namespace
66
67// Explicit specialization and instantiation declarations for the pass manager.
68// See the comments on the definition of the specialization for details on how
69// it differs from the primary template.
70template <>
72 LPMUpdater &>
73 : public RequiredPassInfoMixin<
75 LPMUpdater &>> {
76public:
77 explicit PassManager() = default;
78
79 // FIXME: These are equivalent to the default move constructor/move
80 // assignment. However, using = default triggers linker errors due to the
81 // explicit instantiations below. Find a way to use the default and remove the
82 // duplicated code here.
84 : IsLoopNestPass(std::move(Arg.IsLoopNestPass)),
85 LoopPasses(std::move(Arg.LoopPasses)),
86 LoopNestPasses(std::move(Arg.LoopNestPasses)) {}
87
88 PassManager &operator=(PassManager &&RHS) {
89 IsLoopNestPass = std::move(RHS.IsLoopNestPass);
90 LoopPasses = std::move(RHS.LoopPasses);
91 LoopNestPasses = std::move(RHS.LoopNestPasses);
92 return *this;
93 }
94
97 LPMUpdater &U);
98
99 LLVM_ABI void
100 printPipeline(raw_ostream &OS,
101 function_ref<StringRef(StringRef)> MapClassName2PassName);
102 /// Add either a loop pass or a loop-nest pass to the pass manager. Append \p
103 /// Pass to the list of loop passes if it has a dedicated \fn run() method for
104 /// loops and to the list of loop-nest passes if the \fn run() method is for
105 /// loop-nests instead. Also append whether \p Pass is loop-nest pass or not
106 /// to the end of \var IsLoopNestPass so we can easily identify the types of
107 /// passes in the pass manager later.
108 template <typename PassT> LLVM_ATTRIBUTE_MINSIZE void addPass(PassT &&Pass) {
110 using LoopPassModelT =
113 IsLoopNestPass.push_back(false);
114 LoopPasses.push_back(LoopPassModelT::create(std::move(Pass)));
115 } else {
116 using LoopNestPassModelT =
119 IsLoopNestPass.push_back(true);
120 LoopNestPasses.push_back(LoopNestPassModelT::create(std::move(Pass)));
121 }
122 }
123
124 bool isEmpty() const { return LoopPasses.empty() && LoopNestPasses.empty(); }
125
126 size_t getNumLoopPasses() const { return LoopPasses.size(); }
127 size_t getNumLoopNestPasses() const { return LoopNestPasses.size(); }
128
129protected:
130 using LoopPassConceptT =
133 using LoopNestPassConceptT =
136
137 // BitVector that identifies whether the passes are loop passes or loop-nest
138 // passes (true for loop-nest passes).
139 BitVector IsLoopNestPass;
140 std::vector<LoopPassConceptT::unique_ptr> LoopPasses;
141 std::vector<LoopNestPassConceptT::unique_ptr> LoopNestPasses;
142
143 /// Run either a loop pass or a loop-nest pass. Returns `std::nullopt` if
144 /// PassInstrumentation's BeforePass returns false. Otherwise, returns the
145 /// preserved analyses of the pass.
146 template <typename IRUnitT, typename PassT>
147 std::optional<PreservedAnalyses>
148 runSinglePass(IRUnitT &IR, PassT &Pass, LoopAnalysisManager &AM,
151
153 runWithLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
156 runWithoutLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
158
159private:
160 static const Loop &getLoopFromIR(Loop &L) { return L; }
161 static const Loop &getLoopFromIR(LoopNest &LN) {
162 return LN.getOutermostLoop();
163 }
164};
165
166/// The Loop pass manager.
167///
168/// See the documentation for the PassManager template for details. It runs
169/// a sequence of Loop passes over each Loop that the manager is run over. This
170/// typedef serves as a convenient way to refer to this construct.
172 LPMUpdater &>
174
175/// A partial specialization of the require analysis template pass to forward
176/// the extra parameters from a transformation's run method to the
177/// AnalysisManager's getResult.
178template <typename AnalysisT>
186 (void)AM.template getResult<AnalysisT>(L, AR);
187 return PreservedAnalyses::all();
188 }
189 void printPipeline(raw_ostream &OS,
190 function_ref<StringRef(StringRef)> MapClassName2PassName) {
191 auto ClassName = AnalysisT::name();
192 auto PassName = MapClassName2PassName(ClassName);
193 OS << "require<" << PassName << '>';
194 }
195};
196
197/// An alias template to easily name a require analysis loop pass.
198template <typename AnalysisT>
202
204
205/// This class provides an interface for updating the loop pass manager based
206/// on mutations to the loop nest.
207///
208/// A reference to an instance of this class is passed as an argument to each
209/// Loop pass, and Loop passes should use it to update LPM infrastructure if
210/// they modify the loop nest structure.
211///
212/// \c LPMUpdater comes with two modes: the loop mode and the loop-nest mode. In
213/// loop mode, all the loops in the function will be pushed into the worklist
214/// and when new loops are added to the pipeline, their subloops are also
215/// inserted recursively. On the other hand, in loop-nest mode, only top-level
216/// loops are contained in the worklist and the addition of new (top-level)
217/// loops will not trigger the addition of their subloops.
218class LPMUpdater {
219public:
220 /// This can be queried by loop passes which run other loop passes (like pass
221 /// managers) to know whether the loop needs to be skipped due to updates to
222 /// the loop nest.
223 ///
224 /// If this returns true, the loop object may have been deleted, so passes
225 /// should take care not to touch the object.
226 bool skipCurrentLoop() const { return SkipCurrentLoop; }
227
228 /// Loop passes should use this method to indicate they have deleted a loop
229 /// from the nest.
230 ///
231 /// Note that this loop must either be the current loop or a subloop of the
232 /// current loop. This routine must be called prior to removing the loop from
233 /// the loop nest.
234 ///
235 /// If this is called for the current loop, in addition to clearing any
236 /// state, this routine will mark that the current loop should be skipped by
237 /// the rest of the pass management infrastructure.
239 LAM.clear(L, Name);
240 assert((&L == CurrentL || CurrentL->contains(&L)) &&
241 "Cannot delete a loop outside of the "
242 "subloop tree currently being processed.");
243 if (&L == CurrentL)
244 SkipCurrentLoop = true;
245 }
246
248#if LLVM_ENABLE_ABI_BREAKING_CHECKS
249 ParentL = L;
250#endif
251 }
252
253 /// Loop passes should use this method to indicate they have added new child
254 /// loops of the current loop.
255 ///
256 /// \p NewChildLoops must contain only the immediate children. Any nested
257 /// loops within them will be visited in postorder as usual for the loop pass
258 /// manager.
259 void addChildLoops(ArrayRef<Loop *> NewChildLoops) {
260 assert(!LoopNestMode &&
261 "Child loops should not be pushed in loop-nest mode.");
262 // Insert ourselves back into the worklist first, as this loop should be
263 // revisited after all the children have been processed.
264 Worklist.insert(CurrentL);
265
266#ifndef NDEBUG
267 for (Loop *NewL : NewChildLoops)
268 assert(NewL->getParentLoop() == CurrentL && "All of the new loops must "
269 "be immediate children of "
270 "the current loop!");
271#endif
272
273 appendLoopsToWorklist(NewChildLoops, Worklist);
274
275 // Also skip further processing of the current loop--it will be revisited
276 // after all of its newly added children are accounted for.
277 SkipCurrentLoop = true;
278 }
279
280 /// Loop passes should use this method to indicate they have added new
281 /// sibling loops to the current loop.
282 ///
283 /// \p NewSibLoops must only contain the immediate sibling loops. Any nested
284 /// loops within them will be visited in postorder as usual for the loop pass
285 /// manager.
287#if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
288 for (Loop *NewL : NewSibLoops)
289 assert(NewL->getParentLoop() == ParentL &&
290 "All of the new loops must be siblings of the current loop!");
291#endif
292
293 if (LoopNestMode)
294 Worklist.insert(NewSibLoops);
295 else
296 appendLoopsToWorklist(NewSibLoops, Worklist);
297
298 // No need to skip the current loop or revisit it, as sibling loops
299 // shouldn't impact anything.
300 }
301
302 /// Restart the current loop.
303 ///
304 /// Loop passes should call this method to indicate the current loop has been
305 /// sufficiently changed that it should be re-visited from the begining of
306 /// the loop pass pipeline rather than continuing.
308 // Tell the currently in-flight pipeline to stop running.
309 SkipCurrentLoop = true;
310
311 // And insert ourselves back into the worklist.
312 Worklist.insert(CurrentL);
313 }
314
315 bool isLoopNestChanged() const {
316 return LoopNestChanged;
317 }
318
319 /// Loopnest passes should use this method to indicate if the
320 /// loopnest has been modified.
322 LoopNestChanged = Changed;
323 }
324
325private:
327
328 /// The \c FunctionToLoopPassAdaptor's worklist of loops to process.
330
331 /// The analysis manager for use in the current loop nest.
333
334 Loop *CurrentL;
335 bool SkipCurrentLoop;
336 const bool LoopNestMode;
337 bool LoopNestChanged;
338
339#if LLVM_ENABLE_ABI_BREAKING_CHECKS
340 // In debug builds we also track the parent loop to implement asserts even in
341 // the face of loop deletion.
342 Loop *ParentL;
343#endif
344
345 LPMUpdater(SmallPriorityWorklist<Loop *, 4> &Worklist,
346 LoopAnalysisManager &LAM, bool LoopNestMode = false,
347 bool LoopNestChanged = false)
348 : Worklist(Worklist), LAM(LAM), LoopNestMode(LoopNestMode),
349 LoopNestChanged(LoopNestChanged) {}
350};
351
352template <typename IRUnitT, typename PassT>
353std::optional<PreservedAnalyses> LoopPassManager::runSinglePass(
354 IRUnitT &IR, PassT &Pass, LoopAnalysisManager &AM,
355 LoopStandardAnalysisResults &AR, LPMUpdater &U, PassInstrumentation &PI) {
356 // Get the loop in case of Loop pass and outermost loop in case of LoopNest
357 // pass which is to be passed to BeforePass and AfterPass call backs.
358 const Loop &L = getLoopFromIR(IR);
359 // Check the PassInstrumentation's BeforePass callbacks before running the
360 // pass, skip its execution completely if asked to (callback returns false).
361 if (!PI.runBeforePass<Loop>(*Pass, L))
362 return std::nullopt;
363
364 PreservedAnalyses PA = Pass->run(IR, AM, AR, U);
365
366 // do not pass deleted Loop into the instrumentation
367 if (U.skipCurrentLoop())
368 PI.runAfterPassInvalidated<IRUnitT>(*Pass, PA);
369 else
370 PI.runAfterPass<Loop>(*Pass, L, PA);
371 return PA;
372}
373
374/// Adaptor that maps from a function to its loops.
375///
376/// Designed to allow composition of a LoopPass(Manager) and a
377/// FunctionPassManager. Note that if this pass is constructed with a \c
378/// FunctionAnalysisManager it will run the \c LoopAnalysisManagerFunctionProxy
379/// analysis prior to running the loop passes over the function to enable a \c
380/// LoopAnalysisManager to be used within this run safely.
381///
382/// The adaptor comes with two modes: the loop mode and the loop-nest mode, and
383/// the worklist updater lived inside will be in the same mode as the adaptor
384/// (refer to the documentation of \c LPMUpdater for more detailed explanation).
385/// Specifically, in loop mode, all loops in the function will be pushed into
386/// the worklist and processed by \p Pass, while only top-level loops are
387/// processed in loop-nest mode. Please refer to the various specializations of
388/// \fn createLoopFunctionToLoopPassAdaptor to see when loop mode and loop-nest
389/// mode are used.
391 : public RequiredPassInfoMixin<FunctionToLoopPassAdaptor> {
392public:
396
398 bool UseMemorySSA = false,
399 bool LoopNestMode = false)
400 : Pass(std::move(Pass)), UseMemorySSA(UseMemorySSA),
401 LoopNestMode(LoopNestMode) {
402 LoopCanonicalizationFPM.addPass(LoopSimplifyPass());
403 LoopCanonicalizationFPM.addPass(LCSSAPass());
404 }
405
406 /// Runs the loop passes across every loop in the function.
408 LLVM_ABI void
410 function_ref<StringRef(StringRef)> MapClassName2PassName);
411
412 bool isLoopNestMode() const { return LoopNestMode; }
413
414private:
416
417 FunctionPassManager LoopCanonicalizationFPM;
418
419 bool UseMemorySSA = false;
420 const bool LoopNestMode;
421};
422
423/// A function to deduce a loop pass type and wrap it in the templated
424/// adaptor.
425///
426/// If \p Pass is a loop pass, the returned adaptor will be in loop mode.
427///
428/// If \p Pass is a loop-nest pass, \p Pass will first be wrapped into a
429/// \c LoopPassManager and the returned adaptor will be in loop-nest mode.
430template <typename LoopPassT>
431inline FunctionToLoopPassAdaptor
432createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA = false) {
434 using PassModelT =
437 return FunctionToLoopPassAdaptor(PassModelT::create(std::move(Pass)),
438 UseMemorySSA, false);
439 } else {
440 LoopPassManager LPM;
441 LPM.addPass(std::move(Pass));
442 using PassModelT =
445 return FunctionToLoopPassAdaptor(PassModelT::create(std::move(LPM)),
446 UseMemorySSA, true);
447 }
448}
449
450/// If \p Pass is an instance of \c LoopPassManager, the returned adaptor will
451/// be in loop-nest mode if the pass manager contains only loop-nest passes.
452template <>
455 bool UseMemorySSA) {
456 // Check if LPM contains any loop pass and if it does not, returns an adaptor
457 // in loop-nest mode.
458 using PassModelT =
461 bool LoopNestMode = (LPM.getNumLoopPasses() == 0);
462 return FunctionToLoopPassAdaptor(PassModelT::create(std::move(LPM)),
463 UseMemorySSA, LoopNestMode);
464}
465
466/// Pass for printing a loop's contents as textual IR.
467class PrintLoopPass : public RequiredPassInfoMixin<PrintLoopPass> {
468 raw_ostream &OS;
469 std::string Banner;
470
471public:
473 LLVM_ABI PrintLoopPass(raw_ostream &OS, const std::string &Banner = "");
474
477};
478}
479
480#endif // LLVM_TRANSFORMS_SCALAR_LOOPPASSMANAGER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_ATTRIBUTE_MINSIZE
Definition Compiler.h:330
This header defines various interfaces for pass management in LLVM.
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:81
This header provides classes for managing per-loop analyses.
This file defines the interface for the loop nest analysis.
#define F(x, y, z)
Definition MD5.cpp:54
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:598
This file defines the Pass Instrumentation classes that provide instrumentation points into the pass ...
This file provides a priority worklist.
static const char PassName[]
Value * RHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
FunctionToLoopPassAdaptor(PassConceptT::unique_ptr Pass, bool UseMemorySSA=false, bool LoopNestMode=false)
detail::PassConcept< Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > PassConceptT
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Runs the loop passes across every loop in the function.
Converts loops into loop-closed SSA form.
Definition LCSSA.h:38
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
void markLoopNestChanged(bool Changed)
Loopnest passes should use this method to indicate if the loopnest has been modified.
void setParentLoop(Loop *L)
bool isLoopNestChanged() const
void revisitCurrentLoop()
Restart the current loop.
bool skipCurrentLoop() const
This can be queried by loop passes which run other loop passes (like pass managers) to know whether t...
void addChildLoops(ArrayRef< Loop * > NewChildLoops)
Loop passes should use this method to indicate they have added new child loops of the current loop.
void markLoopAsDeleted(Loop &L, llvm::StringRef Name)
Loop passes should use this method to indicate they have deleted a loop from the nest.
void addSiblingLoops(ArrayRef< Loop * > NewSibLoops)
Loop passes should use this method to indicate they have added new sibling loops to the current loop.
const LoopT * getOutermostLoop() const
Get the outermost loop in which this loop is contained.
This class represents a loop nest and can be used to query its properties.
This pass is responsible for loop canonicalization.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class provides instrumentation entry points for the Pass Manager, doing calls to callbacks regis...
Manages a sequence of passes over a particular unit of IR.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
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
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &, LoopStandardAnalysisResults &, LPMUpdater &)
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Template for the abstract base class used to dispatch over pass objects.
A template wrapper used to implement PassConcept.
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
Changed
DXILDebugInfoMap run(Module &M)
This is an optimization pass for GlobalISel generic memory operations.
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
PassManager< Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > LoopPassManager
The Loop pass manager.
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
LLVM_TEMPLATE_ABI void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
typename detail::detector< void, Op, Args... >::value_t is_detected
Detects if a given trait holds for some set of arguments 'Args'.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor< LoopPassManager >(LoopPassManager &&LPM, bool UseMemorySSA)
If Pass is an instance of LoopPassManager, the returned adaptor will be in loop-nest mode if the pass...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
RequireAnalysisPass< AnalysisT, Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > RequireAnalysisLoopPass
An alias template to easily name a require analysis loop pass.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
A CRTP mix-in for passes that can be skipped.
A utility pass template to force an analysis result to be available.
A CRTP mix-in for passes that should not be skipped.