LLVM  4.0.0
LoopPassManager.h
Go to the documentation of this file.
1 //===- LoopPassManager.h - Loop pass management -----------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
11 /// This header provides classes for managing a pipeline of passes over loops
12 /// in LLVM IR.
13 ///
14 /// The primary loop pass pipeline is managed in a very particular way to
15 /// provide a set of core guarantees:
16 /// 1) Loops are, where possible, in simplified form.
17 /// 2) Loops are *always* in LCSSA form.
18 /// 3) A collection of Loop-specific analysis results are available:
19 /// - LoopInfo
20 /// - DominatorTree
21 /// - ScalarEvolution
22 /// - AAManager
23 /// 4) All loop passes preserve #1 (where possible), #2, and #3.
24 /// 5) Loop passes run over each loop in the loop nest from the innermost to
25 /// the outermost. Specifically, all inner loops are processed before
26 /// passes run over outer loops. When running the pipeline across an inner
27 /// loop creates new inner loops, those are added and processed in this
28 /// order as well.
29 ///
30 /// This process is designed to facilitate transformations which simplify,
31 /// reduce, and remove loops. For passes which are more oriented towards
32 /// optimizing loops, especially optimizing loop *nests* instead of single
33 /// loops in isolation, this framework is less interesting.
34 ///
35 //===----------------------------------------------------------------------===//
36 
37 #ifndef LLVM_TRANSFORMS_SCALAR_LOOPPASSMANAGER_H
38 #define LLVM_TRANSFORMS_SCALAR_LOOPPASSMANAGER_H
39 
42 #include "llvm/ADT/STLExtras.h"
47 #include "llvm/Analysis/LoopInfo.h"
52 #include "llvm/IR/Dominators.h"
53 #include "llvm/IR/PassManager.h"
54 
55 namespace llvm {
56 
57 // Forward declarations of an update tracking API used in the pass manager.
58 class LPMUpdater;
59 
60 // Explicit specialization and instantiation declarations for the pass manager.
61 // See the comments on the definition of the specialization for details on how
62 // it differs from the primary template.
63 template <>
64 PreservedAnalyses
65 PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &,
66  LPMUpdater &>::run(Loop &InitialL, LoopAnalysisManager &AM,
67  LoopStandardAnalysisResults &AnalysisResults,
68  LPMUpdater &U);
69 extern template class PassManager<Loop, LoopAnalysisManager,
70  LoopStandardAnalysisResults &, LPMUpdater &>;
71 
72 /// \brief The Loop pass manager.
73 ///
74 /// See the documentation for the PassManager template for details. It runs
75 /// a sequence of Loop passes over each Loop that the manager is run over. This
76 /// typedef serves as a convenient way to refer to this construct.
77 typedef PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &,
78  LPMUpdater &>
80 
81 /// A partial specialization of the require analysis template pass to forward
82 /// the extra parameters from a transformation's run method to the
83 /// AnalysisManager's getResult.
84 template <typename AnalysisT>
87  : PassInfoMixin<
92  (void)AM.template getResult<AnalysisT>(L, AR);
93  return PreservedAnalyses::all();
94  }
95 };
96 
97 /// An alias template to easily name a require analysis loop pass.
98 template <typename AnalysisT>
100  RequireAnalysisPass<AnalysisT, Loop, LoopAnalysisManager,
102 
103 namespace internal {
104 /// Helper to implement appending of loops onto a worklist.
105 ///
106 /// We want to process loops in postorder, but the worklist is a LIFO data
107 /// structure, so we append to it in *reverse* postorder.
108 ///
109 /// For trees, a preorder traversal is a viable reverse postorder, so we
110 /// actually append using a preorder walk algorithm.
111 template <typename RangeT>
112 inline void appendLoopsToWorklist(RangeT &&Loops,
114  // We use an internal worklist to build up the preorder traversal without
115  // recursion.
116  SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
117 
118  // We walk the initial sequence of loops in reverse because we generally want
119  // to visit defs before uses and the worklist is LIFO.
120  for (Loop *RootL : reverse(Loops)) {
121  assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
122  assert(PreOrderWorklist.empty() &&
123  "Must start with an empty preorder walk worklist.");
124  PreOrderWorklist.push_back(RootL);
125  do {
126  Loop *L = PreOrderWorklist.pop_back_val();
127  PreOrderWorklist.append(L->begin(), L->end());
128  PreOrderLoops.push_back(L);
129  } while (!PreOrderWorklist.empty());
130 
131  Worklist.insert(std::move(PreOrderLoops));
132  PreOrderLoops.clear();
133  }
134 }
135 }
136 
137 template <typename LoopPassT> class FunctionToLoopPassAdaptor;
138 
139 /// This class provides an interface for updating the loop pass manager based
140 /// on mutations to the loop nest.
141 ///
142 /// A reference to an instance of this class is passed as an argument to each
143 /// Loop pass, and Loop passes should use it to update LPM infrastructure if
144 /// they modify the loop nest structure.
145 class LPMUpdater {
146 public:
147  /// This can be queried by loop passes which run other loop passes (like pass
148  /// managers) to know whether the loop needs to be skipped due to updates to
149  /// the loop nest.
150  ///
151  /// If this returns true, the loop object may have been deleted, so passes
152  /// should take care not to touch the object.
153  bool skipCurrentLoop() const { return SkipCurrentLoop; }
154 
155  /// Loop passes should use this method to indicate they have deleted a loop
156  /// from the nest.
157  ///
158  /// Note that this loop must either be the current loop or a subloop of the
159  /// current loop. This routine must be called prior to removing the loop from
160  /// the loop nest.
161  ///
162  /// If this is called for the current loop, in addition to clearing any
163  /// state, this routine will mark that the current loop should be skipped by
164  /// the rest of the pass management infrastructure.
166  LAM.clear(L);
167  assert(CurrentL->contains(&L) && "Cannot delete a loop outside of the "
168  "subloop tree currently being processed.");
169  if (&L == CurrentL)
170  SkipCurrentLoop = true;
171  }
172 
173  /// Loop passes should use this method to indicate they have added new child
174  /// loops of the current loop.
175  ///
176  /// \p NewChildLoops must contain only the immediate children. Any nested
177  /// loops within them will be visited in postorder as usual for the loop pass
178  /// manager.
179  void addChildLoops(ArrayRef<Loop *> NewChildLoops) {
180  // Insert ourselves back into the worklist first, as this loop should be
181  // revisited after all the children have been processed.
182  Worklist.insert(CurrentL);
183 
184 #ifndef NDEBUG
185  for (Loop *NewL : NewChildLoops)
186  assert(NewL->getParentLoop() == CurrentL && "All of the new loops must "
187  "be immediate children of "
188  "the current loop!");
189 #endif
190 
191  internal::appendLoopsToWorklist(NewChildLoops, Worklist);
192 
193  // Also skip further processing of the current loop--it will be revisited
194  // after all of its newly added children are accounted for.
195  SkipCurrentLoop = true;
196  }
197 
198  /// Loop passes should use this method to indicate they have added new
199  /// sibling loops to the current loop.
200  ///
201  /// \p NewSibLoops must only contain the immediate sibling loops. Any nested
202  /// loops within them will be visited in postorder as usual for the loop pass
203  /// manager.
204  void addSiblingLoops(ArrayRef<Loop *> NewSibLoops) {
205 #ifndef NDEBUG
206  for (Loop *NewL : NewSibLoops)
207  assert(NewL->getParentLoop() == ParentL &&
208  "All of the new loops must be siblings of the current loop!");
209 #endif
210 
211  internal::appendLoopsToWorklist(NewSibLoops, Worklist);
212 
213  // No need to skip the current loop or revisit it, as sibling loops
214  // shouldn't impact anything.
215  }
216 
217 private:
218  template <typename LoopPassT> friend class llvm::FunctionToLoopPassAdaptor;
219 
220  /// The \c FunctionToLoopPassAdaptor's worklist of loops to process.
222 
223  /// The analysis manager for use in the current loop nest.
224  LoopAnalysisManager &LAM;
225 
226  Loop *CurrentL;
227  bool SkipCurrentLoop;
228 
229 #ifndef NDEBUG
230  // In debug builds we also track the parent loop to implement asserts even in
231  // the face of loop deletion.
232  Loop *ParentL;
233 #endif
234 
236  LoopAnalysisManager &LAM)
237  : Worklist(Worklist), LAM(LAM) {}
238 };
239 
240 /// \brief Adaptor that maps from a function to its loops.
241 ///
242 /// Designed to allow composition of a LoopPass(Manager) and a
243 /// FunctionPassManager. Note that if this pass is constructed with a \c
244 /// FunctionAnalysisManager it will run the \c LoopAnalysisManagerFunctionProxy
245 /// analysis prior to running the loop passes over the function to enable a \c
246 /// LoopAnalysisManager to be used within this run safely.
247 template <typename LoopPassT>
248 class FunctionToLoopPassAdaptor
249  : public PassInfoMixin<FunctionToLoopPassAdaptor<LoopPassT>> {
250 public:
251  explicit FunctionToLoopPassAdaptor(LoopPassT Pass) : Pass(std::move(Pass)) {}
252 
253  /// \brief Runs the loop passes across every loop in the function.
255  // Setup the loop analysis manager from its proxy.
256  LoopAnalysisManager &LAM =
257  AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
258  // Get the loop structure for this function
259  LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
260 
261  // If there are no loops, there is nothing to do here.
262  if (LI.empty())
263  return PreservedAnalyses::all();
264 
265  // Get the analysis results needed by loop passes.
269  AM.getResult<LoopAnalysis>(F),
273 
275 
276  // A postorder worklist of loops to process.
278 
279  // Register the worklist and loop analysis manager so that loop passes can
280  // update them when they mutate the loop nest structure.
281  LPMUpdater Updater(Worklist, LAM);
282 
283  // Add the loop nests in the reverse order of LoopInfo. For some reason,
284  // they are stored in RPO w.r.t. the control flow graph in LoopInfo. For
285  // the purpose of unrolling, loop deletion, and LICM, we largely want to
286  // work forward across the CFG so that we visit defs before uses and can
287  // propagate simplifications from one loop nest into the next.
288  // FIXME: Consider changing the order in LoopInfo.
290 
291  do {
292  Loop *L = Worklist.pop_back_val();
293 
294  // Reset the update structure for this loop.
295  Updater.CurrentL = L;
296  Updater.SkipCurrentLoop = false;
297 #ifndef NDEBUG
298  Updater.ParentL = L->getParentLoop();
299 #endif
300 
301  PreservedAnalyses PassPA = Pass.run(*L, LAM, LAR, Updater);
302  // FIXME: We should verify the set of analyses relevant to Loop passes
303  // are preserved.
304 
305  // If the loop hasn't been deleted, we need to handle invalidation here.
306  if (!Updater.skipCurrentLoop())
307  // We know that the loop pass couldn't have invalidated any other
308  // loop's analyses (that's the contract of a loop pass), so directly
309  // handle the loop analysis manager's invalidation here.
310  LAM.invalidate(*L, PassPA);
311 
312  // Then intersect the preserved set so that invalidation of module
313  // analyses will eventually occur when the module pass completes.
314  PA.intersect(std::move(PassPA));
315  } while (!Worklist.empty());
316 
317  // By definition we preserve the proxy. We also preserve all analyses on
318  // Loops. This precludes *any* invalidation of loop analyses by the proxy,
319  // but that's OK because we've taken care to invalidate analyses in the
320  // loop analysis manager incrementally above.
321  PA.preserveSet<AllAnalysesOn<Loop>>();
322  PA.preserve<LoopAnalysisManagerFunctionProxy>();
323  // We also preserve the set of standard analyses.
324  PA.preserve<AssumptionAnalysis>();
325  PA.preserve<DominatorTreeAnalysis>();
326  PA.preserve<LoopAnalysis>();
327  PA.preserve<ScalarEvolutionAnalysis>();
328  // FIXME: What we really want to do here is preserve an AA category, but
329  // that concept doesn't exist yet.
330  PA.preserve<AAManager>();
331  PA.preserve<BasicAA>();
332  PA.preserve<GlobalsAA>();
333  PA.preserve<SCEVAA>();
334  return PA;
335  }
336 
337 private:
338  LoopPassT Pass;
339 };
340 
341 /// \brief A function to deduce a loop pass type and wrap it in the templated
342 /// adaptor.
343 template <typename LoopPassT>
346  return FunctionToLoopPassAdaptor<LoopPassT>(std::move(Pass));
347 }
348 
349 /// \brief Pass for printing a loop's contents as textual IR.
350 class PrintLoopPass : public PassInfoMixin<PrintLoopPass> {
351  raw_ostream &OS;
352  std::string Banner;
353 
354 public:
355  PrintLoopPass();
356  PrintLoopPass(raw_ostream &OS, const std::string &Banner = "");
357 
360 };
361 }
362 
363 #endif // LLVM_TRANSFORMS_SCALAR_LOOPPASSMANAGER_H
MachineLoop * L
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:81
This file provides a priority worklist.
bool empty() const
Definition: LoopInfo.h:571
bool insert(const T &X)
Insert a new element into the PriorityWorklist.
This is the interface for a simple mod/ref and alias analysis over globals.
Analysis pass providing the TargetTransformInfo.
LoopT * getParentLoop() const
Definition: LoopInfo.h:103
RequireAnalysisPass< AnalysisT, Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > RequireAnalysisLoopPass
An alias template to easily name a require analysis loop pass.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:189
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &)
A utility pass template to force an analysis result to be available.
Definition: PassManager.h:1183
Hexagon Hardware Loops
This is the interface for a SCEV-based alias analysis.
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:806
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:241
#define F(x, y, z)
Definition: MD5.cpp:51
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:311
Adaptor that maps from a function to its loops.
This header provides classes for managing per-loop analyses.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
iterator begin() const
Definition: LoopInfo.h:132
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:107
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:653
FunctionToLoopPassAdaptor(LoopPassT Pass)
void addChildLoops(ArrayRef< Loop * > NewChildLoops)
Loop passes should use this method to indicate they have added new child loops of the current loop...
A manager for alias analyses.
iterator end() const
Definition: LoopInfo.h:133
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:109
Analysis pass providing a never-invalidated alias analysis result.
Analysis pass providing a never-invalidated alias analysis result.
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:392
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:113
void addSiblingLoops(ArrayRef< Loop * > NewSibLoops)
Loop passes should use this method to indicate they have added new sibling loops to the current loop...
FunctionToLoopPassAdaptor< LoopPassT > createFunctionToLoopPassAdaptor(LoopPassT Pass)
A function to deduce a loop pass type and wrap it in the templated adaptor.
void clear(IRUnitT &IR)
Clear any cached analysis results for a single unit of IR.
Definition: PassManager.h:623
A function analysis which provides an AssumptionCache.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Pass for printing a loop's contents as textual IR.
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:382
void invalidate(IRUnitT &IR)
Invalidate a specific analysis pass for an IR module.
Definition: PassManager.h:722
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Runs the loop passes across every loop in the function.
Analysis pass that exposes the ScalarEvolution for a function.
Analysis pass providing a never-invalidated alias analysis result.
PassManager< Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > LoopPassManager
The Loop pass manager.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:368
void appendLoopsToWorklist(RangeT &&Loops, SmallPriorityWorklist< Loop *, 4 > &Worklist)
Helper to implement appending of loops onto a worklist.
bool skipCurrentLoop() const
This can be queried by loop passes which run other loop passes (like pass managers) to know whether t...
Analysis pass providing the TargetLibraryInfo.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This templated class represents "all analyses that operate over \<a particular IR unit\>" (e...
Definition: PassManager.h:361
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
This is the interface for LLVM's primary stateless and local alias analysis.
A container for analyses that lazily runs them and caches their results.
This pass exposes codegen information to IR-level passes.
This header defines various interfaces for pass management in LLVM.
void markLoopAsDeleted(Loop &L)
Loop passes should use this method to indicate they have deleted a loop from the nest.
bool empty() const
Determine if the PriorityWorklist is empty or not.
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:905