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