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 
9 #include "llvm/Transforms/Scalar/LoopPassManager.h"
10 #include "llvm/Analysis/AssumptionCache.h"
11 #include "llvm/Analysis/BasicAliasAnalysis.h"
12 #include "llvm/Analysis/BlockFrequencyInfo.h"
13 #include "llvm/Analysis/GlobalsModRef.h"
14 #include "llvm/Analysis/MemorySSA.h"
15 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
16 #include "llvm/Analysis/TargetLibraryInfo.h"
17 #include "llvm/Support/TimeProfiler.h"
18 
19 using namespace llvm;
20 
21 namespace llvm {
22 
23 /// Explicitly specialize the pass manager's run method to handle loop nest
24 /// structure updates.
25 PreservedAnalyses
26 PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &,
27             LPMUpdater &>::run(Loop &L, LoopAnalysisManager &AM,
28                                LoopStandardAnalysisResults &AR, LPMUpdater &U) {
29 
30   if (DebugLogging)
31     dbgs() << "Starting Loop pass manager run.\n";
32 
33   // Runs loop-nest passes only when the current loop is a top-level one.
34   PreservedAnalyses PA = (L.isOutermost() && !LoopNestPasses.empty())
35                              ? runWithLoopNestPasses(L, AM, AR, U)
36                              : runWithoutLoopNestPasses(L, AM, AR, U);
37 
38   // Invalidation for the current loop should be handled above, and other loop
39   // analysis results shouldn't be impacted by runs over this loop. Therefore,
40   // the remaining analysis results in the AnalysisManager are preserved. We
41   // mark this with a set so that we don't need to inspect each one
42   // individually.
43   // FIXME: This isn't correct! This loop and all nested loops' analyses should
44   // be preserved, but unrolling should invalidate the parent loop's analyses.
45   PA.preserveSet<AllAnalysesOn<Loop>>();
46 
47   if (DebugLogging)
48     dbgs() << "Finished Loop pass manager run.\n";
49 
50   return PA;
51 }
52 
53 // Run both loop passes and loop-nest passes on top-level loop \p L.
54 PreservedAnalyses
55 LoopPassManager::runWithLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
56                                        LoopStandardAnalysisResults &AR,
57                                        LPMUpdater &U) {
58   assert(L.isOutermost() &&
59          "Loop-nest passes should only run on top-level loops.");
60   PreservedAnalyses PA = PreservedAnalyses::all();
61 
62   // Request PassInstrumentation from analysis manager, will use it to run
63   // instrumenting callbacks for the passes later.
64   PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR);
65 
66   unsigned LoopPassIndex = 0, LoopNestPassIndex = 0;
67 
68   // `LoopNestPtr` points to the `LoopNest` object for the current top-level
69   // loop and `IsLoopNestPtrValid` indicates whether the pointer is still valid.
70   // The `LoopNest` object will have to be re-constructed if the pointer is
71   // invalid when encountering a loop-nest pass.
72   std::unique_ptr<LoopNest> LoopNestPtr;
73   bool IsLoopNestPtrValid = false;
74 
75   for (size_t I = 0, E = IsLoopNestPass.size(); I != E; ++I) {
76     Optional<PreservedAnalyses> PassPA;
77     if (!IsLoopNestPass[I]) {
78       // The `I`-th pass is a loop pass.
79       auto &Pass = LoopPasses[LoopPassIndex++];
80       PassPA = runSinglePass(L, Pass, AM, AR, U, PI);
81     } else {
82       // The `I`-th pass is a loop-nest pass.
83       auto &Pass = LoopNestPasses[LoopNestPassIndex++];
84 
85       // If the loop-nest object calculated before is no longer valid,
86       // re-calculate it here before running the loop-nest pass.
87       if (!IsLoopNestPtrValid) {
88         LoopNestPtr = LoopNest::getLoopNest(L, AR.SE);
89         IsLoopNestPtrValid = true;
90       }
91       PassPA = runSinglePass(*LoopNestPtr, Pass, AM, AR, U, PI);
92     }
93 
94     // `PassPA` is `None` means that the before-pass callbacks in
95     // `PassInstrumentation` return false. The pass does not run in this case,
96     // so we can skip the following procedure.
97     if (!PassPA)
98       continue;
99 
100     // If the loop was deleted, abort the run and return to the outer walk.
101     if (U.skipCurrentLoop()) {
102       PA.intersect(std::move(*PassPA));
103       break;
104     }
105 
106     // Update the analysis manager as each pass runs and potentially
107     // invalidates analyses.
108     AM.invalidate(L, *PassPA);
109 
110     // Finally, we intersect the final preserved analyses to compute the
111     // aggregate preserved set for this pass manager.
112     PA.intersect(std::move(*PassPA));
113 
114     // Check if the current pass preserved the loop-nest object or not.
115     IsLoopNestPtrValid &= PassPA->getChecker<LoopNestAnalysis>().preserved();
116 
117     // FIXME: Historically, the pass managers all called the LLVM context's
118     // yield function here. We don't have a generic way to acquire the
119     // context and it isn't yet clear what the right pattern is for yielding
120     // in the new pass manager so it is currently omitted.
121     // ...getContext().yield();
122   }
123   return PA;
124 }
125 
126 // Run all loop passes on loop \p L. Loop-nest passes don't run either because
127 // \p L is not a top-level one or simply because there are no loop-nest passes
128 // in the pass manager at all.
129 PreservedAnalyses
130 LoopPassManager::runWithoutLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
131                                           LoopStandardAnalysisResults &AR,
132                                           LPMUpdater &U) {
133   PreservedAnalyses PA = PreservedAnalyses::all();
134 
135   // Request PassInstrumentation from analysis manager, will use it to run
136   // instrumenting callbacks for the passes later.
137   PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR);
138   for (auto &Pass : LoopPasses) {
139     Optional<PreservedAnalyses> PassPA = runSinglePass(L, Pass, AM, AR, U, PI);
140 
141     // `PassPA` is `None` means that the before-pass callbacks in
142     // `PassInstrumentation` return false. The pass does not run in this case,
143     // so we can skip the following procedure.
144     if (!PassPA)
145       continue;
146 
147     // If the loop was deleted, abort the run and return to the outer walk.
148     if (U.skipCurrentLoop()) {
149       PA.intersect(std::move(*PassPA));
150       break;
151     }
152 
153     // Update the analysis manager as each pass runs and potentially
154     // invalidates analyses.
155     AM.invalidate(L, *PassPA);
156 
157     // Finally, we intersect the final preserved analyses to compute the
158     // aggregate preserved set for this pass manager.
159     PA.intersect(std::move(*PassPA));
160 
161     // FIXME: Historically, the pass managers all called the LLVM context's
162     // yield function here. We don't have a generic way to acquire the
163     // context and it isn't yet clear what the right pattern is for yielding
164     // in the new pass manager so it is currently omitted.
165     // ...getContext().yield();
166   }
167   return PA;
168 }
169 } // namespace llvm
170 
171 PreservedAnalyses FunctionToLoopPassAdaptor::run(Function &F,
172                                                  FunctionAnalysisManager &AM) {
173   // Before we even compute any loop analyses, first run a miniature function
174   // pass pipeline to put loops into their canonical form. Note that we can
175   // directly build up function analyses after this as the function pass
176   // manager handles all the invalidation at that layer.
177   PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(F);
178 
179   PreservedAnalyses PA = PreservedAnalyses::all();
180   // Check the PassInstrumentation's BeforePass callbacks before running the
181   // canonicalization pipeline.
182   if (PI.runBeforePass<Function>(LoopCanonicalizationFPM, F)) {
183     PA = LoopCanonicalizationFPM.run(F, AM);
184     PI.runAfterPass<Function>(LoopCanonicalizationFPM, F, PA);
185   }
186 
187   // Get the loop structure for this function
188   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
189 
190   // If there are no loops, there is nothing to do here.
191   if (LI.empty())
192     return PA;
193 
194   // Get the analysis results needed by loop passes.
195   MemorySSA *MSSA =
196       UseMemorySSA ? (&AM.getResult<MemorySSAAnalysis>(F).getMSSA()) : nullptr;
197   BlockFrequencyInfo *BFI = UseBlockFrequencyInfo && F.hasProfileData()
198                                 ? (&AM.getResult<BlockFrequencyAnalysis>(F))
199                                 : nullptr;
200   LoopStandardAnalysisResults LAR = {AM.getResult<AAManager>(F),
201                                      AM.getResult<AssumptionAnalysis>(F),
202                                      AM.getResult<DominatorTreeAnalysis>(F),
203                                      AM.getResult<LoopAnalysis>(F),
204                                      AM.getResult<ScalarEvolutionAnalysis>(F),
205                                      AM.getResult<TargetLibraryAnalysis>(F),
206                                      AM.getResult<TargetIRAnalysis>(F),
207                                      BFI,
208                                      MSSA};
209 
210   // Setup the loop analysis manager from its proxy. It is important that
211   // this is only done when there are loops to process and we have built the
212   // LoopStandardAnalysisResults object. The loop analyses cached in this
213   // manager have access to those analysis results and so it must invalidate
214   // itself when they go away.
215   auto &LAMFP = AM.getResult<LoopAnalysisManagerFunctionProxy>(F);
216   if (UseMemorySSA)
217     LAMFP.markMSSAUsed();
218   LoopAnalysisManager &LAM = LAMFP.getManager();
219 
220   // A postorder worklist of loops to process.
221   SmallPriorityWorklist<Loop *, 4> Worklist;
222 
223   // Register the worklist and loop analysis manager so that loop passes can
224   // update them when they mutate the loop nest structure.
225   LPMUpdater Updater(Worklist, LAM, LoopNestMode);
226 
227   // Add the loop nests in the reverse order of LoopInfo. See method
228   // declaration.
229   if (!LoopNestMode) {
230     appendLoopsToWorklist(LI, Worklist);
231   } else {
232     for (Loop *L : LI)
233       Worklist.insert(L);
234   }
235 
236 #ifndef NDEBUG
237   PI.pushBeforeNonSkippedPassCallback([&LAR, &LI](StringRef PassID, Any IR) {
238     if (isSpecialPass(PassID, {"PassManager"}))
239       return;
240     assert(any_isa<const Loop *>(IR) || any_isa<const LoopNest *>(IR));
241     const Loop *L = any_isa<const Loop *>(IR)
242                         ? any_cast<const Loop *>(IR)
243                         : &any_cast<const LoopNest *>(IR)->getOutermostLoop();
244     assert(L && "Loop should be valid for printing");
245 
246     // Verify the loop structure and LCSSA form before visiting the loop.
247     L->verifyLoop();
248     assert(L->isRecursivelyLCSSAForm(LAR.DT, LI) &&
249            "Loops must remain in LCSSA form!");
250   });
251 #endif
252 
253   do {
254     Loop *L = Worklist.pop_back_val();
255     assert(!(LoopNestMode && L->getParentLoop()) &&
256            "L should be a top-level loop in loop-nest mode.");
257 
258     // Reset the update structure for this loop.
259     Updater.CurrentL = L;
260     Updater.SkipCurrentLoop = false;
261 
262 #ifndef NDEBUG
263     // Save a parent loop pointer for asserts.
264     Updater.ParentL = L->getParentLoop();
265 #endif
266     // Check the PassInstrumentation's BeforePass callbacks before running the
267     // pass, skip its execution completely if asked to (callback returns
268     // false).
269     if (!PI.runBeforePass<Loop>(*Pass, *L))
270       continue;
271 
272     PreservedAnalyses PassPA;
273     {
274       TimeTraceScope TimeScope(Pass->name());
275       PassPA = Pass->run(*L, LAM, LAR, Updater);
276     }
277 
278     // Do not pass deleted Loop into the instrumentation.
279     if (Updater.skipCurrentLoop())
280       PI.runAfterPassInvalidated<Loop>(*Pass, PassPA);
281     else
282       PI.runAfterPass<Loop>(*Pass, *L, PassPA);
283 
284     // FIXME: We should verify the set of analyses relevant to Loop passes
285     // are preserved.
286 
287     // If the loop hasn't been deleted, we need to handle invalidation here.
288     if (!Updater.skipCurrentLoop())
289       // We know that the loop pass couldn't have invalidated any other
290       // loop's analyses (that's the contract of a loop pass), so directly
291       // handle the loop analysis manager's invalidation here.
292       LAM.invalidate(*L, PassPA);
293 
294     // Then intersect the preserved set so that invalidation of module
295     // analyses will eventually occur when the module pass completes.
296     PA.intersect(std::move(PassPA));
297   } while (!Worklist.empty());
298 
299 #ifndef NDEBUG
300   PI.popBeforeNonSkippedPassCallback();
301 #endif
302 
303   // By definition we preserve the proxy. We also preserve all analyses on
304   // Loops. This precludes *any* invalidation of loop analyses by the proxy,
305   // but that's OK because we've taken care to invalidate analyses in the
306   // loop analysis manager incrementally above.
307   PA.preserveSet<AllAnalysesOn<Loop>>();
308   PA.preserve<LoopAnalysisManagerFunctionProxy>();
309   // We also preserve the set of standard analyses.
310   PA.preserve<DominatorTreeAnalysis>();
311   PA.preserve<LoopAnalysis>();
312   PA.preserve<ScalarEvolutionAnalysis>();
313   if (UseBlockFrequencyInfo && F.hasProfileData())
314     PA.preserve<BlockFrequencyAnalysis>();
315   if (UseMemorySSA)
316     PA.preserve<MemorySSAAnalysis>();
317   // FIXME: What we really want to do here is preserve an AA category, but
318   // that concept doesn't exist yet.
319   PA.preserve<AAManager>();
320   PA.preserve<BasicAA>();
321   PA.preserve<GlobalsAA>();
322   PA.preserve<SCEVAA>();
323   return PA;
324 }
325 
326 PrintLoopPass::PrintLoopPass() : OS(dbgs()) {}
327 PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner)
328     : OS(OS), Banner(Banner) {}
329 
330 PreservedAnalyses PrintLoopPass::run(Loop &L, LoopAnalysisManager &,
331                                      LoopStandardAnalysisResults &,
332                                      LPMUpdater &) {
333   printLoop(L, OS, Banner);
334   return PreservedAnalyses::all();
335 }
336