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 
39 #include "llvm/ADT/PriorityWorklist.h"
40 #include "llvm/Analysis/LoopAnalysisManager.h"
41 #include "llvm/Analysis/LoopInfo.h"
42 #include "llvm/Analysis/LoopNestAnalysis.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/PassInstrumentation.h"
45 #include "llvm/IR/PassManager.h"
46 #include "llvm/Transforms/Utils/LCSSA.h"
47 #include "llvm/Transforms/Utils/LoopSimplify.h"
48 #include "llvm/Transforms/Utils/LoopUtils.h"
49 #include <memory>
50 
51 namespace llvm {
52 
53 // Forward declarations of an update tracking API used in the pass manager.
54 class LPMUpdater;
55 
56 namespace {
57 
58 template <typename PassT>
59 using HasRunOnLoopT = decltype(std::declval<PassT>().run(
60     std::declval<Loop &>(), std::declval<LoopAnalysisManager &>(),
61     std::declval<LoopStandardAnalysisResults &>(),
62     std::declval<LPMUpdater &>()));
63 
64 } // namespace
65 
66 // Explicit specialization and instantiation declarations for the pass manager.
67 // See the comments on the definition of the specialization for details on how
68 // it differs from the primary template.
69 template <>
70 class PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &,
71                   LPMUpdater &>
72     : public PassInfoMixin<
73           PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &,
74                       LPMUpdater &>> {
75 public:
PassManager()76   explicit PassManager() {}
77 
78   // FIXME: These are equivalent to the default move constructor/move
79   // assignment. However, using = default triggers linker errors due to the
80   // explicit instantiations below. Find a way to use the default and remove the
81   // duplicated code here.
PassManager(PassManager && Arg)82   PassManager(PassManager &&Arg)
83       : IsLoopNestPass(std::move(Arg.IsLoopNestPass)),
84         LoopPasses(std::move(Arg.LoopPasses)),
85         LoopNestPasses(std::move(Arg.LoopNestPasses)) {}
86 
87   PassManager &operator=(PassManager &&RHS) {
88     IsLoopNestPass = std::move(RHS.IsLoopNestPass);
89     LoopPasses = std::move(RHS.LoopPasses);
90     LoopNestPasses = std::move(RHS.LoopNestPasses);
91     return *this;
92   }
93 
94   PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM,
95                         LoopStandardAnalysisResults &AR, LPMUpdater &U);
96 
97   /// Add either a loop pass or a loop-nest pass to the pass manager. Append \p
98   /// Pass to the list of loop passes if it has a dedicated \fn run() method for
99   /// loops and to the list of loop-nest passes if the \fn run() method is for
100   /// loop-nests instead. Also append whether \p Pass is loop-nest pass or not
101   /// to the end of \var IsLoopNestPass so we can easily identify the types of
102   /// passes in the pass manager later.
103   template <typename PassT>
104   std::enable_if_t<is_detected<HasRunOnLoopT, PassT>::value>
addPass(PassT && Pass)105   addPass(PassT &&Pass) {
106     using LoopPassModelT =
107         detail::PassModel<Loop, PassT, PreservedAnalyses, LoopAnalysisManager,
108                           LoopStandardAnalysisResults &, LPMUpdater &>;
109     IsLoopNestPass.push_back(false);
110     LoopPasses.emplace_back(new LoopPassModelT(std::forward<PassT>(Pass)));
111   }
112 
113   template <typename PassT>
114   std::enable_if_t<!is_detected<HasRunOnLoopT, PassT>::value>
addPass(PassT && Pass)115   addPass(PassT &&Pass) {
116     using LoopNestPassModelT =
117         detail::PassModel<LoopNest, PassT, PreservedAnalyses,
118                           LoopAnalysisManager, LoopStandardAnalysisResults &,
119                           LPMUpdater &>;
120     IsLoopNestPass.push_back(true);
121     LoopNestPasses.emplace_back(
122         new LoopNestPassModelT(std::forward<PassT>(Pass)));
123   }
124 
125   // Specializations of `addPass` for `RepeatedPass`. These are necessary since
126   // `RepeatedPass` has a templated `run` method that will result in incorrect
127   // detection of `HasRunOnLoopT`.
128   template <typename PassT>
129   std::enable_if_t<is_detected<HasRunOnLoopT, PassT>::value>
addPass(RepeatedPass<PassT> && Pass)130   addPass(RepeatedPass<PassT> &&Pass) {
131     using RepeatedLoopPassModelT =
132         detail::PassModel<Loop, RepeatedPass<PassT>, PreservedAnalyses,
133                           LoopAnalysisManager, LoopStandardAnalysisResults &,
134                           LPMUpdater &>;
135     IsLoopNestPass.push_back(false);
136     LoopPasses.emplace_back(new RepeatedLoopPassModelT(std::move(Pass)));
137   }
138 
139   template <typename PassT>
140   std::enable_if_t<!is_detected<HasRunOnLoopT, PassT>::value>
addPass(RepeatedPass<PassT> && Pass)141   addPass(RepeatedPass<PassT> &&Pass) {
142     using RepeatedLoopNestPassModelT =
143         detail::PassModel<LoopNest, RepeatedPass<PassT>, PreservedAnalyses,
144                           LoopAnalysisManager, LoopStandardAnalysisResults &,
145                           LPMUpdater &>;
146     IsLoopNestPass.push_back(true);
147     LoopNestPasses.emplace_back(
148         new RepeatedLoopNestPassModelT(std::move(Pass)));
149   }
150 
isEmpty()151   bool isEmpty() const { return LoopPasses.empty() && LoopNestPasses.empty(); }
152 
isRequired()153   static bool isRequired() { return true; }
154 
getNumLoopPasses()155   size_t getNumLoopPasses() const { return LoopPasses.size(); }
getNumLoopNestPasses()156   size_t getNumLoopNestPasses() const { return LoopNestPasses.size(); }
157 
158 protected:
159   using LoopPassConceptT =
160       detail::PassConcept<Loop, LoopAnalysisManager,
161                           LoopStandardAnalysisResults &, LPMUpdater &>;
162   using LoopNestPassConceptT =
163       detail::PassConcept<LoopNest, LoopAnalysisManager,
164                           LoopStandardAnalysisResults &, LPMUpdater &>;
165 
166   // BitVector that identifies whether the passes are loop passes or loop-nest
167   // passes (true for loop-nest passes).
168   BitVector IsLoopNestPass;
169   std::vector<std::unique_ptr<LoopPassConceptT>> LoopPasses;
170   std::vector<std::unique_ptr<LoopNestPassConceptT>> LoopNestPasses;
171 
172   /// Run either a loop pass or a loop-nest pass. Returns `None` if
173   /// PassInstrumentation's BeforePass returns false. Otherwise, returns the
174   /// preserved analyses of the pass.
175   template <typename IRUnitT, typename PassT>
176   Optional<PreservedAnalyses>
177   runSinglePass(IRUnitT &IR, PassT &Pass, LoopAnalysisManager &AM,
178                 LoopStandardAnalysisResults &AR, LPMUpdater &U,
179                 PassInstrumentation &PI);
180 
181   PreservedAnalyses runWithLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
182                                           LoopStandardAnalysisResults &AR,
183                                           LPMUpdater &U);
184   PreservedAnalyses runWithoutLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
185                                              LoopStandardAnalysisResults &AR,
186                                              LPMUpdater &U);
187 
188 private:
getLoopFromIR(Loop & L)189   static const Loop &getLoopFromIR(Loop &L) { return L; }
getLoopFromIR(LoopNest & LN)190   static const Loop &getLoopFromIR(LoopNest &LN) {
191     return LN.getOutermostLoop();
192   }
193 };
194 
195 /// The Loop pass manager.
196 ///
197 /// See the documentation for the PassManager template for details. It runs
198 /// a sequence of Loop passes over each Loop that the manager is run over. This
199 /// typedef serves as a convenient way to refer to this construct.
200 typedef PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &,
201                     LPMUpdater &>
202     LoopPassManager;
203 
204 /// A partial specialization of the require analysis template pass to forward
205 /// the extra parameters from a transformation's run method to the
206 /// AnalysisManager's getResult.
207 template <typename AnalysisT>
208 struct RequireAnalysisPass<AnalysisT, Loop, LoopAnalysisManager,
209                            LoopStandardAnalysisResults &, LPMUpdater &>
210     : PassInfoMixin<
211           RequireAnalysisPass<AnalysisT, Loop, LoopAnalysisManager,
212                               LoopStandardAnalysisResults &, LPMUpdater &>> {
213   PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM,
214                         LoopStandardAnalysisResults &AR, LPMUpdater &) {
215     (void)AM.template getResult<AnalysisT>(L, AR);
216     return PreservedAnalyses::all();
217   }
218 };
219 
220 /// An alias template to easily name a require analysis loop pass.
221 template <typename AnalysisT>
222 using RequireAnalysisLoopPass =
223     RequireAnalysisPass<AnalysisT, Loop, LoopAnalysisManager,
224                         LoopStandardAnalysisResults &, LPMUpdater &>;
225 
226 class FunctionToLoopPassAdaptor;
227 
228 /// This class provides an interface for updating the loop pass manager based
229 /// on mutations to the loop nest.
230 ///
231 /// A reference to an instance of this class is passed as an argument to each
232 /// Loop pass, and Loop passes should use it to update LPM infrastructure if
233 /// they modify the loop nest structure.
234 ///
235 /// \c LPMUpdater comes with two modes: the loop mode and the loop-nest mode. In
236 /// loop mode, all the loops in the function will be pushed into the worklist
237 /// and when new loops are added to the pipeline, their subloops are also
238 /// inserted recursively. On the other hand, in loop-nest mode, only top-level
239 /// loops are contained in the worklist and the addition of new (top-level)
240 /// loops will not trigger the addition of their subloops.
241 class LPMUpdater {
242 public:
243   /// This can be queried by loop passes which run other loop passes (like pass
244   /// managers) to know whether the loop needs to be skipped due to updates to
245   /// the loop nest.
246   ///
247   /// If this returns true, the loop object may have been deleted, so passes
248   /// should take care not to touch the object.
249   bool skipCurrentLoop() const { return SkipCurrentLoop; }
250 
251   /// Loop passes should use this method to indicate they have deleted a loop
252   /// from the nest.
253   ///
254   /// Note that this loop must either be the current loop or a subloop of the
255   /// current loop. This routine must be called prior to removing the loop from
256   /// the loop nest.
257   ///
258   /// If this is called for the current loop, in addition to clearing any
259   /// state, this routine will mark that the current loop should be skipped by
260   /// the rest of the pass management infrastructure.
261   void markLoopAsDeleted(Loop &L, llvm::StringRef Name) {
262     assert((!LoopNestMode || CurrentL == &L) &&
263            "L should be a top-level loop in loop-nest mode.");
264     LAM.clear(L, Name);
265     assert((&L == CurrentL || CurrentL->contains(&L)) &&
266            "Cannot delete a loop outside of the "
267            "subloop tree currently being processed.");
268     if (&L == CurrentL)
269       SkipCurrentLoop = true;
270   }
271 
272   void setParentLoop(Loop *L) {
273 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
274     ParentL = L;
275 #endif
276   }
277 
278   /// Loop passes should use this method to indicate they have added new child
279   /// loops of the current loop.
280   ///
281   /// \p NewChildLoops must contain only the immediate children. Any nested
282   /// loops within them will be visited in postorder as usual for the loop pass
283   /// manager.
284   void addChildLoops(ArrayRef<Loop *> NewChildLoops) {
285     assert(!LoopNestMode &&
286            "Child loops should not be pushed in loop-nest mode.");
287     // Insert ourselves back into the worklist first, as this loop should be
288     // revisited after all the children have been processed.
289     Worklist.insert(CurrentL);
290 
291 #ifndef NDEBUG
292     for (Loop *NewL : NewChildLoops)
293       assert(NewL->getParentLoop() == CurrentL && "All of the new loops must "
294                                                   "be immediate children of "
295                                                   "the current loop!");
296 #endif
297 
298     appendLoopsToWorklist(NewChildLoops, Worklist);
299 
300     // Also skip further processing of the current loop--it will be revisited
301     // after all of its newly added children are accounted for.
302     SkipCurrentLoop = true;
303   }
304 
305   /// Loop passes should use this method to indicate they have added new
306   /// sibling loops to the current loop.
307   ///
308   /// \p NewSibLoops must only contain the immediate sibling loops. Any nested
309   /// loops within them will be visited in postorder as usual for the loop pass
310   /// manager.
311   void addSiblingLoops(ArrayRef<Loop *> NewSibLoops) {
312 #if defined(LLVM_ENABLE_ABI_BREAKING_CHECKS) && !defined(NDEBUG)
313     for (Loop *NewL : NewSibLoops)
314       assert(NewL->getParentLoop() == ParentL &&
315              "All of the new loops must be siblings of the current loop!");
316 #endif
317 
318     if (LoopNestMode)
319       Worklist.insert(NewSibLoops);
320     else
321       appendLoopsToWorklist(NewSibLoops, Worklist);
322 
323     // No need to skip the current loop or revisit it, as sibling loops
324     // shouldn't impact anything.
325   }
326 
327   /// Restart the current loop.
328   ///
329   /// Loop passes should call this method to indicate the current loop has been
330   /// sufficiently changed that it should be re-visited from the begining of
331   /// the loop pass pipeline rather than continuing.
332   void revisitCurrentLoop() {
333     // Tell the currently in-flight pipeline to stop running.
334     SkipCurrentLoop = true;
335 
336     // And insert ourselves back into the worklist.
337     Worklist.insert(CurrentL);
338   }
339 
340 private:
341   friend class llvm::FunctionToLoopPassAdaptor;
342 
343   /// The \c FunctionToLoopPassAdaptor's worklist of loops to process.
344   SmallPriorityWorklist<Loop *, 4> &Worklist;
345 
346   /// The analysis manager for use in the current loop nest.
347   LoopAnalysisManager &LAM;
348 
349   Loop *CurrentL;
350   bool SkipCurrentLoop;
351   const bool LoopNestMode;
352 
353 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
354   // In debug builds we also track the parent loop to implement asserts even in
355   // the face of loop deletion.
356   Loop *ParentL;
357 #endif
358 
359   LPMUpdater(SmallPriorityWorklist<Loop *, 4> &Worklist,
360              LoopAnalysisManager &LAM, bool LoopNestMode = false)
361       : Worklist(Worklist), LAM(LAM), LoopNestMode(LoopNestMode) {}
362 };
363 
364 template <typename IRUnitT, typename PassT>
365 Optional<PreservedAnalyses> LoopPassManager::runSinglePass(
366     IRUnitT &IR, PassT &Pass, LoopAnalysisManager &AM,
367     LoopStandardAnalysisResults &AR, LPMUpdater &U, PassInstrumentation &PI) {
368   // Get the loop in case of Loop pass and outermost loop in case of LoopNest
369   // pass which is to be passed to BeforePass and AfterPass call backs.
370   const Loop &L = getLoopFromIR(IR);
371   // Check the PassInstrumentation's BeforePass callbacks before running the
372   // pass, skip its execution completely if asked to (callback returns false).
373   if (!PI.runBeforePass<Loop>(*Pass, L))
374     return None;
375 
376   PreservedAnalyses PA;
377   {
378     TimeTraceScope TimeScope(Pass->name(), IR.getName());
379     PA = Pass->run(IR, AM, AR, U);
380   }
381 
382   // do not pass deleted Loop into the instrumentation
383   if (U.skipCurrentLoop())
384     PI.runAfterPassInvalidated<IRUnitT>(*Pass, PA);
385   else
386     PI.runAfterPass<Loop>(*Pass, L, PA);
387   return PA;
388 }
389 
390 /// Adaptor that maps from a function to its loops.
391 ///
392 /// Designed to allow composition of a LoopPass(Manager) and a
393 /// FunctionPassManager. Note that if this pass is constructed with a \c
394 /// FunctionAnalysisManager it will run the \c LoopAnalysisManagerFunctionProxy
395 /// analysis prior to running the loop passes over the function to enable a \c
396 /// LoopAnalysisManager to be used within this run safely.
397 ///
398 /// The adaptor comes with two modes: the loop mode and the loop-nest mode, and
399 /// the worklist updater lived inside will be in the same mode as the adaptor
400 /// (refer to the documentation of \c LPMUpdater for more detailed explanation).
401 /// Specifically, in loop mode, all loops in the funciton will be pushed into
402 /// the worklist and processed by \p Pass, while only top-level loops are
403 /// processed in loop-nest mode. Please refer to the various specializations of
404 /// \fn createLoopFunctionToLoopPassAdaptor to see when loop mode and loop-nest
405 /// mode are used.
406 class FunctionToLoopPassAdaptor
407     : public PassInfoMixin<FunctionToLoopPassAdaptor> {
408 public:
409   using PassConceptT =
410       detail::PassConcept<Loop, LoopAnalysisManager,
411                           LoopStandardAnalysisResults &, LPMUpdater &>;
412 
413   explicit FunctionToLoopPassAdaptor(std::unique_ptr<PassConceptT> Pass,
414                                      bool UseMemorySSA = false,
415                                      bool UseBlockFrequencyInfo = false,
416                                      bool LoopNestMode = false)
417       : Pass(std::move(Pass)), LoopCanonicalizationFPM(),
418         UseMemorySSA(UseMemorySSA),
419         UseBlockFrequencyInfo(UseBlockFrequencyInfo),
420         LoopNestMode(LoopNestMode) {
421     LoopCanonicalizationFPM.addPass(LoopSimplifyPass());
422     LoopCanonicalizationFPM.addPass(LCSSAPass());
423   }
424 
425   /// Runs the loop passes across every loop in the function.
426   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
427 
428   static bool isRequired() { return true; }
429 
430   bool isLoopNestMode() const { return LoopNestMode; }
431 
432 private:
433   std::unique_ptr<PassConceptT> Pass;
434 
435   FunctionPassManager LoopCanonicalizationFPM;
436 
437   bool UseMemorySSA = false;
438   bool UseBlockFrequencyInfo = false;
439   const bool LoopNestMode;
440 };
441 
442 /// A function to deduce a loop pass type and wrap it in the templated
443 /// adaptor.
444 ///
445 /// If \p Pass is a loop pass, the returned adaptor will be in loop mode.
446 template <typename LoopPassT>
447 inline std::enable_if_t<is_detected<HasRunOnLoopT, LoopPassT>::value,
448                         FunctionToLoopPassAdaptor>
449 createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA = false,
450                                 bool UseBlockFrequencyInfo = false) {
451   using PassModelT =
452       detail::PassModel<Loop, LoopPassT, PreservedAnalyses, LoopAnalysisManager,
453                         LoopStandardAnalysisResults &, LPMUpdater &>;
454   return FunctionToLoopPassAdaptor(
455       std::make_unique<PassModelT>(std::forward<LoopPassT>(Pass)), UseMemorySSA,
456       UseBlockFrequencyInfo, false);
457 }
458 
459 /// If \p Pass is a loop-nest pass, \p Pass will first be wrapped into a
460 /// \c LoopPassManager and the returned adaptor will be in loop-nest mode.
461 template <typename LoopNestPassT>
462 inline std::enable_if_t<!is_detected<HasRunOnLoopT, LoopNestPassT>::value,
463                         FunctionToLoopPassAdaptor>
464 createFunctionToLoopPassAdaptor(LoopNestPassT &&Pass, bool UseMemorySSA = false,
465                                 bool UseBlockFrequencyInfo = false) {
466   LoopPassManager LPM;
467   LPM.addPass(std::forward<LoopNestPassT>(Pass));
468   using PassModelT =
469       detail::PassModel<Loop, LoopPassManager, PreservedAnalyses,
470                         LoopAnalysisManager, LoopStandardAnalysisResults &,
471                         LPMUpdater &>;
472   return FunctionToLoopPassAdaptor(std::make_unique<PassModelT>(std::move(LPM)),
473                                    UseMemorySSA, UseBlockFrequencyInfo, true);
474 }
475 
476 /// If \p Pass is an instance of \c LoopPassManager, the returned adaptor will
477 /// be in loop-nest mode if the pass manager contains only loop-nest passes.
478 template <>
479 inline FunctionToLoopPassAdaptor
480 createFunctionToLoopPassAdaptor<LoopPassManager>(LoopPassManager &&LPM,
481                                                  bool UseMemorySSA,
482                                                  bool UseBlockFrequencyInfo) {
483   // Check if LPM contains any loop pass and if it does not, returns an adaptor
484   // in loop-nest mode.
485   using PassModelT =
486       detail::PassModel<Loop, LoopPassManager, PreservedAnalyses,
487                         LoopAnalysisManager, LoopStandardAnalysisResults &,
488                         LPMUpdater &>;
489   bool LoopNestMode = (LPM.getNumLoopPasses() == 0);
490   return FunctionToLoopPassAdaptor(std::make_unique<PassModelT>(std::move(LPM)),
491                                    UseMemorySSA, UseBlockFrequencyInfo,
492                                    LoopNestMode);
493 }
494 
495 /// Pass for printing a loop's contents as textual IR.
496 class PrintLoopPass : public PassInfoMixin<PrintLoopPass> {
497   raw_ostream &OS;
498   std::string Banner;
499 
500 public:
501   PrintLoopPass();
502   PrintLoopPass(raw_ostream &OS, const std::string &Banner = "");
503 
504   PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
505                         LoopStandardAnalysisResults &, LPMUpdater &);
506 };
507 }
508 
509 #endif // LLVM_TRANSFORMS_SCALAR_LOOPPASSMANAGER_H
510