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