1 //===- Parsing, selection, and construction of pass pipelines -------------===// 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 file provides the implementation of the PassBuilder based on our 11 /// static pass registry as well as related functionality. It also provides 12 /// helpers to aid in analyzing, debugging, and testing passes and pass 13 /// pipelines. 14 /// 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Passes/PassBuilder.h" 18 #include "llvm/ADT/StringSwitch.h" 19 #include "llvm/Analysis/AliasAnalysisEvaluator.h" 20 #include "llvm/Analysis/AliasSetTracker.h" 21 #include "llvm/Analysis/AssumptionCache.h" 22 #include "llvm/Analysis/BasicAliasAnalysis.h" 23 #include "llvm/Analysis/BlockFrequencyInfo.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/CFGPrinter.h" 26 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 27 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 28 #include "llvm/Analysis/CGSCCPassManager.h" 29 #include "llvm/Analysis/CallGraph.h" 30 #include "llvm/Analysis/CostModel.h" 31 #include "llvm/Analysis/DDG.h" 32 #include "llvm/Analysis/DDGPrinter.h" 33 #include "llvm/Analysis/Delinearization.h" 34 #include "llvm/Analysis/DemandedBits.h" 35 #include "llvm/Analysis/DependenceAnalysis.h" 36 #include "llvm/Analysis/DivergenceAnalysis.h" 37 #include "llvm/Analysis/DominanceFrontier.h" 38 #include "llvm/Analysis/FunctionPropertiesAnalysis.h" 39 #include "llvm/Analysis/GlobalsModRef.h" 40 #include "llvm/Analysis/IRSimilarityIdentifier.h" 41 #include "llvm/Analysis/IVUsers.h" 42 #include "llvm/Analysis/InlineAdvisor.h" 43 #include "llvm/Analysis/InlineSizeEstimatorAnalysis.h" 44 #include "llvm/Analysis/InstCount.h" 45 #include "llvm/Analysis/LazyCallGraph.h" 46 #include "llvm/Analysis/LazyValueInfo.h" 47 #include "llvm/Analysis/Lint.h" 48 #include "llvm/Analysis/LoopAccessAnalysis.h" 49 #include "llvm/Analysis/LoopCacheAnalysis.h" 50 #include "llvm/Analysis/LoopInfo.h" 51 #include "llvm/Analysis/LoopNestAnalysis.h" 52 #include "llvm/Analysis/MemDerefPrinter.h" 53 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 54 #include "llvm/Analysis/MemorySSA.h" 55 #include "llvm/Analysis/ModuleDebugInfoPrinter.h" 56 #include "llvm/Analysis/ModuleSummaryAnalysis.h" 57 #include "llvm/Analysis/MustExecute.h" 58 #include "llvm/Analysis/ObjCARCAliasAnalysis.h" 59 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 60 #include "llvm/Analysis/PhiValues.h" 61 #include "llvm/Analysis/PostDominators.h" 62 #include "llvm/Analysis/ProfileSummaryInfo.h" 63 #include "llvm/Analysis/RegionInfo.h" 64 #include "llvm/Analysis/ScalarEvolution.h" 65 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 66 #include "llvm/Analysis/ScopedNoAliasAA.h" 67 #include "llvm/Analysis/StackLifetime.h" 68 #include "llvm/Analysis/StackSafetyAnalysis.h" 69 #include "llvm/Analysis/TargetLibraryInfo.h" 70 #include "llvm/Analysis/TargetTransformInfo.h" 71 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 72 #include "llvm/IR/Dominators.h" 73 #include "llvm/IR/IRPrintingPasses.h" 74 #include "llvm/IR/PassManager.h" 75 #include "llvm/IR/PrintPasses.h" 76 #include "llvm/IR/SafepointIRVerifier.h" 77 #include "llvm/IR/Verifier.h" 78 #include "llvm/Support/CommandLine.h" 79 #include "llvm/Support/Debug.h" 80 #include "llvm/Support/ErrorHandling.h" 81 #include "llvm/Support/FormatVariadic.h" 82 #include "llvm/Support/Regex.h" 83 #include "llvm/Target/TargetMachine.h" 84 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 85 #include "llvm/Transforms/Coroutines/CoroCleanup.h" 86 #include "llvm/Transforms/Coroutines/CoroEarly.h" 87 #include "llvm/Transforms/Coroutines/CoroElide.h" 88 #include "llvm/Transforms/Coroutines/CoroSplit.h" 89 #include "llvm/Transforms/IPO/AlwaysInliner.h" 90 #include "llvm/Transforms/IPO/Annotation2Metadata.h" 91 #include "llvm/Transforms/IPO/ArgumentPromotion.h" 92 #include "llvm/Transforms/IPO/Attributor.h" 93 #include "llvm/Transforms/IPO/BlockExtractor.h" 94 #include "llvm/Transforms/IPO/CalledValuePropagation.h" 95 #include "llvm/Transforms/IPO/ConstantMerge.h" 96 #include "llvm/Transforms/IPO/CrossDSOCFI.h" 97 #include "llvm/Transforms/IPO/DeadArgumentElimination.h" 98 #include "llvm/Transforms/IPO/ElimAvailExtern.h" 99 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" 100 #include "llvm/Transforms/IPO/FunctionAttrs.h" 101 #include "llvm/Transforms/IPO/FunctionImport.h" 102 #include "llvm/Transforms/IPO/GlobalDCE.h" 103 #include "llvm/Transforms/IPO/GlobalOpt.h" 104 #include "llvm/Transforms/IPO/GlobalSplit.h" 105 #include "llvm/Transforms/IPO/HotColdSplitting.h" 106 #include "llvm/Transforms/IPO/IROutliner.h" 107 #include "llvm/Transforms/IPO/InferFunctionAttrs.h" 108 #include "llvm/Transforms/IPO/Inliner.h" 109 #include "llvm/Transforms/IPO/Internalize.h" 110 #include "llvm/Transforms/IPO/LoopExtractor.h" 111 #include "llvm/Transforms/IPO/LowerTypeTests.h" 112 #include "llvm/Transforms/IPO/MergeFunctions.h" 113 #include "llvm/Transforms/IPO/OpenMPOpt.h" 114 #include "llvm/Transforms/IPO/PartialInlining.h" 115 #include "llvm/Transforms/IPO/SCCP.h" 116 #include "llvm/Transforms/IPO/SampleProfile.h" 117 #include "llvm/Transforms/IPO/SampleProfileProbe.h" 118 #include "llvm/Transforms/IPO/StripDeadPrototypes.h" 119 #include "llvm/Transforms/IPO/StripSymbols.h" 120 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h" 121 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 122 #include "llvm/Transforms/InstCombine/InstCombine.h" 123 #include "llvm/Transforms/Instrumentation.h" 124 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h" 125 #include "llvm/Transforms/Instrumentation/BoundsChecking.h" 126 #include "llvm/Transforms/Instrumentation/CGProfile.h" 127 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h" 128 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h" 129 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h" 130 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h" 131 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h" 132 #include "llvm/Transforms/Instrumentation/InstrProfiling.h" 133 #include "llvm/Transforms/Instrumentation/MemProfiler.h" 134 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" 135 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h" 136 #include "llvm/Transforms/Instrumentation/PoisonChecking.h" 137 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h" 138 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h" 139 #include "llvm/Transforms/ObjCARC.h" 140 #include "llvm/Transforms/Scalar/ADCE.h" 141 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h" 142 #include "llvm/Transforms/Scalar/AnnotationRemarks.h" 143 #include "llvm/Transforms/Scalar/BDCE.h" 144 #include "llvm/Transforms/Scalar/CallSiteSplitting.h" 145 #include "llvm/Transforms/Scalar/ConstantHoisting.h" 146 #include "llvm/Transforms/Scalar/ConstraintElimination.h" 147 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h" 148 #include "llvm/Transforms/Scalar/DCE.h" 149 #include "llvm/Transforms/Scalar/DFAJumpThreading.h" 150 #include "llvm/Transforms/Scalar/DeadStoreElimination.h" 151 #include "llvm/Transforms/Scalar/DivRemPairs.h" 152 #include "llvm/Transforms/Scalar/EarlyCSE.h" 153 #include "llvm/Transforms/Scalar/Float2Int.h" 154 #include "llvm/Transforms/Scalar/GVN.h" 155 #include "llvm/Transforms/Scalar/GuardWidening.h" 156 #include "llvm/Transforms/Scalar/IVUsersPrinter.h" 157 #include "llvm/Transforms/Scalar/IndVarSimplify.h" 158 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h" 159 #include "llvm/Transforms/Scalar/InferAddressSpaces.h" 160 #include "llvm/Transforms/Scalar/InstSimplifyPass.h" 161 #include "llvm/Transforms/Scalar/JumpThreading.h" 162 #include "llvm/Transforms/Scalar/LICM.h" 163 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h" 164 #include "llvm/Transforms/Scalar/LoopBoundSplit.h" 165 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h" 166 #include "llvm/Transforms/Scalar/LoopDeletion.h" 167 #include "llvm/Transforms/Scalar/LoopDistribute.h" 168 #include "llvm/Transforms/Scalar/LoopFlatten.h" 169 #include "llvm/Transforms/Scalar/LoopFuse.h" 170 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h" 171 #include "llvm/Transforms/Scalar/LoopInstSimplify.h" 172 #include "llvm/Transforms/Scalar/LoopInterchange.h" 173 #include "llvm/Transforms/Scalar/LoopLoadElimination.h" 174 #include "llvm/Transforms/Scalar/LoopPassManager.h" 175 #include "llvm/Transforms/Scalar/LoopPredication.h" 176 #include "llvm/Transforms/Scalar/LoopReroll.h" 177 #include "llvm/Transforms/Scalar/LoopRotation.h" 178 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h" 179 #include "llvm/Transforms/Scalar/LoopSink.h" 180 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h" 181 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h" 182 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 183 #include "llvm/Transforms/Scalar/LoopVersioningLICM.h" 184 #include "llvm/Transforms/Scalar/LowerAtomic.h" 185 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h" 186 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h" 187 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h" 188 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h" 189 #include "llvm/Transforms/Scalar/LowerWidenableCondition.h" 190 #include "llvm/Transforms/Scalar/MakeGuardsExplicit.h" 191 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h" 192 #include "llvm/Transforms/Scalar/MergeICmps.h" 193 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h" 194 #include "llvm/Transforms/Scalar/NaryReassociate.h" 195 #include "llvm/Transforms/Scalar/NewGVN.h" 196 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h" 197 #include "llvm/Transforms/Scalar/Reassociate.h" 198 #include "llvm/Transforms/Scalar/Reg2Mem.h" 199 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h" 200 #include "llvm/Transforms/Scalar/SCCP.h" 201 #include "llvm/Transforms/Scalar/SROA.h" 202 #include "llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h" 203 #include "llvm/Transforms/Scalar/Scalarizer.h" 204 #include "llvm/Transforms/Scalar/SeparateConstOffsetFromGEP.h" 205 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 206 #include "llvm/Transforms/Scalar/SimplifyCFG.h" 207 #include "llvm/Transforms/Scalar/Sink.h" 208 #include "llvm/Transforms/Scalar/SpeculativeExecution.h" 209 #include "llvm/Transforms/Scalar/StraightLineStrengthReduce.h" 210 #include "llvm/Transforms/Scalar/StructurizeCFG.h" 211 #include "llvm/Transforms/Scalar/TailRecursionElimination.h" 212 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h" 213 #include "llvm/Transforms/Utils/AddDiscriminators.h" 214 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 215 #include "llvm/Transforms/Utils/BreakCriticalEdges.h" 216 #include "llvm/Transforms/Utils/CanonicalizeAliases.h" 217 #include "llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h" 218 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h" 219 #include "llvm/Transforms/Utils/FixIrreducible.h" 220 #include "llvm/Transforms/Utils/HelloWorld.h" 221 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 222 #include "llvm/Transforms/Utils/InstructionNamer.h" 223 #include "llvm/Transforms/Utils/LCSSA.h" 224 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h" 225 #include "llvm/Transforms/Utils/LoopSimplify.h" 226 #include "llvm/Transforms/Utils/LoopVersioning.h" 227 #include "llvm/Transforms/Utils/LowerInvoke.h" 228 #include "llvm/Transforms/Utils/LowerSwitch.h" 229 #include "llvm/Transforms/Utils/Mem2Reg.h" 230 #include "llvm/Transforms/Utils/MetaRenamer.h" 231 #include "llvm/Transforms/Utils/NameAnonGlobals.h" 232 #include "llvm/Transforms/Utils/RelLookupTableConverter.h" 233 #include "llvm/Transforms/Utils/StripGCRelocates.h" 234 #include "llvm/Transforms/Utils/StripNonLineTableDebugInfo.h" 235 #include "llvm/Transforms/Utils/SymbolRewriter.h" 236 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h" 237 #include "llvm/Transforms/Utils/UnifyLoopExits.h" 238 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h" 239 #include "llvm/Transforms/Vectorize/LoopVectorize.h" 240 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 241 #include "llvm/Transforms/Vectorize/VectorCombine.h" 242 243 using namespace llvm; 244 245 static cl::opt<InliningAdvisorMode> UseInlineAdvisor( 246 "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden, 247 cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"), 248 cl::values(clEnumValN(InliningAdvisorMode::Default, "default", 249 "Heuristics-based inliner version."), 250 clEnumValN(InliningAdvisorMode::Development, "development", 251 "Use development mode (runtime-loadable model)."), 252 clEnumValN(InliningAdvisorMode::Release, "release", 253 "Use release mode (AOT-compiled model)."))); 254 255 static cl::opt<bool> EnableSyntheticCounts( 256 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore, 257 cl::desc("Run synthetic function entry count generation " 258 "pass")); 259 260 static const Regex DefaultAliasRegex( 261 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$"); 262 263 /// Flag to enable inline deferral during PGO. 264 static cl::opt<bool> 265 EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true), 266 cl::Hidden, 267 cl::desc("Enable inline deferral during PGO")); 268 269 static cl::opt<bool> EnableMemProfiler("enable-mem-prof", cl::init(false), 270 cl::Hidden, cl::ZeroOrMore, 271 cl::desc("Enable memory profiler")); 272 273 static cl::opt<bool> PerformMandatoryInliningsFirst( 274 "mandatory-inlining-first", cl::init(true), cl::Hidden, cl::ZeroOrMore, 275 cl::desc("Perform mandatory inlinings module-wide, before performing " 276 "inlining.")); 277 278 static cl::opt<bool> EnableO3NonTrivialUnswitching( 279 "enable-npm-O3-nontrivial-unswitch", cl::init(true), cl::Hidden, 280 cl::ZeroOrMore, cl::desc("Enable non-trivial loop unswitching for -O3")); 281 282 PipelineTuningOptions::PipelineTuningOptions() { 283 LoopInterleaving = true; 284 LoopVectorization = true; 285 SLPVectorization = false; 286 LoopUnrolling = true; 287 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll; 288 LicmMssaOptCap = SetLicmMssaOptCap; 289 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap; 290 CallGraphProfile = true; 291 MergeFunctions = false; 292 } 293 294 namespace llvm { 295 cl::opt<bool> PrintPipelinePasses( 296 "print-pipeline-passes", 297 cl::desc("Print a '-passes' compatible string describing the pipeline " 298 "(best-effort only).")); 299 300 extern cl::opt<unsigned> MaxDevirtIterations; 301 extern cl::opt<bool> EnableConstraintElimination; 302 extern cl::opt<bool> EnableFunctionSpecialization; 303 extern cl::opt<bool> EnableGVNHoist; 304 extern cl::opt<bool> EnableGVNSink; 305 extern cl::opt<bool> EnableHotColdSplit; 306 extern cl::opt<bool> EnableIROutliner; 307 extern cl::opt<bool> EnableOrderFileInstrumentation; 308 extern cl::opt<bool> EnableCHR; 309 extern cl::opt<bool> EnableLoopInterchange; 310 extern cl::opt<bool> EnableUnrollAndJam; 311 extern cl::opt<bool> EnableLoopFlatten; 312 extern cl::opt<bool> EnableDFAJumpThreading; 313 extern cl::opt<bool> RunNewGVN; 314 extern cl::opt<bool> RunPartialInlining; 315 extern cl::opt<bool> ExtraVectorizerPasses; 316 317 extern cl::opt<bool> FlattenedProfileUsed; 318 319 extern cl::opt<AttributorRunOption> AttributorRun; 320 extern cl::opt<bool> EnableKnowledgeRetention; 321 322 extern cl::opt<bool> EnableMatrix; 323 324 extern cl::opt<bool> DisablePreInliner; 325 extern cl::opt<int> PreInlineThreshold; 326 } // namespace llvm 327 328 const OptimizationLevel OptimizationLevel::O0 = { 329 /*SpeedLevel*/ 0, 330 /*SizeLevel*/ 0}; 331 const OptimizationLevel OptimizationLevel::O1 = { 332 /*SpeedLevel*/ 1, 333 /*SizeLevel*/ 0}; 334 const OptimizationLevel OptimizationLevel::O2 = { 335 /*SpeedLevel*/ 2, 336 /*SizeLevel*/ 0}; 337 const OptimizationLevel OptimizationLevel::O3 = { 338 /*SpeedLevel*/ 3, 339 /*SizeLevel*/ 0}; 340 const OptimizationLevel OptimizationLevel::Os = { 341 /*SpeedLevel*/ 2, 342 /*SizeLevel*/ 1}; 343 const OptimizationLevel OptimizationLevel::Oz = { 344 /*SpeedLevel*/ 2, 345 /*SizeLevel*/ 2}; 346 347 namespace { 348 349 // The following passes/analyses have custom names, otherwise their name will 350 // include `(anonymous namespace)`. These are special since they are only for 351 // testing purposes and don't live in a header file. 352 353 /// No-op module pass which does nothing. 354 struct NoOpModulePass : PassInfoMixin<NoOpModulePass> { 355 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) { 356 return PreservedAnalyses::all(); 357 } 358 359 static StringRef name() { return "NoOpModulePass"; } 360 }; 361 362 /// No-op module analysis. 363 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> { 364 friend AnalysisInfoMixin<NoOpModuleAnalysis>; 365 static AnalysisKey Key; 366 367 public: 368 struct Result {}; 369 Result run(Module &, ModuleAnalysisManager &) { return Result(); } 370 static StringRef name() { return "NoOpModuleAnalysis"; } 371 }; 372 373 /// No-op CGSCC pass which does nothing. 374 struct NoOpCGSCCPass : PassInfoMixin<NoOpCGSCCPass> { 375 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &, 376 LazyCallGraph &, CGSCCUpdateResult &UR) { 377 return PreservedAnalyses::all(); 378 } 379 static StringRef name() { return "NoOpCGSCCPass"; } 380 }; 381 382 /// No-op CGSCC analysis. 383 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> { 384 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>; 385 static AnalysisKey Key; 386 387 public: 388 struct Result {}; 389 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) { 390 return Result(); 391 } 392 static StringRef name() { return "NoOpCGSCCAnalysis"; } 393 }; 394 395 /// No-op function pass which does nothing. 396 struct NoOpFunctionPass : PassInfoMixin<NoOpFunctionPass> { 397 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) { 398 return PreservedAnalyses::all(); 399 } 400 static StringRef name() { return "NoOpFunctionPass"; } 401 }; 402 403 /// No-op function analysis. 404 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> { 405 friend AnalysisInfoMixin<NoOpFunctionAnalysis>; 406 static AnalysisKey Key; 407 408 public: 409 struct Result {}; 410 Result run(Function &, FunctionAnalysisManager &) { return Result(); } 411 static StringRef name() { return "NoOpFunctionAnalysis"; } 412 }; 413 414 /// No-op loop pass which does nothing. 415 struct NoOpLoopPass : PassInfoMixin<NoOpLoopPass> { 416 PreservedAnalyses run(Loop &L, LoopAnalysisManager &, 417 LoopStandardAnalysisResults &, LPMUpdater &) { 418 return PreservedAnalyses::all(); 419 } 420 static StringRef name() { return "NoOpLoopPass"; } 421 }; 422 423 /// No-op loop analysis. 424 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> { 425 friend AnalysisInfoMixin<NoOpLoopAnalysis>; 426 static AnalysisKey Key; 427 428 public: 429 struct Result {}; 430 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) { 431 return Result(); 432 } 433 static StringRef name() { return "NoOpLoopAnalysis"; } 434 }; 435 436 AnalysisKey NoOpModuleAnalysis::Key; 437 AnalysisKey NoOpCGSCCAnalysis::Key; 438 AnalysisKey NoOpFunctionAnalysis::Key; 439 AnalysisKey NoOpLoopAnalysis::Key; 440 441 /// Whether or not we should populate a PassInstrumentationCallbacks's class to 442 /// pass name map. 443 /// 444 /// This is for optimization purposes so we don't populate it if we never use 445 /// it. This should be updated if new pass instrumentation wants to use the map. 446 /// We currently only use this for --print-before/after. 447 bool shouldPopulateClassToPassNames() { 448 return PrintPipelinePasses || !printBeforePasses().empty() || 449 !printAfterPasses().empty(); 450 } 451 452 } // namespace 453 454 PassBuilder::PassBuilder(TargetMachine *TM, PipelineTuningOptions PTO, 455 Optional<PGOOptions> PGOOpt, 456 PassInstrumentationCallbacks *PIC) 457 : TM(TM), PTO(PTO), PGOOpt(PGOOpt), PIC(PIC) { 458 if (TM) 459 TM->registerPassBuilderCallbacks(*this); 460 if (PIC && shouldPopulateClassToPassNames()) { 461 #define MODULE_PASS(NAME, CREATE_PASS) \ 462 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); 463 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 464 PIC->addClassToPassName(CLASS, NAME); 465 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 466 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); 467 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 468 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); 469 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 470 PIC->addClassToPassName(CLASS, NAME); 471 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 472 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); 473 #define LOOP_PASS(NAME, CREATE_PASS) \ 474 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); 475 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 476 PIC->addClassToPassName(CLASS, NAME); 477 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 478 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); 479 #define CGSCC_PASS(NAME, CREATE_PASS) \ 480 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); 481 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 482 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); 483 #include "PassRegistry.def" 484 } 485 } 486 487 void PassBuilder::invokePeepholeEPCallbacks(FunctionPassManager &FPM, 488 OptimizationLevel Level) { 489 for (auto &C : PeepholeEPCallbacks) 490 C(FPM, Level); 491 } 492 493 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) { 494 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 495 MAM.registerPass([&] { return CREATE_PASS; }); 496 #include "PassRegistry.def" 497 498 for (auto &C : ModuleAnalysisRegistrationCallbacks) 499 C(MAM); 500 } 501 502 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) { 503 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 504 CGAM.registerPass([&] { return CREATE_PASS; }); 505 #include "PassRegistry.def" 506 507 for (auto &C : CGSCCAnalysisRegistrationCallbacks) 508 C(CGAM); 509 } 510 511 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) { 512 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 513 FAM.registerPass([&] { return CREATE_PASS; }); 514 #include "PassRegistry.def" 515 516 for (auto &C : FunctionAnalysisRegistrationCallbacks) 517 C(FAM); 518 } 519 520 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) { 521 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 522 LAM.registerPass([&] { return CREATE_PASS; }); 523 #include "PassRegistry.def" 524 525 for (auto &C : LoopAnalysisRegistrationCallbacks) 526 C(LAM); 527 } 528 529 // Helper to add AnnotationRemarksPass. 530 static void addAnnotationRemarksPass(ModulePassManager &MPM) { 531 FunctionPassManager FPM; 532 FPM.addPass(AnnotationRemarksPass()); 533 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 534 } 535 536 // Helper to check if the current compilation phase is preparing for LTO 537 static bool isLTOPreLink(ThinOrFullLTOPhase Phase) { 538 return Phase == ThinOrFullLTOPhase::ThinLTOPreLink || 539 Phase == ThinOrFullLTOPhase::FullLTOPreLink; 540 } 541 542 // TODO: Investigate the cost/benefit of tail call elimination on debugging. 543 FunctionPassManager 544 PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level, 545 ThinOrFullLTOPhase Phase) { 546 547 FunctionPassManager FPM; 548 549 // Form SSA out of local memory accesses after breaking apart aggregates into 550 // scalars. 551 FPM.addPass(SROA()); 552 553 // Catch trivial redundancies 554 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */)); 555 556 // Hoisting of scalars and load expressions. 557 FPM.addPass(SimplifyCFGPass()); 558 FPM.addPass(InstCombinePass()); 559 560 FPM.addPass(LibCallsShrinkWrapPass()); 561 562 invokePeepholeEPCallbacks(FPM, Level); 563 564 FPM.addPass(SimplifyCFGPass()); 565 566 // Form canonically associated expression trees, and simplify the trees using 567 // basic mathematical properties. For example, this will form (nearly) 568 // minimal multiplication trees. 569 FPM.addPass(ReassociatePass()); 570 571 // Add the primary loop simplification pipeline. 572 // FIXME: Currently this is split into two loop pass pipelines because we run 573 // some function passes in between them. These can and should be removed 574 // and/or replaced by scheduling the loop pass equivalents in the correct 575 // positions. But those equivalent passes aren't powerful enough yet. 576 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still 577 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to 578 // fully replace `SimplifyCFGPass`, and the closest to the other we have is 579 // `LoopInstSimplify`. 580 LoopPassManager LPM1, LPM2; 581 582 // Simplify the loop body. We do this initially to clean up after other loop 583 // passes run, either when iterating on a loop or on inner loops with 584 // implications on the outer loop. 585 LPM1.addPass(LoopInstSimplifyPass()); 586 LPM1.addPass(LoopSimplifyCFGPass()); 587 588 // Try to remove as much code from the loop header as possible, 589 // to reduce amount of IR that will have to be duplicated. 590 // TODO: Investigate promotion cap for O1. 591 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); 592 593 LPM1.addPass(LoopRotatePass(/* Disable header duplication */ true, 594 isLTOPreLink(Phase))); 595 // TODO: Investigate promotion cap for O1. 596 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); 597 LPM1.addPass(SimpleLoopUnswitchPass()); 598 599 LPM2.addPass(LoopIdiomRecognizePass()); 600 LPM2.addPass(IndVarSimplifyPass()); 601 602 for (auto &C : LateLoopOptimizationsEPCallbacks) 603 C(LPM2, Level); 604 605 LPM2.addPass(LoopDeletionPass()); 606 607 if (EnableLoopInterchange) 608 LPM2.addPass(LoopInterchangePass()); 609 610 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO 611 // because it changes IR to makes profile annotation in back compile 612 // inaccurate. The normal unroller doesn't pay attention to forced full unroll 613 // attributes so we need to make sure and allow the full unroll pass to pay 614 // attention to it. 615 if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt || 616 PGOOpt->Action != PGOOptions::SampleUse) 617 LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(), 618 /* OnlyWhenForced= */ !PTO.LoopUnrolling, 619 PTO.ForgetAllSCEVInLoopUnroll)); 620 621 for (auto &C : LoopOptimizerEndEPCallbacks) 622 C(LPM2, Level); 623 624 // We provide the opt remark emitter pass for LICM to use. We only need to do 625 // this once as it is immutable. 626 FPM.addPass( 627 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 628 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), 629 /*UseMemorySSA=*/true, 630 /*UseBlockFrequencyInfo=*/true)); 631 FPM.addPass(SimplifyCFGPass()); 632 FPM.addPass(InstCombinePass()); 633 if (EnableLoopFlatten) 634 FPM.addPass(createFunctionToLoopPassAdaptor(LoopFlattenPass())); 635 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA. 636 // *All* loop passes must preserve it, in order to be able to use it. 637 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), 638 /*UseMemorySSA=*/false, 639 /*UseBlockFrequencyInfo=*/false)); 640 641 // Delete small array after loop unroll. 642 FPM.addPass(SROA()); 643 644 // Specially optimize memory movement as it doesn't look like dataflow in SSA. 645 FPM.addPass(MemCpyOptPass()); 646 647 // Sparse conditional constant propagation. 648 // FIXME: It isn't clear why we do this *after* loop passes rather than 649 // before... 650 FPM.addPass(SCCPPass()); 651 652 // Delete dead bit computations (instcombine runs after to fold away the dead 653 // computations, and then ADCE will run later to exploit any new DCE 654 // opportunities that creates). 655 FPM.addPass(BDCEPass()); 656 657 // Run instcombine after redundancy and dead bit elimination to exploit 658 // opportunities opened up by them. 659 FPM.addPass(InstCombinePass()); 660 invokePeepholeEPCallbacks(FPM, Level); 661 662 FPM.addPass(CoroElidePass()); 663 664 for (auto &C : ScalarOptimizerLateEPCallbacks) 665 C(FPM, Level); 666 667 // Finally, do an expensive DCE pass to catch all the dead code exposed by 668 // the simplifications and basic cleanup after all the simplifications. 669 // TODO: Investigate if this is too expensive. 670 FPM.addPass(ADCEPass()); 671 FPM.addPass(SimplifyCFGPass()); 672 FPM.addPass(InstCombinePass()); 673 invokePeepholeEPCallbacks(FPM, Level); 674 675 return FPM; 676 } 677 678 FunctionPassManager 679 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level, 680 ThinOrFullLTOPhase Phase) { 681 assert(Level != OptimizationLevel::O0 && "Must request optimizations!"); 682 683 // The O1 pipeline has a separate pipeline creation function to simplify 684 // construction readability. 685 if (Level.getSpeedupLevel() == 1) 686 return buildO1FunctionSimplificationPipeline(Level, Phase); 687 688 FunctionPassManager FPM; 689 690 // Form SSA out of local memory accesses after breaking apart aggregates into 691 // scalars. 692 FPM.addPass(SROA()); 693 694 // Catch trivial redundancies 695 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */)); 696 if (EnableKnowledgeRetention) 697 FPM.addPass(AssumeSimplifyPass()); 698 699 // Hoisting of scalars and load expressions. 700 if (EnableGVNHoist) 701 FPM.addPass(GVNHoistPass()); 702 703 // Global value numbering based sinking. 704 if (EnableGVNSink) { 705 FPM.addPass(GVNSinkPass()); 706 FPM.addPass(SimplifyCFGPass()); 707 } 708 709 if (EnableConstraintElimination) 710 FPM.addPass(ConstraintEliminationPass()); 711 712 // Speculative execution if the target has divergent branches; otherwise nop. 713 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true)); 714 715 // Optimize based on known information about branches, and cleanup afterward. 716 FPM.addPass(JumpThreadingPass()); 717 FPM.addPass(CorrelatedValuePropagationPass()); 718 719 FPM.addPass(SimplifyCFGPass()); 720 if (Level == OptimizationLevel::O3) 721 FPM.addPass(AggressiveInstCombinePass()); 722 FPM.addPass(InstCombinePass()); 723 724 if (!Level.isOptimizingForSize()) 725 FPM.addPass(LibCallsShrinkWrapPass()); 726 727 invokePeepholeEPCallbacks(FPM, Level); 728 729 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy 730 // using the size value profile. Don't perform this when optimizing for size. 731 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse && 732 !Level.isOptimizingForSize()) 733 FPM.addPass(PGOMemOPSizeOpt()); 734 735 FPM.addPass(TailCallElimPass()); 736 FPM.addPass(SimplifyCFGPass()); 737 738 // Form canonically associated expression trees, and simplify the trees using 739 // basic mathematical properties. For example, this will form (nearly) 740 // minimal multiplication trees. 741 FPM.addPass(ReassociatePass()); 742 743 // Add the primary loop simplification pipeline. 744 // FIXME: Currently this is split into two loop pass pipelines because we run 745 // some function passes in between them. These can and should be removed 746 // and/or replaced by scheduling the loop pass equivalents in the correct 747 // positions. But those equivalent passes aren't powerful enough yet. 748 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still 749 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to 750 // fully replace `SimplifyCFGPass`, and the closest to the other we have is 751 // `LoopInstSimplify`. 752 LoopPassManager LPM1, LPM2; 753 754 // Simplify the loop body. We do this initially to clean up after other loop 755 // passes run, either when iterating on a loop or on inner loops with 756 // implications on the outer loop. 757 LPM1.addPass(LoopInstSimplifyPass()); 758 LPM1.addPass(LoopSimplifyCFGPass()); 759 760 // Try to remove as much code from the loop header as possible, 761 // to reduce amount of IR that will have to be duplicated. 762 // TODO: Investigate promotion cap for O1. 763 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); 764 765 // Disable header duplication in loop rotation at -Oz. 766 LPM1.addPass( 767 LoopRotatePass(Level != OptimizationLevel::Oz, isLTOPreLink(Phase))); 768 // TODO: Investigate promotion cap for O1. 769 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); 770 LPM1.addPass( 771 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3 && 772 EnableO3NonTrivialUnswitching)); 773 LPM2.addPass(LoopIdiomRecognizePass()); 774 LPM2.addPass(IndVarSimplifyPass()); 775 776 for (auto &C : LateLoopOptimizationsEPCallbacks) 777 C(LPM2, Level); 778 779 LPM2.addPass(LoopDeletionPass()); 780 781 if (EnableLoopInterchange) 782 LPM2.addPass(LoopInterchangePass()); 783 784 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO 785 // because it changes IR to makes profile annotation in back compile 786 // inaccurate. The normal unroller doesn't pay attention to forced full unroll 787 // attributes so we need to make sure and allow the full unroll pass to pay 788 // attention to it. 789 if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt || 790 PGOOpt->Action != PGOOptions::SampleUse) 791 LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(), 792 /* OnlyWhenForced= */ !PTO.LoopUnrolling, 793 PTO.ForgetAllSCEVInLoopUnroll)); 794 795 for (auto &C : LoopOptimizerEndEPCallbacks) 796 C(LPM2, Level); 797 798 // We provide the opt remark emitter pass for LICM to use. We only need to do 799 // this once as it is immutable. 800 FPM.addPass( 801 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 802 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), 803 /*UseMemorySSA=*/true, 804 /*UseBlockFrequencyInfo=*/true)); 805 FPM.addPass(SimplifyCFGPass()); 806 FPM.addPass(InstCombinePass()); 807 if (EnableLoopFlatten) 808 FPM.addPass(createFunctionToLoopPassAdaptor(LoopFlattenPass())); 809 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass, 810 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA. 811 // *All* loop passes must preserve it, in order to be able to use it. 812 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), 813 /*UseMemorySSA=*/false, 814 /*UseBlockFrequencyInfo=*/false)); 815 816 // Delete small array after loop unroll. 817 FPM.addPass(SROA()); 818 819 // Eliminate redundancies. 820 FPM.addPass(MergedLoadStoreMotionPass()); 821 if (RunNewGVN) 822 FPM.addPass(NewGVNPass()); 823 else 824 FPM.addPass(GVN()); 825 826 // Sparse conditional constant propagation. 827 // FIXME: It isn't clear why we do this *after* loop passes rather than 828 // before... 829 FPM.addPass(SCCPPass()); 830 831 // Delete dead bit computations (instcombine runs after to fold away the dead 832 // computations, and then ADCE will run later to exploit any new DCE 833 // opportunities that creates). 834 FPM.addPass(BDCEPass()); 835 836 // Run instcombine after redundancy and dead bit elimination to exploit 837 // opportunities opened up by them. 838 FPM.addPass(InstCombinePass()); 839 invokePeepholeEPCallbacks(FPM, Level); 840 841 // Re-consider control flow based optimizations after redundancy elimination, 842 // redo DCE, etc. 843 if (EnableDFAJumpThreading && Level.getSizeLevel() == 0) 844 FPM.addPass(DFAJumpThreadingPass()); 845 846 FPM.addPass(JumpThreadingPass()); 847 FPM.addPass(CorrelatedValuePropagationPass()); 848 849 // Finally, do an expensive DCE pass to catch all the dead code exposed by 850 // the simplifications and basic cleanup after all the simplifications. 851 // TODO: Investigate if this is too expensive. 852 FPM.addPass(ADCEPass()); 853 854 // Specially optimize memory movement as it doesn't look like dataflow in SSA. 855 FPM.addPass(MemCpyOptPass()); 856 857 FPM.addPass(DSEPass()); 858 FPM.addPass(createFunctionToLoopPassAdaptor( 859 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap), 860 /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true)); 861 862 FPM.addPass(CoroElidePass()); 863 864 for (auto &C : ScalarOptimizerLateEPCallbacks) 865 C(FPM, Level); 866 867 FPM.addPass(SimplifyCFGPass( 868 SimplifyCFGOptions().hoistCommonInsts(true).sinkCommonInsts(true))); 869 FPM.addPass(InstCombinePass()); 870 invokePeepholeEPCallbacks(FPM, Level); 871 872 if (EnableCHR && Level == OptimizationLevel::O3 && PGOOpt && 873 (PGOOpt->Action == PGOOptions::IRUse || 874 PGOOpt->Action == PGOOptions::SampleUse)) 875 FPM.addPass(ControlHeightReductionPass()); 876 877 return FPM; 878 } 879 880 void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) { 881 MPM.addPass(CanonicalizeAliasesPass()); 882 MPM.addPass(NameAnonGlobalPass()); 883 } 884 885 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, 886 OptimizationLevel Level, bool RunProfileGen, 887 bool IsCS, std::string ProfileFile, 888 std::string ProfileRemappingFile) { 889 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!"); 890 if (!IsCS && !DisablePreInliner) { 891 InlineParams IP; 892 893 IP.DefaultThreshold = PreInlineThreshold; 894 895 // FIXME: The hint threshold has the same value used by the regular inliner 896 // when not optimzing for size. This should probably be lowered after 897 // performance testing. 898 // FIXME: this comment is cargo culted from the old pass manager, revisit). 899 IP.HintThreshold = Level.isOptimizingForSize() ? PreInlineThreshold : 325; 900 ModuleInlinerWrapperPass MIWP(IP); 901 CGSCCPassManager &CGPipeline = MIWP.getPM(); 902 903 FunctionPassManager FPM; 904 FPM.addPass(SROA()); 905 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies. 906 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks. 907 FPM.addPass(InstCombinePass()); // Combine silly sequences. 908 invokePeepholeEPCallbacks(FPM, Level); 909 910 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM))); 911 912 MPM.addPass(std::move(MIWP)); 913 914 // Delete anything that is now dead to make sure that we don't instrument 915 // dead code. Instrumentation can end up keeping dead code around and 916 // dramatically increase code size. 917 MPM.addPass(GlobalDCEPass()); 918 } 919 920 if (!RunProfileGen) { 921 assert(!ProfileFile.empty() && "Profile use expecting a profile file!"); 922 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS)); 923 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 924 // RequireAnalysisPass for PSI before subsequent non-module passes. 925 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 926 return; 927 } 928 929 // Perform PGO instrumentation. 930 MPM.addPass(PGOInstrumentationGen(IsCS)); 931 932 FunctionPassManager FPM; 933 // Disable header duplication in loop rotation at -Oz. 934 FPM.addPass(createFunctionToLoopPassAdaptor( 935 LoopRotatePass(Level != OptimizationLevel::Oz), /*UseMemorySSA=*/false, 936 /*UseBlockFrequencyInfo=*/false)); 937 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 938 939 // Add the profile lowering pass. 940 InstrProfOptions Options; 941 if (!ProfileFile.empty()) 942 Options.InstrProfileOutput = ProfileFile; 943 // Do counter promotion at Level greater than O0. 944 Options.DoCounterPromotion = true; 945 Options.UseBFIInPromotion = IsCS; 946 MPM.addPass(InstrProfiling(Options, IsCS)); 947 } 948 949 void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM, 950 bool RunProfileGen, bool IsCS, 951 std::string ProfileFile, 952 std::string ProfileRemappingFile) { 953 if (!RunProfileGen) { 954 assert(!ProfileFile.empty() && "Profile use expecting a profile file!"); 955 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS)); 956 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 957 // RequireAnalysisPass for PSI before subsequent non-module passes. 958 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 959 return; 960 } 961 962 // Perform PGO instrumentation. 963 MPM.addPass(PGOInstrumentationGen(IsCS)); 964 // Add the profile lowering pass. 965 InstrProfOptions Options; 966 if (!ProfileFile.empty()) 967 Options.InstrProfileOutput = ProfileFile; 968 // Do not do counter promotion at O0. 969 Options.DoCounterPromotion = false; 970 Options.UseBFIInPromotion = IsCS; 971 MPM.addPass(InstrProfiling(Options, IsCS)); 972 } 973 974 static InlineParams getInlineParamsFromOptLevel(OptimizationLevel Level) { 975 return getInlineParams(Level.getSpeedupLevel(), Level.getSizeLevel()); 976 } 977 978 ModuleInlinerWrapperPass 979 PassBuilder::buildInlinerPipeline(OptimizationLevel Level, 980 ThinOrFullLTOPhase Phase) { 981 InlineParams IP = getInlineParamsFromOptLevel(Level); 982 if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt && 983 PGOOpt->Action == PGOOptions::SampleUse) 984 IP.HotCallSiteThreshold = 0; 985 986 if (PGOOpt) 987 IP.EnableDeferral = EnablePGOInlineDeferral; 988 989 ModuleInlinerWrapperPass MIWP(IP, PerformMandatoryInliningsFirst, 990 UseInlineAdvisor, MaxDevirtIterations); 991 992 // Require the GlobalsAA analysis for the module so we can query it within 993 // the CGSCC pipeline. 994 MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>()); 995 // Invalidate AAManager so it can be recreated and pick up the newly available 996 // GlobalsAA. 997 MIWP.addModulePass( 998 createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>())); 999 1000 // Require the ProfileSummaryAnalysis for the module so we can query it within 1001 // the inliner pass. 1002 MIWP.addModulePass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 1003 1004 // Now begin the main postorder CGSCC pipeline. 1005 // FIXME: The current CGSCC pipeline has its origins in the legacy pass 1006 // manager and trying to emulate its precise behavior. Much of this doesn't 1007 // make a lot of sense and we should revisit the core CGSCC structure. 1008 CGSCCPassManager &MainCGPipeline = MIWP.getPM(); 1009 1010 // Note: historically, the PruneEH pass was run first to deduce nounwind and 1011 // generally clean up exception handling overhead. It isn't clear this is 1012 // valuable as the inliner doesn't currently care whether it is inlining an 1013 // invoke or a call. 1014 1015 if (AttributorRun & AttributorRunOption::CGSCC) 1016 MainCGPipeline.addPass(AttributorCGSCCPass()); 1017 1018 // Now deduce any function attributes based in the current code. 1019 MainCGPipeline.addPass(PostOrderFunctionAttrsPass()); 1020 1021 // When at O3 add argument promotion to the pass pipeline. 1022 // FIXME: It isn't at all clear why this should be limited to O3. 1023 if (Level == OptimizationLevel::O3) 1024 MainCGPipeline.addPass(ArgumentPromotionPass()); 1025 1026 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 1027 // there are no OpenMP runtime calls present in the module. 1028 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3) 1029 MainCGPipeline.addPass(OpenMPOptCGSCCPass()); 1030 1031 for (auto &C : CGSCCOptimizerLateEPCallbacks) 1032 C(MainCGPipeline, Level); 1033 1034 // Lastly, add the core function simplification pipeline nested inside the 1035 // CGSCC walk. 1036 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor( 1037 buildFunctionSimplificationPipeline(Level, Phase))); 1038 1039 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0)); 1040 1041 return MIWP; 1042 } 1043 1044 ModulePassManager 1045 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level, 1046 ThinOrFullLTOPhase Phase) { 1047 ModulePassManager MPM; 1048 1049 // Place pseudo probe instrumentation as the first pass of the pipeline to 1050 // minimize the impact of optimization changes. 1051 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && 1052 Phase != ThinOrFullLTOPhase::ThinLTOPostLink) 1053 MPM.addPass(SampleProfileProbePass(TM)); 1054 1055 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse); 1056 1057 // In ThinLTO mode, when flattened profile is used, all the available 1058 // profile information will be annotated in PreLink phase so there is 1059 // no need to load the profile again in PostLink. 1060 bool LoadSampleProfile = 1061 HasSampleProfile && 1062 !(FlattenedProfileUsed && Phase == ThinOrFullLTOPhase::ThinLTOPostLink); 1063 1064 // During the ThinLTO backend phase we perform early indirect call promotion 1065 // here, before globalopt. Otherwise imported available_externally functions 1066 // look unreferenced and are removed. If we are going to load the sample 1067 // profile then defer until later. 1068 // TODO: See if we can move later and consolidate with the location where 1069 // we perform ICP when we are loading a sample profile. 1070 // TODO: We pass HasSampleProfile (whether there was a sample profile file 1071 // passed to the compile) to the SamplePGO flag of ICP. This is used to 1072 // determine whether the new direct calls are annotated with prof metadata. 1073 // Ideally this should be determined from whether the IR is annotated with 1074 // sample profile, and not whether the a sample profile was provided on the 1075 // command line. E.g. for flattened profiles where we will not be reloading 1076 // the sample profile in the ThinLTO backend, we ideally shouldn't have to 1077 // provide the sample profile file. 1078 if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink && !LoadSampleProfile) 1079 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile)); 1080 1081 // Do basic inference of function attributes from known properties of system 1082 // libraries and other oracles. 1083 MPM.addPass(InferFunctionAttrsPass()); 1084 1085 // Create an early function pass manager to cleanup the output of the 1086 // frontend. 1087 FunctionPassManager EarlyFPM; 1088 // Lower llvm.expect to metadata before attempting transforms. 1089 // Compare/branch metadata may alter the behavior of passes like SimplifyCFG. 1090 EarlyFPM.addPass(LowerExpectIntrinsicPass()); 1091 EarlyFPM.addPass(SimplifyCFGPass()); 1092 EarlyFPM.addPass(SROA()); 1093 EarlyFPM.addPass(EarlyCSEPass()); 1094 EarlyFPM.addPass(CoroEarlyPass()); 1095 if (Level == OptimizationLevel::O3) 1096 EarlyFPM.addPass(CallSiteSplittingPass()); 1097 1098 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation 1099 // to convert bitcast to direct calls so that they can be inlined during the 1100 // profile annotation prepration step. 1101 // More details about SamplePGO design can be found in: 1102 // https://research.google.com/pubs/pub45290.html 1103 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured. 1104 if (LoadSampleProfile) 1105 EarlyFPM.addPass(InstCombinePass()); 1106 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM))); 1107 1108 if (LoadSampleProfile) { 1109 // Annotate sample profile right after early FPM to ensure freshness of 1110 // the debug info. 1111 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile, 1112 PGOOpt->ProfileRemappingFile, Phase)); 1113 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 1114 // RequireAnalysisPass for PSI before subsequent non-module passes. 1115 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 1116 // Do not invoke ICP in the LTOPrelink phase as it makes it hard 1117 // for the profile annotation to be accurate in the LTO backend. 1118 if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink && 1119 Phase != ThinOrFullLTOPhase::FullLTOPreLink) 1120 // We perform early indirect call promotion here, before globalopt. 1121 // This is important for the ThinLTO backend phase because otherwise 1122 // imported available_externally functions look unreferenced and are 1123 // removed. 1124 MPM.addPass( 1125 PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */)); 1126 } 1127 1128 // Try to perform OpenMP specific optimizations on the module. This is a 1129 // (quick!) no-op if there are no OpenMP runtime calls present in the module. 1130 if (Level != OptimizationLevel::O0) 1131 MPM.addPass(OpenMPOptPass()); 1132 1133 if (AttributorRun & AttributorRunOption::MODULE) 1134 MPM.addPass(AttributorPass()); 1135 1136 // Lower type metadata and the type.test intrinsic in the ThinLTO 1137 // post link pipeline after ICP. This is to enable usage of the type 1138 // tests in ICP sequences. 1139 if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink) 1140 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1141 1142 for (auto &C : PipelineEarlySimplificationEPCallbacks) 1143 C(MPM, Level); 1144 1145 // Specialize functions with IPSCCP. 1146 if (EnableFunctionSpecialization) 1147 MPM.addPass(FunctionSpecializationPass()); 1148 1149 // Interprocedural constant propagation now that basic cleanup has occurred 1150 // and prior to optimizing globals. 1151 // FIXME: This position in the pipeline hasn't been carefully considered in 1152 // years, it should be re-analyzed. 1153 MPM.addPass(IPSCCPPass()); 1154 1155 // Attach metadata to indirect call sites indicating the set of functions 1156 // they may target at run-time. This should follow IPSCCP. 1157 MPM.addPass(CalledValuePropagationPass()); 1158 1159 // Optimize globals to try and fold them into constants. 1160 MPM.addPass(GlobalOptPass()); 1161 1162 // Promote any localized globals to SSA registers. 1163 // FIXME: Should this instead by a run of SROA? 1164 // FIXME: We should probably run instcombine and simplifycfg afterward to 1165 // delete control flows that are dead once globals have been folded to 1166 // constants. 1167 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 1168 1169 // Remove any dead arguments exposed by cleanups and constant folding 1170 // globals. 1171 MPM.addPass(DeadArgumentEliminationPass()); 1172 1173 // Create a small function pass pipeline to cleanup after all the global 1174 // optimizations. 1175 FunctionPassManager GlobalCleanupPM; 1176 GlobalCleanupPM.addPass(InstCombinePass()); 1177 invokePeepholeEPCallbacks(GlobalCleanupPM, Level); 1178 1179 GlobalCleanupPM.addPass(SimplifyCFGPass()); 1180 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM))); 1181 1182 // Add all the requested passes for instrumentation PGO, if requested. 1183 if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink && 1184 (PGOOpt->Action == PGOOptions::IRInstr || 1185 PGOOpt->Action == PGOOptions::IRUse)) { 1186 addPGOInstrPasses(MPM, Level, 1187 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr, 1188 /* IsCS */ false, PGOOpt->ProfileFile, 1189 PGOOpt->ProfileRemappingFile); 1190 MPM.addPass(PGOIndirectCallPromotion(false, false)); 1191 } 1192 if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink && 1193 PGOOpt->CSAction == PGOOptions::CSIRInstr) 1194 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile)); 1195 1196 // Synthesize function entry counts for non-PGO compilation. 1197 if (EnableSyntheticCounts && !PGOOpt) 1198 MPM.addPass(SyntheticCountsPropagation()); 1199 1200 MPM.addPass(buildInlinerPipeline(Level, Phase)); 1201 1202 if (EnableMemProfiler && Phase != ThinOrFullLTOPhase::ThinLTOPreLink) { 1203 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass())); 1204 MPM.addPass(ModuleMemProfilerPass()); 1205 } 1206 1207 return MPM; 1208 } 1209 1210 /// TODO: Should LTO cause any differences to this set of passes? 1211 void PassBuilder::addVectorPasses(OptimizationLevel Level, 1212 FunctionPassManager &FPM, bool IsFullLTO) { 1213 FPM.addPass(LoopVectorizePass( 1214 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization))); 1215 1216 if (IsFullLTO) { 1217 // The vectorizer may have significantly shortened a loop body; unroll 1218 // again. Unroll small loops to hide loop backedge latency and saturate any 1219 // parallel execution resources of an out-of-order processor. We also then 1220 // need to clean up redundancies and loop invariant code. 1221 // FIXME: It would be really good to use a loop-integrated instruction 1222 // combiner for cleanup here so that the unrolling and LICM can be pipelined 1223 // across the loop nests. 1224 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 1225 if (EnableUnrollAndJam && PTO.LoopUnrolling) 1226 FPM.addPass(createFunctionToLoopPassAdaptor( 1227 LoopUnrollAndJamPass(Level.getSpeedupLevel()))); 1228 FPM.addPass(LoopUnrollPass(LoopUnrollOptions( 1229 Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling, 1230 PTO.ForgetAllSCEVInLoopUnroll))); 1231 FPM.addPass(WarnMissedTransformationsPass()); 1232 } 1233 1234 if (!IsFullLTO) { 1235 // Eliminate loads by forwarding stores from the previous iteration to loads 1236 // of the current iteration. 1237 FPM.addPass(LoopLoadEliminationPass()); 1238 } 1239 // Cleanup after the loop optimization passes. 1240 FPM.addPass(InstCombinePass()); 1241 1242 if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) { 1243 // At higher optimization levels, try to clean up any runtime overlap and 1244 // alignment checks inserted by the vectorizer. We want to track correlated 1245 // runtime checks for two inner loops in the same outer loop, fold any 1246 // common computations, hoist loop-invariant aspects out of any outer loop, 1247 // and unswitch the runtime checks if possible. Once hoisted, we may have 1248 // dead (or speculatable) control flows or more combining opportunities. 1249 FPM.addPass(EarlyCSEPass()); 1250 FPM.addPass(CorrelatedValuePropagationPass()); 1251 FPM.addPass(InstCombinePass()); 1252 LoopPassManager LPM; 1253 LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); 1254 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level == 1255 OptimizationLevel::O3)); 1256 FPM.addPass( 1257 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 1258 FPM.addPass( 1259 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true, 1260 /*UseBlockFrequencyInfo=*/true)); 1261 FPM.addPass(SimplifyCFGPass()); 1262 FPM.addPass(InstCombinePass()); 1263 } 1264 1265 // Now that we've formed fast to execute loop structures, we do further 1266 // optimizations. These are run afterward as they might block doing complex 1267 // analyses and transforms such as what are needed for loop vectorization. 1268 1269 // Cleanup after loop vectorization, etc. Simplification passes like CVP and 1270 // GVN, loop transforms, and others have already run, so it's now better to 1271 // convert to more optimized IR using more aggressive simplify CFG options. 1272 // The extra sinking transform can create larger basic blocks, so do this 1273 // before SLP vectorization. 1274 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions() 1275 .forwardSwitchCondToPhi(true) 1276 .convertSwitchToLookupTable(true) 1277 .needCanonicalLoops(false) 1278 .hoistCommonInsts(true) 1279 .sinkCommonInsts(true))); 1280 1281 if (IsFullLTO) { 1282 FPM.addPass(SCCPPass()); 1283 FPM.addPass(InstCombinePass()); 1284 FPM.addPass(BDCEPass()); 1285 } 1286 1287 // Optimize parallel scalar instruction chains into SIMD instructions. 1288 if (PTO.SLPVectorization) { 1289 FPM.addPass(SLPVectorizerPass()); 1290 if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) { 1291 FPM.addPass(EarlyCSEPass()); 1292 } 1293 } 1294 // Enhance/cleanup vector code. 1295 FPM.addPass(VectorCombinePass()); 1296 1297 if (!IsFullLTO) { 1298 FPM.addPass(InstCombinePass()); 1299 // Unroll small loops to hide loop backedge latency and saturate any 1300 // parallel execution resources of an out-of-order processor. We also then 1301 // need to clean up redundancies and loop invariant code. 1302 // FIXME: It would be really good to use a loop-integrated instruction 1303 // combiner for cleanup here so that the unrolling and LICM can be pipelined 1304 // across the loop nests. 1305 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 1306 if (EnableUnrollAndJam && PTO.LoopUnrolling) { 1307 FPM.addPass(createFunctionToLoopPassAdaptor( 1308 LoopUnrollAndJamPass(Level.getSpeedupLevel()))); 1309 } 1310 FPM.addPass(LoopUnrollPass(LoopUnrollOptions( 1311 Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling, 1312 PTO.ForgetAllSCEVInLoopUnroll))); 1313 FPM.addPass(WarnMissedTransformationsPass()); 1314 FPM.addPass(InstCombinePass()); 1315 FPM.addPass( 1316 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 1317 FPM.addPass(createFunctionToLoopPassAdaptor( 1318 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap), 1319 /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true)); 1320 } 1321 1322 // Now that we've vectorized and unrolled loops, we may have more refined 1323 // alignment information, try to re-derive it here. 1324 FPM.addPass(AlignmentFromAssumptionsPass()); 1325 1326 if (IsFullLTO) 1327 FPM.addPass(InstCombinePass()); 1328 } 1329 1330 ModulePassManager 1331 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level, 1332 bool LTOPreLink) { 1333 ModulePassManager MPM; 1334 1335 // Optimize globals now that the module is fully simplified. 1336 MPM.addPass(GlobalOptPass()); 1337 MPM.addPass(GlobalDCEPass()); 1338 1339 // Run partial inlining pass to partially inline functions that have 1340 // large bodies. 1341 if (RunPartialInlining) 1342 MPM.addPass(PartialInlinerPass()); 1343 1344 // Remove avail extern fns and globals definitions since we aren't compiling 1345 // an object file for later LTO. For LTO we want to preserve these so they 1346 // are eligible for inlining at link-time. Note if they are unreferenced they 1347 // will be removed by GlobalDCE later, so this only impacts referenced 1348 // available externally globals. Eventually they will be suppressed during 1349 // codegen, but eliminating here enables more opportunity for GlobalDCE as it 1350 // may make globals referenced by available external functions dead and saves 1351 // running remaining passes on the eliminated functions. These should be 1352 // preserved during prelinking for link-time inlining decisions. 1353 if (!LTOPreLink) 1354 MPM.addPass(EliminateAvailableExternallyPass()); 1355 1356 if (EnableOrderFileInstrumentation) 1357 MPM.addPass(InstrOrderFilePass()); 1358 1359 // Do RPO function attribute inference across the module to forward-propagate 1360 // attributes where applicable. 1361 // FIXME: Is this really an optimization rather than a canonicalization? 1362 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 1363 1364 // Do a post inline PGO instrumentation and use pass. This is a context 1365 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as 1366 // cross-module inline has not been done yet. The context sensitive 1367 // instrumentation is after all the inlines are done. 1368 if (!LTOPreLink && PGOOpt) { 1369 if (PGOOpt->CSAction == PGOOptions::CSIRInstr) 1370 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, 1371 /* IsCS */ true, PGOOpt->CSProfileGenFile, 1372 PGOOpt->ProfileRemappingFile); 1373 else if (PGOOpt->CSAction == PGOOptions::CSIRUse) 1374 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false, 1375 /* IsCS */ true, PGOOpt->ProfileFile, 1376 PGOOpt->ProfileRemappingFile); 1377 } 1378 1379 // Re-require GloblasAA here prior to function passes. This is particularly 1380 // useful as the above will have inlined, DCE'ed, and function-attr 1381 // propagated everything. We should at this point have a reasonably minimal 1382 // and richly annotated call graph. By computing aliasing and mod/ref 1383 // information for all local globals here, the late loop passes and notably 1384 // the vectorizer will be able to use them to help recognize vectorizable 1385 // memory operations. 1386 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>()); 1387 1388 FunctionPassManager OptimizePM; 1389 OptimizePM.addPass(Float2IntPass()); 1390 OptimizePM.addPass(LowerConstantIntrinsicsPass()); 1391 1392 if (EnableMatrix) { 1393 OptimizePM.addPass(LowerMatrixIntrinsicsPass()); 1394 OptimizePM.addPass(EarlyCSEPass()); 1395 } 1396 1397 // FIXME: We need to run some loop optimizations to re-rotate loops after 1398 // simplifycfg and others undo their rotation. 1399 1400 // Optimize the loop execution. These passes operate on entire loop nests 1401 // rather than on each loop in an inside-out manner, and so they are actually 1402 // function passes. 1403 1404 for (auto &C : VectorizerStartEPCallbacks) 1405 C(OptimizePM, Level); 1406 1407 // First rotate loops that may have been un-rotated by prior passes. 1408 // Disable header duplication at -Oz. 1409 OptimizePM.addPass(createFunctionToLoopPassAdaptor( 1410 LoopRotatePass(Level != OptimizationLevel::Oz, LTOPreLink), 1411 /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/false)); 1412 1413 // Distribute loops to allow partial vectorization. I.e. isolate dependences 1414 // into separate loop that would otherwise inhibit vectorization. This is 1415 // currently only performed for loops marked with the metadata 1416 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 1417 OptimizePM.addPass(LoopDistributePass()); 1418 1419 // Populates the VFABI attribute with the scalar-to-vector mappings 1420 // from the TargetLibraryInfo. 1421 OptimizePM.addPass(InjectTLIMappings()); 1422 1423 addVectorPasses(Level, OptimizePM, /* IsFullLTO */ false); 1424 1425 // Split out cold code. Splitting is done late to avoid hiding context from 1426 // other optimizations and inadvertently regressing performance. The tradeoff 1427 // is that this has a higher code size cost than splitting early. 1428 if (EnableHotColdSplit && !LTOPreLink) 1429 MPM.addPass(HotColdSplittingPass()); 1430 1431 // Search the code for similar regions of code. If enough similar regions can 1432 // be found where extracting the regions into their own function will decrease 1433 // the size of the program, we extract the regions, a deduplicate the 1434 // structurally similar regions. 1435 if (EnableIROutliner) 1436 MPM.addPass(IROutlinerPass()); 1437 1438 // Merge functions if requested. 1439 if (PTO.MergeFunctions) 1440 MPM.addPass(MergeFunctionsPass()); 1441 1442 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 1443 // canonicalization pass that enables other optimizations. As a result, 1444 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 1445 // result too early. 1446 OptimizePM.addPass(LoopSinkPass()); 1447 1448 // And finally clean up LCSSA form before generating code. 1449 OptimizePM.addPass(InstSimplifyPass()); 1450 1451 // This hoists/decomposes div/rem ops. It should run after other sink/hoist 1452 // passes to avoid re-sinking, but before SimplifyCFG because it can allow 1453 // flattening of blocks. 1454 OptimizePM.addPass(DivRemPairsPass()); 1455 1456 // LoopSink (and other loop passes since the last simplifyCFG) might have 1457 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 1458 OptimizePM.addPass(SimplifyCFGPass()); 1459 1460 OptimizePM.addPass(CoroCleanupPass()); 1461 1462 // Add the core optimizing pipeline. 1463 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM))); 1464 1465 for (auto &C : OptimizerLastEPCallbacks) 1466 C(MPM, Level); 1467 1468 if (PTO.CallGraphProfile) 1469 MPM.addPass(CGProfilePass()); 1470 1471 // Now we need to do some global optimization transforms. 1472 // FIXME: It would seem like these should come first in the optimization 1473 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird 1474 // ordering here. 1475 MPM.addPass(GlobalDCEPass()); 1476 MPM.addPass(ConstantMergePass()); 1477 1478 // TODO: Relative look table converter pass caused an issue when full lto is 1479 // enabled. See https://reviews.llvm.org/D94355 for more details. 1480 // Until the issue fixed, disable this pass during pre-linking phase. 1481 if (!LTOPreLink) 1482 MPM.addPass(RelLookupTableConverterPass()); 1483 1484 return MPM; 1485 } 1486 1487 ModulePassManager 1488 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level, 1489 bool LTOPreLink) { 1490 assert(Level != OptimizationLevel::O0 && 1491 "Must request optimizations for the default pipeline!"); 1492 1493 ModulePassManager MPM; 1494 1495 // Convert @llvm.global.annotations to !annotation metadata. 1496 MPM.addPass(Annotation2MetadataPass()); 1497 1498 // Force any function attributes we want the rest of the pipeline to observe. 1499 MPM.addPass(ForceFunctionAttrsPass()); 1500 1501 // Apply module pipeline start EP callback. 1502 for (auto &C : PipelineStartEPCallbacks) 1503 C(MPM, Level); 1504 1505 if (PGOOpt && PGOOpt->DebugInfoForProfiling) 1506 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 1507 1508 // Add the core simplification pipeline. 1509 MPM.addPass(buildModuleSimplificationPipeline( 1510 Level, LTOPreLink ? ThinOrFullLTOPhase::FullLTOPreLink 1511 : ThinOrFullLTOPhase::None)); 1512 1513 // Now add the optimization pipeline. 1514 MPM.addPass(buildModuleOptimizationPipeline(Level, LTOPreLink)); 1515 1516 if (PGOOpt && PGOOpt->PseudoProbeForProfiling) 1517 MPM.addPass(PseudoProbeUpdatePass()); 1518 1519 // Emit annotation remarks. 1520 addAnnotationRemarksPass(MPM); 1521 1522 if (LTOPreLink) 1523 addRequiredLTOPreLinkPasses(MPM); 1524 1525 return MPM; 1526 } 1527 1528 ModulePassManager 1529 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level) { 1530 assert(Level != OptimizationLevel::O0 && 1531 "Must request optimizations for the default pipeline!"); 1532 1533 ModulePassManager MPM; 1534 1535 // Convert @llvm.global.annotations to !annotation metadata. 1536 MPM.addPass(Annotation2MetadataPass()); 1537 1538 // Force any function attributes we want the rest of the pipeline to observe. 1539 MPM.addPass(ForceFunctionAttrsPass()); 1540 1541 if (PGOOpt && PGOOpt->DebugInfoForProfiling) 1542 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 1543 1544 // Apply module pipeline start EP callback. 1545 for (auto &C : PipelineStartEPCallbacks) 1546 C(MPM, Level); 1547 1548 // If we are planning to perform ThinLTO later, we don't bloat the code with 1549 // unrolling/vectorization/... now. Just simplify the module as much as we 1550 // can. 1551 MPM.addPass(buildModuleSimplificationPipeline( 1552 Level, ThinOrFullLTOPhase::ThinLTOPreLink)); 1553 1554 // Run partial inlining pass to partially inline functions that have 1555 // large bodies. 1556 // FIXME: It isn't clear whether this is really the right place to run this 1557 // in ThinLTO. Because there is another canonicalization and simplification 1558 // phase that will run after the thin link, running this here ends up with 1559 // less information than will be available later and it may grow functions in 1560 // ways that aren't beneficial. 1561 if (RunPartialInlining) 1562 MPM.addPass(PartialInlinerPass()); 1563 1564 // Reduce the size of the IR as much as possible. 1565 MPM.addPass(GlobalOptPass()); 1566 1567 // Module simplification splits coroutines, but does not fully clean up 1568 // coroutine intrinsics. To ensure ThinLTO optimization passes don't trip up 1569 // on these, we schedule the cleanup here. 1570 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass())); 1571 1572 if (PGOOpt && PGOOpt->PseudoProbeForProfiling) 1573 MPM.addPass(PseudoProbeUpdatePass()); 1574 1575 // Handle OptimizerLastEPCallbacks added by clang on PreLink. Actual 1576 // optimization is going to be done in PostLink stage, but clang can't 1577 // add callbacks there in case of in-process ThinLTO called by linker. 1578 for (auto &C : OptimizerLastEPCallbacks) 1579 C(MPM, Level); 1580 1581 // Emit annotation remarks. 1582 addAnnotationRemarksPass(MPM); 1583 1584 addRequiredLTOPreLinkPasses(MPM); 1585 1586 return MPM; 1587 } 1588 1589 ModulePassManager PassBuilder::buildThinLTODefaultPipeline( 1590 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) { 1591 ModulePassManager MPM; 1592 1593 // Convert @llvm.global.annotations to !annotation metadata. 1594 MPM.addPass(Annotation2MetadataPass()); 1595 1596 if (ImportSummary) { 1597 // These passes import type identifier resolutions for whole-program 1598 // devirtualization and CFI. They must run early because other passes may 1599 // disturb the specific instruction patterns that these passes look for, 1600 // creating dependencies on resolutions that may not appear in the summary. 1601 // 1602 // For example, GVN may transform the pattern assume(type.test) appearing in 1603 // two basic blocks into assume(phi(type.test, type.test)), which would 1604 // transform a dependency on a WPD resolution into a dependency on a type 1605 // identifier resolution for CFI. 1606 // 1607 // Also, WPD has access to more precise information than ICP and can 1608 // devirtualize more effectively, so it should operate on the IR first. 1609 // 1610 // The WPD and LowerTypeTest passes need to run at -O0 to lower type 1611 // metadata and intrinsics. 1612 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary)); 1613 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary)); 1614 } 1615 1616 if (Level == OptimizationLevel::O0) { 1617 // Run a second time to clean up any type tests left behind by WPD for use 1618 // in ICP. 1619 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1620 // Drop available_externally and unreferenced globals. This is necessary 1621 // with ThinLTO in order to avoid leaving undefined references to dead 1622 // globals in the object file. 1623 MPM.addPass(EliminateAvailableExternallyPass()); 1624 MPM.addPass(GlobalDCEPass()); 1625 return MPM; 1626 } 1627 1628 // Force any function attributes we want the rest of the pipeline to observe. 1629 MPM.addPass(ForceFunctionAttrsPass()); 1630 1631 // Add the core simplification pipeline. 1632 MPM.addPass(buildModuleSimplificationPipeline( 1633 Level, ThinOrFullLTOPhase::ThinLTOPostLink)); 1634 1635 // Now add the optimization pipeline. 1636 MPM.addPass(buildModuleOptimizationPipeline(Level)); 1637 1638 // Emit annotation remarks. 1639 addAnnotationRemarksPass(MPM); 1640 1641 return MPM; 1642 } 1643 1644 ModulePassManager 1645 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level) { 1646 assert(Level != OptimizationLevel::O0 && 1647 "Must request optimizations for the default pipeline!"); 1648 // FIXME: We should use a customized pre-link pipeline! 1649 return buildPerModuleDefaultPipeline(Level, 1650 /* LTOPreLink */ true); 1651 } 1652 1653 ModulePassManager 1654 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, 1655 ModuleSummaryIndex *ExportSummary) { 1656 ModulePassManager MPM; 1657 1658 // Convert @llvm.global.annotations to !annotation metadata. 1659 MPM.addPass(Annotation2MetadataPass()); 1660 1661 // Create a function that performs CFI checks for cross-DSO calls with targets 1662 // in the current module. 1663 MPM.addPass(CrossDSOCFIPass()); 1664 1665 if (Level == OptimizationLevel::O0) { 1666 // The WPD and LowerTypeTest passes need to run at -O0 to lower type 1667 // metadata and intrinsics. 1668 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr)); 1669 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1670 // Run a second time to clean up any type tests left behind by WPD for use 1671 // in ICP. 1672 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1673 1674 // Emit annotation remarks. 1675 addAnnotationRemarksPass(MPM); 1676 1677 return MPM; 1678 } 1679 1680 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) { 1681 // Load sample profile before running the LTO optimization pipeline. 1682 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile, 1683 PGOOpt->ProfileRemappingFile, 1684 ThinOrFullLTOPhase::FullLTOPostLink)); 1685 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 1686 // RequireAnalysisPass for PSI before subsequent non-module passes. 1687 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 1688 } 1689 1690 // Remove unused virtual tables to improve the quality of code generated by 1691 // whole-program devirtualization and bitset lowering. 1692 MPM.addPass(GlobalDCEPass()); 1693 1694 // Force any function attributes we want the rest of the pipeline to observe. 1695 MPM.addPass(ForceFunctionAttrsPass()); 1696 1697 // Do basic inference of function attributes from known properties of system 1698 // libraries and other oracles. 1699 MPM.addPass(InferFunctionAttrsPass()); 1700 1701 if (Level.getSpeedupLevel() > 1) { 1702 FunctionPassManager EarlyFPM; 1703 EarlyFPM.addPass(CallSiteSplittingPass()); 1704 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM))); 1705 1706 // Indirect call promotion. This should promote all the targets that are 1707 // left by the earlier promotion pass that promotes intra-module targets. 1708 // This two-step promotion is to save the compile time. For LTO, it should 1709 // produce the same result as if we only do promotion here. 1710 MPM.addPass(PGOIndirectCallPromotion( 1711 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)); 1712 1713 if (EnableFunctionSpecialization) 1714 MPM.addPass(FunctionSpecializationPass()); 1715 // Propagate constants at call sites into the functions they call. This 1716 // opens opportunities for globalopt (and inlining) by substituting function 1717 // pointers passed as arguments to direct uses of functions. 1718 MPM.addPass(IPSCCPPass()); 1719 1720 // Attach metadata to indirect call sites indicating the set of functions 1721 // they may target at run-time. This should follow IPSCCP. 1722 MPM.addPass(CalledValuePropagationPass()); 1723 } 1724 1725 // Now deduce any function attributes based in the current code. 1726 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 1727 PostOrderFunctionAttrsPass())); 1728 1729 // Do RPO function attribute inference across the module to forward-propagate 1730 // attributes where applicable. 1731 // FIXME: Is this really an optimization rather than a canonicalization? 1732 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 1733 1734 // Use in-range annotations on GEP indices to split globals where beneficial. 1735 MPM.addPass(GlobalSplitPass()); 1736 1737 // Run whole program optimization of virtual call when the list of callees 1738 // is fixed. 1739 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr)); 1740 1741 // Stop here at -O1. 1742 if (Level == OptimizationLevel::O1) { 1743 // The LowerTypeTestsPass needs to run to lower type metadata and the 1744 // type.test intrinsics. The pass does nothing if CFI is disabled. 1745 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1746 // Run a second time to clean up any type tests left behind by WPD for use 1747 // in ICP (which is performed earlier than this in the regular LTO 1748 // pipeline). 1749 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1750 1751 // Emit annotation remarks. 1752 addAnnotationRemarksPass(MPM); 1753 1754 return MPM; 1755 } 1756 1757 // Optimize globals to try and fold them into constants. 1758 MPM.addPass(GlobalOptPass()); 1759 1760 // Promote any localized globals to SSA registers. 1761 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 1762 1763 // Linking modules together can lead to duplicate global constant, only 1764 // keep one copy of each constant. 1765 MPM.addPass(ConstantMergePass()); 1766 1767 // Remove unused arguments from functions. 1768 MPM.addPass(DeadArgumentEliminationPass()); 1769 1770 // Reduce the code after globalopt and ipsccp. Both can open up significant 1771 // simplification opportunities, and both can propagate functions through 1772 // function pointers. When this happens, we often have to resolve varargs 1773 // calls, etc, so let instcombine do this. 1774 FunctionPassManager PeepholeFPM; 1775 if (Level == OptimizationLevel::O3) 1776 PeepholeFPM.addPass(AggressiveInstCombinePass()); 1777 PeepholeFPM.addPass(InstCombinePass()); 1778 invokePeepholeEPCallbacks(PeepholeFPM, Level); 1779 1780 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM))); 1781 1782 // Note: historically, the PruneEH pass was run first to deduce nounwind and 1783 // generally clean up exception handling overhead. It isn't clear this is 1784 // valuable as the inliner doesn't currently care whether it is inlining an 1785 // invoke or a call. 1786 // Run the inliner now. 1787 MPM.addPass(ModuleInlinerWrapperPass(getInlineParamsFromOptLevel(Level))); 1788 1789 // Optimize globals again after we ran the inliner. 1790 MPM.addPass(GlobalOptPass()); 1791 1792 // Garbage collect dead functions. 1793 MPM.addPass(GlobalDCEPass()); 1794 1795 // If we didn't decide to inline a function, check to see if we can 1796 // transform it to pass arguments by value instead of by reference. 1797 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(ArgumentPromotionPass())); 1798 1799 FunctionPassManager FPM; 1800 // The IPO Passes may leave cruft around. Clean up after them. 1801 FPM.addPass(InstCombinePass()); 1802 invokePeepholeEPCallbacks(FPM, Level); 1803 1804 FPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true)); 1805 1806 // Do a post inline PGO instrumentation and use pass. This is a context 1807 // sensitive PGO pass. 1808 if (PGOOpt) { 1809 if (PGOOpt->CSAction == PGOOptions::CSIRInstr) 1810 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, 1811 /* IsCS */ true, PGOOpt->CSProfileGenFile, 1812 PGOOpt->ProfileRemappingFile); 1813 else if (PGOOpt->CSAction == PGOOptions::CSIRUse) 1814 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false, 1815 /* IsCS */ true, PGOOpt->ProfileFile, 1816 PGOOpt->ProfileRemappingFile); 1817 } 1818 1819 // Break up allocas 1820 FPM.addPass(SROA()); 1821 1822 // LTO provides additional opportunities for tailcall elimination due to 1823 // link-time inlining, and visibility of nocapture attribute. 1824 FPM.addPass(TailCallElimPass()); 1825 1826 // Run a few AA driver optimizations here and now to cleanup the code. 1827 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1828 1829 MPM.addPass( 1830 createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass())); 1831 1832 // Require the GlobalsAA analysis for the module so we can query it within 1833 // MainFPM. 1834 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>()); 1835 // Invalidate AAManager so it can be recreated and pick up the newly available 1836 // GlobalsAA. 1837 MPM.addPass( 1838 createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>())); 1839 1840 FunctionPassManager MainFPM; 1841 MainFPM.addPass(createFunctionToLoopPassAdaptor( 1842 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap), 1843 /*USeMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true)); 1844 1845 if (RunNewGVN) 1846 MainFPM.addPass(NewGVNPass()); 1847 else 1848 MainFPM.addPass(GVN()); 1849 1850 // Remove dead memcpy()'s. 1851 MainFPM.addPass(MemCpyOptPass()); 1852 1853 // Nuke dead stores. 1854 MainFPM.addPass(DSEPass()); 1855 MainFPM.addPass(MergedLoadStoreMotionPass()); 1856 1857 // More loops are countable; try to optimize them. 1858 if (EnableLoopFlatten && Level.getSpeedupLevel() > 1) 1859 MainFPM.addPass(createFunctionToLoopPassAdaptor(LoopFlattenPass())); 1860 1861 if (EnableConstraintElimination) 1862 MainFPM.addPass(ConstraintEliminationPass()); 1863 1864 LoopPassManager LPM; 1865 LPM.addPass(IndVarSimplifyPass()); 1866 LPM.addPass(LoopDeletionPass()); 1867 // FIXME: Add loop interchange. 1868 1869 // Unroll small loops and perform peeling. 1870 LPM.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(), 1871 /* OnlyWhenForced= */ !PTO.LoopUnrolling, 1872 PTO.ForgetAllSCEVInLoopUnroll)); 1873 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA. 1874 // *All* loop passes must preserve it, in order to be able to use it. 1875 MainFPM.addPass(createFunctionToLoopPassAdaptor( 1876 std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/true)); 1877 1878 MainFPM.addPass(LoopDistributePass()); 1879 1880 addVectorPasses(Level, MainFPM, /* IsFullLTO */ true); 1881 1882 invokePeepholeEPCallbacks(MainFPM, Level); 1883 MainFPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true)); 1884 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM))); 1885 1886 // Lower type metadata and the type.test intrinsic. This pass supports 1887 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs 1888 // to be run at link time if CFI is enabled. This pass does nothing if 1889 // CFI is disabled. 1890 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1891 // Run a second time to clean up any type tests left behind by WPD for use 1892 // in ICP (which is performed earlier than this in the regular LTO pipeline). 1893 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1894 1895 // Enable splitting late in the FullLTO post-link pipeline. This is done in 1896 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses). 1897 if (EnableHotColdSplit) 1898 MPM.addPass(HotColdSplittingPass()); 1899 1900 // Add late LTO optimization passes. 1901 // Delete basic blocks, which optimization passes may have killed. 1902 MPM.addPass(createModuleToFunctionPassAdaptor( 1903 SimplifyCFGPass(SimplifyCFGOptions().hoistCommonInsts(true)))); 1904 1905 // Drop bodies of available eternally objects to improve GlobalDCE. 1906 MPM.addPass(EliminateAvailableExternallyPass()); 1907 1908 // Now that we have optimized the program, discard unreachable functions. 1909 MPM.addPass(GlobalDCEPass()); 1910 1911 if (PTO.MergeFunctions) 1912 MPM.addPass(MergeFunctionsPass()); 1913 1914 // Emit annotation remarks. 1915 addAnnotationRemarksPass(MPM); 1916 1917 return MPM; 1918 } 1919 1920 ModulePassManager PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level, 1921 bool LTOPreLink) { 1922 assert(Level == OptimizationLevel::O0 && 1923 "buildO0DefaultPipeline should only be used with O0"); 1924 1925 ModulePassManager MPM; 1926 1927 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr || 1928 PGOOpt->Action == PGOOptions::IRUse)) 1929 addPGOInstrPassesForO0( 1930 MPM, 1931 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr), 1932 /* IsCS */ false, PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile); 1933 1934 for (auto &C : PipelineStartEPCallbacks) 1935 C(MPM, Level); 1936 1937 if (PGOOpt && PGOOpt->DebugInfoForProfiling) 1938 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 1939 1940 for (auto &C : PipelineEarlySimplificationEPCallbacks) 1941 C(MPM, Level); 1942 1943 // Build a minimal pipeline based on the semantics required by LLVM, 1944 // which is just that always inlining occurs. Further, disable generating 1945 // lifetime intrinsics to avoid enabling further optimizations during 1946 // code generation. 1947 MPM.addPass(AlwaysInlinerPass( 1948 /*InsertLifetimeIntrinsics=*/false)); 1949 1950 if (PTO.MergeFunctions) 1951 MPM.addPass(MergeFunctionsPass()); 1952 1953 if (EnableMatrix) 1954 MPM.addPass( 1955 createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass(true))); 1956 1957 if (!CGSCCOptimizerLateEPCallbacks.empty()) { 1958 CGSCCPassManager CGPM; 1959 for (auto &C : CGSCCOptimizerLateEPCallbacks) 1960 C(CGPM, Level); 1961 if (!CGPM.isEmpty()) 1962 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 1963 } 1964 if (!LateLoopOptimizationsEPCallbacks.empty()) { 1965 LoopPassManager LPM; 1966 for (auto &C : LateLoopOptimizationsEPCallbacks) 1967 C(LPM, Level); 1968 if (!LPM.isEmpty()) { 1969 MPM.addPass(createModuleToFunctionPassAdaptor( 1970 createFunctionToLoopPassAdaptor(std::move(LPM)))); 1971 } 1972 } 1973 if (!LoopOptimizerEndEPCallbacks.empty()) { 1974 LoopPassManager LPM; 1975 for (auto &C : LoopOptimizerEndEPCallbacks) 1976 C(LPM, Level); 1977 if (!LPM.isEmpty()) { 1978 MPM.addPass(createModuleToFunctionPassAdaptor( 1979 createFunctionToLoopPassAdaptor(std::move(LPM)))); 1980 } 1981 } 1982 if (!ScalarOptimizerLateEPCallbacks.empty()) { 1983 FunctionPassManager FPM; 1984 for (auto &C : ScalarOptimizerLateEPCallbacks) 1985 C(FPM, Level); 1986 if (!FPM.isEmpty()) 1987 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1988 } 1989 if (!VectorizerStartEPCallbacks.empty()) { 1990 FunctionPassManager FPM; 1991 for (auto &C : VectorizerStartEPCallbacks) 1992 C(FPM, Level); 1993 if (!FPM.isEmpty()) 1994 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1995 } 1996 1997 MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass())); 1998 CGSCCPassManager CGPM; 1999 CGPM.addPass(CoroSplitPass()); 2000 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 2001 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass())); 2002 2003 for (auto &C : OptimizerLastEPCallbacks) 2004 C(MPM, Level); 2005 2006 if (LTOPreLink) 2007 addRequiredLTOPreLinkPasses(MPM); 2008 2009 return MPM; 2010 } 2011 2012 AAManager PassBuilder::buildDefaultAAPipeline() { 2013 AAManager AA; 2014 2015 // The order in which these are registered determines their priority when 2016 // being queried. 2017 2018 // First we register the basic alias analysis that provides the majority of 2019 // per-function local AA logic. This is a stateless, on-demand local set of 2020 // AA techniques. 2021 AA.registerFunctionAnalysis<BasicAA>(); 2022 2023 // Next we query fast, specialized alias analyses that wrap IR-embedded 2024 // information about aliasing. 2025 AA.registerFunctionAnalysis<ScopedNoAliasAA>(); 2026 AA.registerFunctionAnalysis<TypeBasedAA>(); 2027 2028 // Add support for querying global aliasing information when available. 2029 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module 2030 // analysis, all that the `AAManager` can do is query for any *cached* 2031 // results from `GlobalsAA` through a readonly proxy. 2032 AA.registerModuleAnalysis<GlobalsAA>(); 2033 2034 // Add target-specific alias analyses. 2035 if (TM) 2036 TM->registerDefaultAliasAnalyses(AA); 2037 2038 return AA; 2039 } 2040 2041 static Optional<int> parseRepeatPassName(StringRef Name) { 2042 if (!Name.consume_front("repeat<") || !Name.consume_back(">")) 2043 return None; 2044 int Count; 2045 if (Name.getAsInteger(0, Count) || Count <= 0) 2046 return None; 2047 return Count; 2048 } 2049 2050 static Optional<int> parseDevirtPassName(StringRef Name) { 2051 if (!Name.consume_front("devirt<") || !Name.consume_back(">")) 2052 return None; 2053 int Count; 2054 if (Name.getAsInteger(0, Count) || Count < 0) 2055 return None; 2056 return Count; 2057 } 2058 2059 static bool checkParametrizedPassName(StringRef Name, StringRef PassName) { 2060 if (!Name.consume_front(PassName)) 2061 return false; 2062 // normal pass name w/o parameters == default parameters 2063 if (Name.empty()) 2064 return true; 2065 return Name.startswith("<") && Name.endswith(">"); 2066 } 2067 2068 namespace { 2069 2070 /// This performs customized parsing of pass name with parameters. 2071 /// 2072 /// We do not need parametrization of passes in textual pipeline very often, 2073 /// yet on a rare occasion ability to specify parameters right there can be 2074 /// useful. 2075 /// 2076 /// \p Name - parameterized specification of a pass from a textual pipeline 2077 /// is a string in a form of : 2078 /// PassName '<' parameter-list '>' 2079 /// 2080 /// Parameter list is being parsed by the parser callable argument, \p Parser, 2081 /// It takes a string-ref of parameters and returns either StringError or a 2082 /// parameter list in a form of a custom parameters type, all wrapped into 2083 /// Expected<> template class. 2084 /// 2085 template <typename ParametersParseCallableT> 2086 auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name, 2087 StringRef PassName) -> decltype(Parser(StringRef{})) { 2088 using ParametersT = typename decltype(Parser(StringRef{}))::value_type; 2089 2090 StringRef Params = Name; 2091 if (!Params.consume_front(PassName)) { 2092 assert(false && 2093 "unable to strip pass name from parametrized pass specification"); 2094 } 2095 if (!Params.empty() && 2096 (!Params.consume_front("<") || !Params.consume_back(">"))) { 2097 assert(false && "invalid format for parametrized pass name"); 2098 } 2099 2100 Expected<ParametersT> Result = Parser(Params); 2101 assert((Result || Result.template errorIsA<StringError>()) && 2102 "Pass parameter parser can only return StringErrors."); 2103 return Result; 2104 } 2105 2106 /// Parser of parameters for LoopUnroll pass. 2107 Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) { 2108 LoopUnrollOptions UnrollOpts; 2109 while (!Params.empty()) { 2110 StringRef ParamName; 2111 std::tie(ParamName, Params) = Params.split(';'); 2112 int OptLevel = StringSwitch<int>(ParamName) 2113 .Case("O0", 0) 2114 .Case("O1", 1) 2115 .Case("O2", 2) 2116 .Case("O3", 3) 2117 .Default(-1); 2118 if (OptLevel >= 0) { 2119 UnrollOpts.setOptLevel(OptLevel); 2120 continue; 2121 } 2122 if (ParamName.consume_front("full-unroll-max=")) { 2123 int Count; 2124 if (ParamName.getAsInteger(0, Count)) 2125 return make_error<StringError>( 2126 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(), 2127 inconvertibleErrorCode()); 2128 UnrollOpts.setFullUnrollMaxCount(Count); 2129 continue; 2130 } 2131 2132 bool Enable = !ParamName.consume_front("no-"); 2133 if (ParamName == "partial") { 2134 UnrollOpts.setPartial(Enable); 2135 } else if (ParamName == "peeling") { 2136 UnrollOpts.setPeeling(Enable); 2137 } else if (ParamName == "profile-peeling") { 2138 UnrollOpts.setProfileBasedPeeling(Enable); 2139 } else if (ParamName == "runtime") { 2140 UnrollOpts.setRuntime(Enable); 2141 } else if (ParamName == "upperbound") { 2142 UnrollOpts.setUpperBound(Enable); 2143 } else { 2144 return make_error<StringError>( 2145 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(), 2146 inconvertibleErrorCode()); 2147 } 2148 } 2149 return UnrollOpts; 2150 } 2151 2152 Expected<bool> parseSinglePassOption(StringRef Params, StringRef OptionName, 2153 StringRef PassName) { 2154 bool Result = false; 2155 while (!Params.empty()) { 2156 StringRef ParamName; 2157 std::tie(ParamName, Params) = Params.split(';'); 2158 2159 if (ParamName == OptionName) { 2160 Result = true; 2161 } else { 2162 return make_error<StringError>( 2163 formatv("invalid {1} pass parameter '{0}' ", ParamName, PassName) 2164 .str(), 2165 inconvertibleErrorCode()); 2166 } 2167 } 2168 return Result; 2169 } 2170 2171 Expected<bool> parseEarlyCSEPassOptions(StringRef Params) { 2172 return parseSinglePassOption(Params, "memssa", "EarlyCSE"); 2173 } 2174 2175 Expected<bool> parseEntryExitInstrumenterPassOptions(StringRef Params) { 2176 return parseSinglePassOption(Params, "post-inline", "EntryExitInstrumenter"); 2177 } 2178 2179 Expected<bool> parseLoopExtractorPassOptions(StringRef Params) { 2180 return parseSinglePassOption(Params, "single", "LoopExtractor"); 2181 } 2182 2183 Expected<bool> parseLowerMatrixIntrinsicsPassOptions(StringRef Params) { 2184 return parseSinglePassOption(Params, "minimal", "LowerMatrixIntrinsics"); 2185 } 2186 2187 Expected<AddressSanitizerOptions> parseASanPassOptions(StringRef Params) { 2188 AddressSanitizerOptions Result; 2189 while (!Params.empty()) { 2190 StringRef ParamName; 2191 std::tie(ParamName, Params) = Params.split(';'); 2192 2193 if (ParamName == "kernel") { 2194 Result.CompileKernel = true; 2195 } else { 2196 return make_error<StringError>( 2197 formatv("invalid AddressSanitizer pass parameter '{0}' ", ParamName) 2198 .str(), 2199 inconvertibleErrorCode()); 2200 } 2201 } 2202 return Result; 2203 } 2204 2205 Expected<HWAddressSanitizerOptions> parseHWASanPassOptions(StringRef Params) { 2206 HWAddressSanitizerOptions Result; 2207 while (!Params.empty()) { 2208 StringRef ParamName; 2209 std::tie(ParamName, Params) = Params.split(';'); 2210 2211 if (ParamName == "recover") { 2212 Result.Recover = true; 2213 } else if (ParamName == "kernel") { 2214 Result.CompileKernel = true; 2215 } else { 2216 return make_error<StringError>( 2217 formatv("invalid HWAddressSanitizer pass parameter '{0}' ", ParamName) 2218 .str(), 2219 inconvertibleErrorCode()); 2220 } 2221 } 2222 return Result; 2223 } 2224 2225 Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) { 2226 MemorySanitizerOptions Result; 2227 while (!Params.empty()) { 2228 StringRef ParamName; 2229 std::tie(ParamName, Params) = Params.split(';'); 2230 2231 if (ParamName == "recover") { 2232 Result.Recover = true; 2233 } else if (ParamName == "kernel") { 2234 Result.Kernel = true; 2235 } else if (ParamName.consume_front("track-origins=")) { 2236 if (ParamName.getAsInteger(0, Result.TrackOrigins)) 2237 return make_error<StringError>( 2238 formatv("invalid argument to MemorySanitizer pass track-origins " 2239 "parameter: '{0}' ", 2240 ParamName) 2241 .str(), 2242 inconvertibleErrorCode()); 2243 } else { 2244 return make_error<StringError>( 2245 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName) 2246 .str(), 2247 inconvertibleErrorCode()); 2248 } 2249 } 2250 return Result; 2251 } 2252 2253 /// Parser of parameters for SimplifyCFG pass. 2254 Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) { 2255 SimplifyCFGOptions Result; 2256 while (!Params.empty()) { 2257 StringRef ParamName; 2258 std::tie(ParamName, Params) = Params.split(';'); 2259 2260 bool Enable = !ParamName.consume_front("no-"); 2261 if (ParamName == "forward-switch-cond") { 2262 Result.forwardSwitchCondToPhi(Enable); 2263 } else if (ParamName == "switch-to-lookup") { 2264 Result.convertSwitchToLookupTable(Enable); 2265 } else if (ParamName == "keep-loops") { 2266 Result.needCanonicalLoops(Enable); 2267 } else if (ParamName == "hoist-common-insts") { 2268 Result.hoistCommonInsts(Enable); 2269 } else if (ParamName == "sink-common-insts") { 2270 Result.sinkCommonInsts(Enable); 2271 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) { 2272 APInt BonusInstThreshold; 2273 if (ParamName.getAsInteger(0, BonusInstThreshold)) 2274 return make_error<StringError>( 2275 formatv("invalid argument to SimplifyCFG pass bonus-threshold " 2276 "parameter: '{0}' ", 2277 ParamName).str(), 2278 inconvertibleErrorCode()); 2279 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue()); 2280 } else { 2281 return make_error<StringError>( 2282 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(), 2283 inconvertibleErrorCode()); 2284 } 2285 } 2286 return Result; 2287 } 2288 2289 /// Parser of parameters for LoopVectorize pass. 2290 Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) { 2291 LoopVectorizeOptions Opts; 2292 while (!Params.empty()) { 2293 StringRef ParamName; 2294 std::tie(ParamName, Params) = Params.split(';'); 2295 2296 bool Enable = !ParamName.consume_front("no-"); 2297 if (ParamName == "interleave-forced-only") { 2298 Opts.setInterleaveOnlyWhenForced(Enable); 2299 } else if (ParamName == "vectorize-forced-only") { 2300 Opts.setVectorizeOnlyWhenForced(Enable); 2301 } else { 2302 return make_error<StringError>( 2303 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(), 2304 inconvertibleErrorCode()); 2305 } 2306 } 2307 return Opts; 2308 } 2309 2310 Expected<std::pair<bool, bool>> parseLoopUnswitchOptions(StringRef Params) { 2311 std::pair<bool, bool> Result = {false, true}; 2312 while (!Params.empty()) { 2313 StringRef ParamName; 2314 std::tie(ParamName, Params) = Params.split(';'); 2315 2316 bool Enable = !ParamName.consume_front("no-"); 2317 if (ParamName == "nontrivial") { 2318 Result.first = Enable; 2319 } else if (ParamName == "trivial") { 2320 Result.second = Enable; 2321 } else { 2322 return make_error<StringError>( 2323 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName) 2324 .str(), 2325 inconvertibleErrorCode()); 2326 } 2327 } 2328 return Result; 2329 } 2330 2331 Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) { 2332 bool Result = false; 2333 while (!Params.empty()) { 2334 StringRef ParamName; 2335 std::tie(ParamName, Params) = Params.split(';'); 2336 2337 bool Enable = !ParamName.consume_front("no-"); 2338 if (ParamName == "split-footer-bb") { 2339 Result = Enable; 2340 } else { 2341 return make_error<StringError>( 2342 formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ", 2343 ParamName) 2344 .str(), 2345 inconvertibleErrorCode()); 2346 } 2347 } 2348 return Result; 2349 } 2350 2351 Expected<GVNOptions> parseGVNOptions(StringRef Params) { 2352 GVNOptions Result; 2353 while (!Params.empty()) { 2354 StringRef ParamName; 2355 std::tie(ParamName, Params) = Params.split(';'); 2356 2357 bool Enable = !ParamName.consume_front("no-"); 2358 if (ParamName == "pre") { 2359 Result.setPRE(Enable); 2360 } else if (ParamName == "load-pre") { 2361 Result.setLoadPRE(Enable); 2362 } else if (ParamName == "split-backedge-load-pre") { 2363 Result.setLoadPRESplitBackedge(Enable); 2364 } else if (ParamName == "memdep") { 2365 Result.setMemDep(Enable); 2366 } else { 2367 return make_error<StringError>( 2368 formatv("invalid GVN pass parameter '{0}' ", ParamName).str(), 2369 inconvertibleErrorCode()); 2370 } 2371 } 2372 return Result; 2373 } 2374 2375 Expected<StackLifetime::LivenessType> 2376 parseStackLifetimeOptions(StringRef Params) { 2377 StackLifetime::LivenessType Result = StackLifetime::LivenessType::May; 2378 while (!Params.empty()) { 2379 StringRef ParamName; 2380 std::tie(ParamName, Params) = Params.split(';'); 2381 2382 if (ParamName == "may") { 2383 Result = StackLifetime::LivenessType::May; 2384 } else if (ParamName == "must") { 2385 Result = StackLifetime::LivenessType::Must; 2386 } else { 2387 return make_error<StringError>( 2388 formatv("invalid StackLifetime parameter '{0}' ", ParamName).str(), 2389 inconvertibleErrorCode()); 2390 } 2391 } 2392 return Result; 2393 } 2394 2395 } // namespace 2396 2397 /// Tests whether a pass name starts with a valid prefix for a default pipeline 2398 /// alias. 2399 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) { 2400 return Name.startswith("default") || Name.startswith("thinlto") || 2401 Name.startswith("lto"); 2402 } 2403 2404 /// Tests whether registered callbacks will accept a given pass name. 2405 /// 2406 /// When parsing a pipeline text, the type of the outermost pipeline may be 2407 /// omitted, in which case the type is automatically determined from the first 2408 /// pass name in the text. This may be a name that is handled through one of the 2409 /// callbacks. We check this through the oridinary parsing callbacks by setting 2410 /// up a dummy PassManager in order to not force the client to also handle this 2411 /// type of query. 2412 template <typename PassManagerT, typename CallbacksT> 2413 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) { 2414 if (!Callbacks.empty()) { 2415 PassManagerT DummyPM; 2416 for (auto &CB : Callbacks) 2417 if (CB(Name, DummyPM, {})) 2418 return true; 2419 } 2420 return false; 2421 } 2422 2423 template <typename CallbacksT> 2424 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) { 2425 // Manually handle aliases for pre-configured pipeline fragments. 2426 if (startsWithDefaultPipelineAliasPrefix(Name)) 2427 return DefaultAliasRegex.match(Name); 2428 2429 // Explicitly handle pass manager names. 2430 if (Name == "module") 2431 return true; 2432 if (Name == "cgscc") 2433 return true; 2434 if (Name == "function") 2435 return true; 2436 2437 // Explicitly handle custom-parsed pass names. 2438 if (parseRepeatPassName(Name)) 2439 return true; 2440 2441 #define MODULE_PASS(NAME, CREATE_PASS) \ 2442 if (Name == NAME) \ 2443 return true; 2444 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 2445 if (checkParametrizedPassName(Name, NAME)) \ 2446 return true; 2447 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 2448 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 2449 return true; 2450 #include "PassRegistry.def" 2451 2452 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks); 2453 } 2454 2455 template <typename CallbacksT> 2456 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) { 2457 // Explicitly handle pass manager names. 2458 if (Name == "cgscc") 2459 return true; 2460 if (Name == "function") 2461 return true; 2462 2463 // Explicitly handle custom-parsed pass names. 2464 if (parseRepeatPassName(Name)) 2465 return true; 2466 if (parseDevirtPassName(Name)) 2467 return true; 2468 2469 #define CGSCC_PASS(NAME, CREATE_PASS) \ 2470 if (Name == NAME) \ 2471 return true; 2472 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 2473 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 2474 return true; 2475 #include "PassRegistry.def" 2476 2477 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks); 2478 } 2479 2480 template <typename CallbacksT> 2481 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) { 2482 // Explicitly handle pass manager names. 2483 if (Name == "function") 2484 return true; 2485 if (Name == "loop" || Name == "loop-mssa") 2486 return true; 2487 2488 // Explicitly handle custom-parsed pass names. 2489 if (parseRepeatPassName(Name)) 2490 return true; 2491 2492 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 2493 if (Name == NAME) \ 2494 return true; 2495 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 2496 if (checkParametrizedPassName(Name, NAME)) \ 2497 return true; 2498 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 2499 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 2500 return true; 2501 #include "PassRegistry.def" 2502 2503 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks); 2504 } 2505 2506 template <typename CallbacksT> 2507 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks, 2508 bool &UseMemorySSA) { 2509 UseMemorySSA = false; 2510 2511 // Explicitly handle custom-parsed pass names. 2512 if (parseRepeatPassName(Name)) 2513 return true; 2514 2515 if (Name == "licm") { 2516 UseMemorySSA = true; 2517 return true; 2518 } 2519 2520 #define LOOP_PASS(NAME, CREATE_PASS) \ 2521 if (Name == NAME) \ 2522 return true; 2523 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 2524 if (checkParametrizedPassName(Name, NAME)) \ 2525 return true; 2526 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 2527 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 2528 return true; 2529 #include "PassRegistry.def" 2530 2531 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks); 2532 } 2533 2534 Optional<std::vector<PassBuilder::PipelineElement>> 2535 PassBuilder::parsePipelineText(StringRef Text) { 2536 std::vector<PipelineElement> ResultPipeline; 2537 2538 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = { 2539 &ResultPipeline}; 2540 for (;;) { 2541 std::vector<PipelineElement> &Pipeline = *PipelineStack.back(); 2542 size_t Pos = Text.find_first_of(",()"); 2543 Pipeline.push_back({Text.substr(0, Pos), {}}); 2544 2545 // If we have a single terminating name, we're done. 2546 if (Pos == Text.npos) 2547 break; 2548 2549 char Sep = Text[Pos]; 2550 Text = Text.substr(Pos + 1); 2551 if (Sep == ',') 2552 // Just a name ending in a comma, continue. 2553 continue; 2554 2555 if (Sep == '(') { 2556 // Push the inner pipeline onto the stack to continue processing. 2557 PipelineStack.push_back(&Pipeline.back().InnerPipeline); 2558 continue; 2559 } 2560 2561 assert(Sep == ')' && "Bogus separator!"); 2562 // When handling the close parenthesis, we greedily consume them to avoid 2563 // empty strings in the pipeline. 2564 do { 2565 // If we try to pop the outer pipeline we have unbalanced parentheses. 2566 if (PipelineStack.size() == 1) 2567 return None; 2568 2569 PipelineStack.pop_back(); 2570 } while (Text.consume_front(")")); 2571 2572 // Check if we've finished parsing. 2573 if (Text.empty()) 2574 break; 2575 2576 // Otherwise, the end of an inner pipeline always has to be followed by 2577 // a comma, and then we can continue. 2578 if (!Text.consume_front(",")) 2579 return None; 2580 } 2581 2582 if (PipelineStack.size() > 1) 2583 // Unbalanced paretheses. 2584 return None; 2585 2586 assert(PipelineStack.back() == &ResultPipeline && 2587 "Wrong pipeline at the bottom of the stack!"); 2588 return {std::move(ResultPipeline)}; 2589 } 2590 2591 Error PassBuilder::parseModulePass(ModulePassManager &MPM, 2592 const PipelineElement &E) { 2593 auto &Name = E.Name; 2594 auto &InnerPipeline = E.InnerPipeline; 2595 2596 // First handle complex passes like the pass managers which carry pipelines. 2597 if (!InnerPipeline.empty()) { 2598 if (Name == "module") { 2599 ModulePassManager NestedMPM; 2600 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline)) 2601 return Err; 2602 MPM.addPass(std::move(NestedMPM)); 2603 return Error::success(); 2604 } 2605 if (Name == "cgscc") { 2606 CGSCCPassManager CGPM; 2607 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline)) 2608 return Err; 2609 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 2610 return Error::success(); 2611 } 2612 if (Name == "function") { 2613 FunctionPassManager FPM; 2614 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline)) 2615 return Err; 2616 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 2617 return Error::success(); 2618 } 2619 if (auto Count = parseRepeatPassName(Name)) { 2620 ModulePassManager NestedMPM; 2621 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline)) 2622 return Err; 2623 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM))); 2624 return Error::success(); 2625 } 2626 2627 for (auto &C : ModulePipelineParsingCallbacks) 2628 if (C(Name, MPM, InnerPipeline)) 2629 return Error::success(); 2630 2631 // Normal passes can't have pipelines. 2632 return make_error<StringError>( 2633 formatv("invalid use of '{0}' pass as module pipeline", Name).str(), 2634 inconvertibleErrorCode()); 2635 ; 2636 } 2637 2638 // Manually handle aliases for pre-configured pipeline fragments. 2639 if (startsWithDefaultPipelineAliasPrefix(Name)) { 2640 SmallVector<StringRef, 3> Matches; 2641 if (!DefaultAliasRegex.match(Name, &Matches)) 2642 return make_error<StringError>( 2643 formatv("unknown default pipeline alias '{0}'", Name).str(), 2644 inconvertibleErrorCode()); 2645 2646 assert(Matches.size() == 3 && "Must capture two matched strings!"); 2647 2648 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2]) 2649 .Case("O0", OptimizationLevel::O0) 2650 .Case("O1", OptimizationLevel::O1) 2651 .Case("O2", OptimizationLevel::O2) 2652 .Case("O3", OptimizationLevel::O3) 2653 .Case("Os", OptimizationLevel::Os) 2654 .Case("Oz", OptimizationLevel::Oz); 2655 if (L == OptimizationLevel::O0 && Matches[1] != "thinlto" && 2656 Matches[1] != "lto") { 2657 MPM.addPass(buildO0DefaultPipeline(L, Matches[1] == "thinlto-pre-link" || 2658 Matches[1] == "lto-pre-link")); 2659 return Error::success(); 2660 } 2661 2662 // This is consistent with old pass manager invoked via opt, but 2663 // inconsistent with clang. Clang doesn't enable loop vectorization 2664 // but does enable slp vectorization at Oz. 2665 PTO.LoopVectorization = 2666 L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz; 2667 PTO.SLPVectorization = 2668 L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz; 2669 2670 if (Matches[1] == "default") { 2671 MPM.addPass(buildPerModuleDefaultPipeline(L)); 2672 } else if (Matches[1] == "thinlto-pre-link") { 2673 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L)); 2674 } else if (Matches[1] == "thinlto") { 2675 MPM.addPass(buildThinLTODefaultPipeline(L, nullptr)); 2676 } else if (Matches[1] == "lto-pre-link") { 2677 MPM.addPass(buildLTOPreLinkDefaultPipeline(L)); 2678 } else { 2679 assert(Matches[1] == "lto" && "Not one of the matched options!"); 2680 MPM.addPass(buildLTODefaultPipeline(L, nullptr)); 2681 } 2682 return Error::success(); 2683 } 2684 2685 // Finally expand the basic registered passes from the .inc file. 2686 #define MODULE_PASS(NAME, CREATE_PASS) \ 2687 if (Name == NAME) { \ 2688 MPM.addPass(CREATE_PASS); \ 2689 return Error::success(); \ 2690 } 2691 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 2692 if (checkParametrizedPassName(Name, NAME)) { \ 2693 auto Params = parsePassParameters(PARSER, Name, NAME); \ 2694 if (!Params) \ 2695 return Params.takeError(); \ 2696 MPM.addPass(CREATE_PASS(Params.get())); \ 2697 return Error::success(); \ 2698 } 2699 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 2700 if (Name == "require<" NAME ">") { \ 2701 MPM.addPass( \ 2702 RequireAnalysisPass< \ 2703 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \ 2704 return Error::success(); \ 2705 } \ 2706 if (Name == "invalidate<" NAME ">") { \ 2707 MPM.addPass(InvalidateAnalysisPass< \ 2708 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 2709 return Error::success(); \ 2710 } 2711 #define CGSCC_PASS(NAME, CREATE_PASS) \ 2712 if (Name == NAME) { \ 2713 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS)); \ 2714 return Error::success(); \ 2715 } 2716 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 2717 if (Name == NAME) { \ 2718 MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS)); \ 2719 return Error::success(); \ 2720 } 2721 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 2722 if (checkParametrizedPassName(Name, NAME)) { \ 2723 auto Params = parsePassParameters(PARSER, Name, NAME); \ 2724 if (!Params) \ 2725 return Params.takeError(); \ 2726 MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \ 2727 return Error::success(); \ 2728 } 2729 #define LOOP_PASS(NAME, CREATE_PASS) \ 2730 if (Name == NAME) { \ 2731 MPM.addPass(createModuleToFunctionPassAdaptor( \ 2732 createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \ 2733 return Error::success(); \ 2734 } 2735 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 2736 if (checkParametrizedPassName(Name, NAME)) { \ 2737 auto Params = parsePassParameters(PARSER, Name, NAME); \ 2738 if (!Params) \ 2739 return Params.takeError(); \ 2740 MPM.addPass( \ 2741 createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor( \ 2742 CREATE_PASS(Params.get()), false, false))); \ 2743 return Error::success(); \ 2744 } 2745 #include "PassRegistry.def" 2746 2747 for (auto &C : ModulePipelineParsingCallbacks) 2748 if (C(Name, MPM, InnerPipeline)) 2749 return Error::success(); 2750 return make_error<StringError>( 2751 formatv("unknown module pass '{0}'", Name).str(), 2752 inconvertibleErrorCode()); 2753 } 2754 2755 Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM, 2756 const PipelineElement &E) { 2757 auto &Name = E.Name; 2758 auto &InnerPipeline = E.InnerPipeline; 2759 2760 // First handle complex passes like the pass managers which carry pipelines. 2761 if (!InnerPipeline.empty()) { 2762 if (Name == "cgscc") { 2763 CGSCCPassManager NestedCGPM; 2764 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline)) 2765 return Err; 2766 // Add the nested pass manager with the appropriate adaptor. 2767 CGPM.addPass(std::move(NestedCGPM)); 2768 return Error::success(); 2769 } 2770 if (Name == "function") { 2771 FunctionPassManager FPM; 2772 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline)) 2773 return Err; 2774 // Add the nested pass manager with the appropriate adaptor. 2775 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM))); 2776 return Error::success(); 2777 } 2778 if (auto Count = parseRepeatPassName(Name)) { 2779 CGSCCPassManager NestedCGPM; 2780 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline)) 2781 return Err; 2782 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM))); 2783 return Error::success(); 2784 } 2785 if (auto MaxRepetitions = parseDevirtPassName(Name)) { 2786 CGSCCPassManager NestedCGPM; 2787 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline)) 2788 return Err; 2789 CGPM.addPass( 2790 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions)); 2791 return Error::success(); 2792 } 2793 2794 for (auto &C : CGSCCPipelineParsingCallbacks) 2795 if (C(Name, CGPM, InnerPipeline)) 2796 return Error::success(); 2797 2798 // Normal passes can't have pipelines. 2799 return make_error<StringError>( 2800 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(), 2801 inconvertibleErrorCode()); 2802 } 2803 2804 // Now expand the basic registered passes from the .inc file. 2805 #define CGSCC_PASS(NAME, CREATE_PASS) \ 2806 if (Name == NAME) { \ 2807 CGPM.addPass(CREATE_PASS); \ 2808 return Error::success(); \ 2809 } 2810 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 2811 if (Name == "require<" NAME ">") { \ 2812 CGPM.addPass(RequireAnalysisPass< \ 2813 std::remove_reference<decltype(CREATE_PASS)>::type, \ 2814 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \ 2815 CGSCCUpdateResult &>()); \ 2816 return Error::success(); \ 2817 } \ 2818 if (Name == "invalidate<" NAME ">") { \ 2819 CGPM.addPass(InvalidateAnalysisPass< \ 2820 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 2821 return Error::success(); \ 2822 } 2823 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 2824 if (Name == NAME) { \ 2825 CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS)); \ 2826 return Error::success(); \ 2827 } 2828 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 2829 if (checkParametrizedPassName(Name, NAME)) { \ 2830 auto Params = parsePassParameters(PARSER, Name, NAME); \ 2831 if (!Params) \ 2832 return Params.takeError(); \ 2833 CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \ 2834 return Error::success(); \ 2835 } 2836 #define LOOP_PASS(NAME, CREATE_PASS) \ 2837 if (Name == NAME) { \ 2838 CGPM.addPass(createCGSCCToFunctionPassAdaptor( \ 2839 createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \ 2840 return Error::success(); \ 2841 } 2842 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 2843 if (checkParametrizedPassName(Name, NAME)) { \ 2844 auto Params = parsePassParameters(PARSER, Name, NAME); \ 2845 if (!Params) \ 2846 return Params.takeError(); \ 2847 CGPM.addPass( \ 2848 createCGSCCToFunctionPassAdaptor(createFunctionToLoopPassAdaptor( \ 2849 CREATE_PASS(Params.get()), false, false))); \ 2850 return Error::success(); \ 2851 } 2852 #include "PassRegistry.def" 2853 2854 for (auto &C : CGSCCPipelineParsingCallbacks) 2855 if (C(Name, CGPM, InnerPipeline)) 2856 return Error::success(); 2857 return make_error<StringError>( 2858 formatv("unknown cgscc pass '{0}'", Name).str(), 2859 inconvertibleErrorCode()); 2860 } 2861 2862 Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM, 2863 const PipelineElement &E) { 2864 auto &Name = E.Name; 2865 auto &InnerPipeline = E.InnerPipeline; 2866 2867 // First handle complex passes like the pass managers which carry pipelines. 2868 if (!InnerPipeline.empty()) { 2869 if (Name == "function") { 2870 FunctionPassManager NestedFPM; 2871 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline)) 2872 return Err; 2873 // Add the nested pass manager with the appropriate adaptor. 2874 FPM.addPass(std::move(NestedFPM)); 2875 return Error::success(); 2876 } 2877 if (Name == "loop" || Name == "loop-mssa") { 2878 LoopPassManager LPM; 2879 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline)) 2880 return Err; 2881 // Add the nested pass manager with the appropriate adaptor. 2882 bool UseMemorySSA = (Name == "loop-mssa"); 2883 bool UseBFI = llvm::any_of( 2884 InnerPipeline, [](auto Pipeline) { return Pipeline.Name == "licm"; }); 2885 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA, 2886 UseBFI)); 2887 return Error::success(); 2888 } 2889 if (auto Count = parseRepeatPassName(Name)) { 2890 FunctionPassManager NestedFPM; 2891 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline)) 2892 return Err; 2893 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM))); 2894 return Error::success(); 2895 } 2896 2897 for (auto &C : FunctionPipelineParsingCallbacks) 2898 if (C(Name, FPM, InnerPipeline)) 2899 return Error::success(); 2900 2901 // Normal passes can't have pipelines. 2902 return make_error<StringError>( 2903 formatv("invalid use of '{0}' pass as function pipeline", Name).str(), 2904 inconvertibleErrorCode()); 2905 } 2906 2907 // Now expand the basic registered passes from the .inc file. 2908 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 2909 if (Name == NAME) { \ 2910 FPM.addPass(CREATE_PASS); \ 2911 return Error::success(); \ 2912 } 2913 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 2914 if (checkParametrizedPassName(Name, NAME)) { \ 2915 auto Params = parsePassParameters(PARSER, Name, NAME); \ 2916 if (!Params) \ 2917 return Params.takeError(); \ 2918 FPM.addPass(CREATE_PASS(Params.get())); \ 2919 return Error::success(); \ 2920 } 2921 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 2922 if (Name == "require<" NAME ">") { \ 2923 FPM.addPass( \ 2924 RequireAnalysisPass< \ 2925 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \ 2926 return Error::success(); \ 2927 } \ 2928 if (Name == "invalidate<" NAME ">") { \ 2929 FPM.addPass(InvalidateAnalysisPass< \ 2930 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 2931 return Error::success(); \ 2932 } 2933 // FIXME: UseMemorySSA is set to false. Maybe we could do things like: 2934 // bool UseMemorySSA = !("canon-freeze" || "loop-predication" || 2935 // "guard-widening"); 2936 // The risk is that it may become obsolete if we're not careful. 2937 #define LOOP_PASS(NAME, CREATE_PASS) \ 2938 if (Name == NAME) { \ 2939 FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)); \ 2940 return Error::success(); \ 2941 } 2942 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 2943 if (checkParametrizedPassName(Name, NAME)) { \ 2944 auto Params = parsePassParameters(PARSER, Name, NAME); \ 2945 if (!Params) \ 2946 return Params.takeError(); \ 2947 FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS(Params.get()), \ 2948 false, false)); \ 2949 return Error::success(); \ 2950 } 2951 #include "PassRegistry.def" 2952 2953 for (auto &C : FunctionPipelineParsingCallbacks) 2954 if (C(Name, FPM, InnerPipeline)) 2955 return Error::success(); 2956 return make_error<StringError>( 2957 formatv("unknown function pass '{0}'", Name).str(), 2958 inconvertibleErrorCode()); 2959 } 2960 2961 Error PassBuilder::parseLoopPass(LoopPassManager &LPM, 2962 const PipelineElement &E) { 2963 StringRef Name = E.Name; 2964 auto &InnerPipeline = E.InnerPipeline; 2965 2966 // First handle complex passes like the pass managers which carry pipelines. 2967 if (!InnerPipeline.empty()) { 2968 if (Name == "loop") { 2969 LoopPassManager NestedLPM; 2970 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline)) 2971 return Err; 2972 // Add the nested pass manager with the appropriate adaptor. 2973 LPM.addPass(std::move(NestedLPM)); 2974 return Error::success(); 2975 } 2976 if (auto Count = parseRepeatPassName(Name)) { 2977 LoopPassManager NestedLPM; 2978 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline)) 2979 return Err; 2980 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM))); 2981 return Error::success(); 2982 } 2983 2984 for (auto &C : LoopPipelineParsingCallbacks) 2985 if (C(Name, LPM, InnerPipeline)) 2986 return Error::success(); 2987 2988 // Normal passes can't have pipelines. 2989 return make_error<StringError>( 2990 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(), 2991 inconvertibleErrorCode()); 2992 } 2993 2994 // Now expand the basic registered passes from the .inc file. 2995 #define LOOP_PASS(NAME, CREATE_PASS) \ 2996 if (Name == NAME) { \ 2997 LPM.addPass(CREATE_PASS); \ 2998 return Error::success(); \ 2999 } 3000 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 3001 if (checkParametrizedPassName(Name, NAME)) { \ 3002 auto Params = parsePassParameters(PARSER, Name, NAME); \ 3003 if (!Params) \ 3004 return Params.takeError(); \ 3005 LPM.addPass(CREATE_PASS(Params.get())); \ 3006 return Error::success(); \ 3007 } 3008 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 3009 if (Name == "require<" NAME ">") { \ 3010 LPM.addPass(RequireAnalysisPass< \ 3011 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \ 3012 LoopAnalysisManager, LoopStandardAnalysisResults &, \ 3013 LPMUpdater &>()); \ 3014 return Error::success(); \ 3015 } \ 3016 if (Name == "invalidate<" NAME ">") { \ 3017 LPM.addPass(InvalidateAnalysisPass< \ 3018 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 3019 return Error::success(); \ 3020 } 3021 #include "PassRegistry.def" 3022 3023 for (auto &C : LoopPipelineParsingCallbacks) 3024 if (C(Name, LPM, InnerPipeline)) 3025 return Error::success(); 3026 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(), 3027 inconvertibleErrorCode()); 3028 } 3029 3030 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) { 3031 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 3032 if (Name == NAME) { \ 3033 AA.registerModuleAnalysis< \ 3034 std::remove_reference<decltype(CREATE_PASS)>::type>(); \ 3035 return true; \ 3036 } 3037 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 3038 if (Name == NAME) { \ 3039 AA.registerFunctionAnalysis< \ 3040 std::remove_reference<decltype(CREATE_PASS)>::type>(); \ 3041 return true; \ 3042 } 3043 #include "PassRegistry.def" 3044 3045 for (auto &C : AAParsingCallbacks) 3046 if (C(Name, AA)) 3047 return true; 3048 return false; 3049 } 3050 3051 Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM, 3052 ArrayRef<PipelineElement> Pipeline) { 3053 for (const auto &Element : Pipeline) { 3054 if (auto Err = parseLoopPass(LPM, Element)) 3055 return Err; 3056 } 3057 return Error::success(); 3058 } 3059 3060 Error PassBuilder::parseFunctionPassPipeline( 3061 FunctionPassManager &FPM, ArrayRef<PipelineElement> Pipeline) { 3062 for (const auto &Element : Pipeline) { 3063 if (auto Err = parseFunctionPass(FPM, Element)) 3064 return Err; 3065 } 3066 return Error::success(); 3067 } 3068 3069 Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM, 3070 ArrayRef<PipelineElement> Pipeline) { 3071 for (const auto &Element : Pipeline) { 3072 if (auto Err = parseCGSCCPass(CGPM, Element)) 3073 return Err; 3074 } 3075 return Error::success(); 3076 } 3077 3078 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM, 3079 FunctionAnalysisManager &FAM, 3080 CGSCCAnalysisManager &CGAM, 3081 ModuleAnalysisManager &MAM) { 3082 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); }); 3083 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); }); 3084 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); }); 3085 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); }); 3086 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); }); 3087 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); }); 3088 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); }); 3089 } 3090 3091 Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM, 3092 ArrayRef<PipelineElement> Pipeline) { 3093 for (const auto &Element : Pipeline) { 3094 if (auto Err = parseModulePass(MPM, Element)) 3095 return Err; 3096 } 3097 return Error::success(); 3098 } 3099 3100 // Primary pass pipeline description parsing routine for a \c ModulePassManager 3101 // FIXME: Should this routine accept a TargetMachine or require the caller to 3102 // pre-populate the analysis managers with target-specific stuff? 3103 Error PassBuilder::parsePassPipeline(ModulePassManager &MPM, 3104 StringRef PipelineText) { 3105 auto Pipeline = parsePipelineText(PipelineText); 3106 if (!Pipeline || Pipeline->empty()) 3107 return make_error<StringError>( 3108 formatv("invalid pipeline '{0}'", PipelineText).str(), 3109 inconvertibleErrorCode()); 3110 3111 // If the first name isn't at the module layer, wrap the pipeline up 3112 // automatically. 3113 StringRef FirstName = Pipeline->front().Name; 3114 3115 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) { 3116 bool UseMemorySSA; 3117 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) { 3118 Pipeline = {{"cgscc", std::move(*Pipeline)}}; 3119 } else if (isFunctionPassName(FirstName, 3120 FunctionPipelineParsingCallbacks)) { 3121 Pipeline = {{"function", std::move(*Pipeline)}}; 3122 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks, 3123 UseMemorySSA)) { 3124 Pipeline = {{"function", {{UseMemorySSA ? "loop-mssa" : "loop", 3125 std::move(*Pipeline)}}}}; 3126 } else { 3127 for (auto &C : TopLevelPipelineParsingCallbacks) 3128 if (C(MPM, *Pipeline)) 3129 return Error::success(); 3130 3131 // Unknown pass or pipeline name! 3132 auto &InnerPipeline = Pipeline->front().InnerPipeline; 3133 return make_error<StringError>( 3134 formatv("unknown {0} name '{1}'", 3135 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName) 3136 .str(), 3137 inconvertibleErrorCode()); 3138 } 3139 } 3140 3141 if (auto Err = parseModulePassPipeline(MPM, *Pipeline)) 3142 return Err; 3143 return Error::success(); 3144 } 3145 3146 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager 3147 Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM, 3148 StringRef PipelineText) { 3149 auto Pipeline = parsePipelineText(PipelineText); 3150 if (!Pipeline || Pipeline->empty()) 3151 return make_error<StringError>( 3152 formatv("invalid pipeline '{0}'", PipelineText).str(), 3153 inconvertibleErrorCode()); 3154 3155 StringRef FirstName = Pipeline->front().Name; 3156 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) 3157 return make_error<StringError>( 3158 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName, 3159 PipelineText) 3160 .str(), 3161 inconvertibleErrorCode()); 3162 3163 if (auto Err = parseCGSCCPassPipeline(CGPM, *Pipeline)) 3164 return Err; 3165 return Error::success(); 3166 } 3167 3168 // Primary pass pipeline description parsing routine for a \c 3169 // FunctionPassManager 3170 Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM, 3171 StringRef PipelineText) { 3172 auto Pipeline = parsePipelineText(PipelineText); 3173 if (!Pipeline || Pipeline->empty()) 3174 return make_error<StringError>( 3175 formatv("invalid pipeline '{0}'", PipelineText).str(), 3176 inconvertibleErrorCode()); 3177 3178 StringRef FirstName = Pipeline->front().Name; 3179 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks)) 3180 return make_error<StringError>( 3181 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName, 3182 PipelineText) 3183 .str(), 3184 inconvertibleErrorCode()); 3185 3186 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline)) 3187 return Err; 3188 return Error::success(); 3189 } 3190 3191 // Primary pass pipeline description parsing routine for a \c LoopPassManager 3192 Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM, 3193 StringRef PipelineText) { 3194 auto Pipeline = parsePipelineText(PipelineText); 3195 if (!Pipeline || Pipeline->empty()) 3196 return make_error<StringError>( 3197 formatv("invalid pipeline '{0}'", PipelineText).str(), 3198 inconvertibleErrorCode()); 3199 3200 if (auto Err = parseLoopPassPipeline(CGPM, *Pipeline)) 3201 return Err; 3202 3203 return Error::success(); 3204 } 3205 3206 Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) { 3207 // If the pipeline just consists of the word 'default' just replace the AA 3208 // manager with our default one. 3209 if (PipelineText == "default") { 3210 AA = buildDefaultAAPipeline(); 3211 return Error::success(); 3212 } 3213 3214 while (!PipelineText.empty()) { 3215 StringRef Name; 3216 std::tie(Name, PipelineText) = PipelineText.split(','); 3217 if (!parseAAPassName(AA, Name)) 3218 return make_error<StringError>( 3219 formatv("unknown alias analysis name '{0}'", Name).str(), 3220 inconvertibleErrorCode()); 3221 } 3222 3223 return Error::success(); 3224 } 3225 3226 bool PassBuilder::isAAPassName(StringRef PassName) { 3227 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 3228 if (PassName == NAME) \ 3229 return true; 3230 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 3231 if (PassName == NAME) \ 3232 return true; 3233 #include "PassRegistry.def" 3234 return false; 3235 } 3236 3237 bool PassBuilder::isAnalysisPassName(StringRef PassName) { 3238 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 3239 if (PassName == NAME) \ 3240 return true; 3241 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 3242 if (PassName == NAME) \ 3243 return true; 3244 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 3245 if (PassName == NAME) \ 3246 return true; 3247 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 3248 if (PassName == NAME) \ 3249 return true; 3250 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 3251 if (PassName == NAME) \ 3252 return true; 3253 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 3254 if (PassName == NAME) \ 3255 return true; 3256 #include "PassRegistry.def" 3257 return false; 3258 } 3259 3260 static void printPassName(StringRef PassName, raw_ostream &OS) { 3261 OS << " " << PassName << "\n"; 3262 } 3263 static void printPassName(StringRef PassName, StringRef Params, 3264 raw_ostream &OS) { 3265 OS << " " << PassName << "<" << Params << ">\n"; 3266 } 3267 3268 void PassBuilder::printPassNames(raw_ostream &OS) { 3269 // TODO: print pass descriptions when they are available 3270 3271 OS << "Module passes:\n"; 3272 #define MODULE_PASS(NAME, CREATE_PASS) printPassName(NAME, OS); 3273 #include "PassRegistry.def" 3274 3275 OS << "Module passes with params:\n"; 3276 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 3277 printPassName(NAME, PARAMS, OS); 3278 #include "PassRegistry.def" 3279 3280 OS << "Module analyses:\n"; 3281 #define MODULE_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS); 3282 #include "PassRegistry.def" 3283 3284 OS << "Module alias analyses:\n"; 3285 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS); 3286 #include "PassRegistry.def" 3287 3288 OS << "CGSCC passes:\n"; 3289 #define CGSCC_PASS(NAME, CREATE_PASS) printPassName(NAME, OS); 3290 #include "PassRegistry.def" 3291 3292 OS << "CGSCC analyses:\n"; 3293 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS); 3294 #include "PassRegistry.def" 3295 3296 OS << "Function passes:\n"; 3297 #define FUNCTION_PASS(NAME, CREATE_PASS) printPassName(NAME, OS); 3298 #include "PassRegistry.def" 3299 3300 OS << "Function passes with params:\n"; 3301 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 3302 printPassName(NAME, PARAMS, OS); 3303 #include "PassRegistry.def" 3304 3305 OS << "Function analyses:\n"; 3306 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS); 3307 #include "PassRegistry.def" 3308 3309 OS << "Function alias analyses:\n"; 3310 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS); 3311 #include "PassRegistry.def" 3312 3313 OS << "Loop passes:\n"; 3314 #define LOOP_PASS(NAME, CREATE_PASS) printPassName(NAME, OS); 3315 #include "PassRegistry.def" 3316 3317 OS << "Loop passes with params:\n"; 3318 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \ 3319 printPassName(NAME, PARAMS, OS); 3320 #include "PassRegistry.def" 3321 3322 OS << "Loop analyses:\n"; 3323 #define LOOP_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS); 3324 #include "PassRegistry.def" 3325 } 3326 3327 void PassBuilder::registerParseTopLevelPipelineCallback( 3328 const std::function<bool(ModulePassManager &, ArrayRef<PipelineElement>)> 3329 &C) { 3330 TopLevelPipelineParsingCallbacks.push_back(C); 3331 } 3332