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