PassBuilder.cpp 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. //===- Parsing and selection 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. #include "llvm/Passes/PassBuilder.h"
  17. #include "llvm/ADT/StringSwitch.h"
  18. #include "llvm/Analysis/AliasAnalysisEvaluator.h"
  19. #include "llvm/Analysis/AliasSetTracker.h"
  20. #include "llvm/Analysis/AssumptionCache.h"
  21. #include "llvm/Analysis/BasicAliasAnalysis.h"
  22. #include "llvm/Analysis/BlockFrequencyInfo.h"
  23. #include "llvm/Analysis/BranchProbabilityInfo.h"
  24. #include "llvm/Analysis/CFGPrinter.h"
  25. #include "llvm/Analysis/CFGSCCPrinter.h"
  26. #include "llvm/Analysis/CGSCCPassManager.h"
  27. #include "llvm/Analysis/CallGraph.h"
  28. #include "llvm/Analysis/CallPrinter.h"
  29. #include "llvm/Analysis/CostModel.h"
  30. #include "llvm/Analysis/CycleAnalysis.h"
  31. #include "llvm/Analysis/DDG.h"
  32. #include "llvm/Analysis/DDGPrinter.h"
  33. #include "llvm/Analysis/Delinearization.h"
  34. #include "llvm/Analysis/DemandedBits.h"
  35. #include "llvm/Analysis/DependenceAnalysis.h"
  36. #include "llvm/Analysis/DivergenceAnalysis.h"
  37. #include "llvm/Analysis/DomPrinter.h"
  38. #include "llvm/Analysis/DominanceFrontier.h"
  39. #include "llvm/Analysis/FunctionPropertiesAnalysis.h"
  40. #include "llvm/Analysis/GlobalsModRef.h"
  41. #include "llvm/Analysis/IRSimilarityIdentifier.h"
  42. #include "llvm/Analysis/IVUsers.h"
  43. #include "llvm/Analysis/InlineAdvisor.h"
  44. #include "llvm/Analysis/InlineSizeEstimatorAnalysis.h"
  45. #include "llvm/Analysis/InstCount.h"
  46. #include "llvm/Analysis/LazyCallGraph.h"
  47. #include "llvm/Analysis/LazyValueInfo.h"
  48. #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
  49. #include "llvm/Analysis/Lint.h"
  50. #include "llvm/Analysis/LoopAccessAnalysis.h"
  51. #include "llvm/Analysis/LoopCacheAnalysis.h"
  52. #include "llvm/Analysis/LoopInfo.h"
  53. #include "llvm/Analysis/LoopNestAnalysis.h"
  54. #include "llvm/Analysis/MemDerefPrinter.h"
  55. #include "llvm/Analysis/MemoryDependenceAnalysis.h"
  56. #include "llvm/Analysis/MemorySSA.h"
  57. #include "llvm/Analysis/ModuleDebugInfoPrinter.h"
  58. #include "llvm/Analysis/ModuleSummaryAnalysis.h"
  59. #include "llvm/Analysis/MustExecute.h"
  60. #include "llvm/Analysis/ObjCARCAliasAnalysis.h"
  61. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  62. #include "llvm/Analysis/PhiValues.h"
  63. #include "llvm/Analysis/PostDominators.h"
  64. #include "llvm/Analysis/ProfileSummaryInfo.h"
  65. #include "llvm/Analysis/RegionInfo.h"
  66. #include "llvm/Analysis/ScalarEvolution.h"
  67. #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
  68. #include "llvm/Analysis/ScopedNoAliasAA.h"
  69. #include "llvm/Analysis/StackLifetime.h"
  70. #include "llvm/Analysis/StackSafetyAnalysis.h"
  71. #include "llvm/Analysis/TargetLibraryInfo.h"
  72. #include "llvm/Analysis/TargetTransformInfo.h"
  73. #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
  74. #include "llvm/Analysis/UniformityAnalysis.h"
  75. #include "llvm/CodeGen/TypePromotion.h"
  76. #include "llvm/IR/DebugInfo.h"
  77. #include "llvm/IR/Dominators.h"
  78. #include "llvm/IR/PassManager.h"
  79. #include "llvm/IR/PrintPasses.h"
  80. #include "llvm/IR/SafepointIRVerifier.h"
  81. #include "llvm/IR/Verifier.h"
  82. #include "llvm/IRPrinter/IRPrintingPasses.h"
  83. #include "llvm/Support/CommandLine.h"
  84. #include "llvm/Support/Debug.h"
  85. #include "llvm/Support/ErrorHandling.h"
  86. #include "llvm/Support/FormatVariadic.h"
  87. #include "llvm/Support/Regex.h"
  88. #include "llvm/Target/TargetMachine.h"
  89. #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
  90. #include "llvm/Transforms/Coroutines/CoroCleanup.h"
  91. #include "llvm/Transforms/Coroutines/CoroConditionalWrapper.h"
  92. #include "llvm/Transforms/Coroutines/CoroEarly.h"
  93. #include "llvm/Transforms/Coroutines/CoroElide.h"
  94. #include "llvm/Transforms/Coroutines/CoroSplit.h"
  95. #include "llvm/Transforms/IPO/AlwaysInliner.h"
  96. #include "llvm/Transforms/IPO/Annotation2Metadata.h"
  97. #include "llvm/Transforms/IPO/ArgumentPromotion.h"
  98. #include "llvm/Transforms/IPO/Attributor.h"
  99. #include "llvm/Transforms/IPO/BlockExtractor.h"
  100. #include "llvm/Transforms/IPO/CalledValuePropagation.h"
  101. #include "llvm/Transforms/IPO/ConstantMerge.h"
  102. #include "llvm/Transforms/IPO/CrossDSOCFI.h"
  103. #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
  104. #include "llvm/Transforms/IPO/ElimAvailExtern.h"
  105. #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
  106. #include "llvm/Transforms/IPO/FunctionAttrs.h"
  107. #include "llvm/Transforms/IPO/FunctionImport.h"
  108. #include "llvm/Transforms/IPO/GlobalDCE.h"
  109. #include "llvm/Transforms/IPO/GlobalOpt.h"
  110. #include "llvm/Transforms/IPO/GlobalSplit.h"
  111. #include "llvm/Transforms/IPO/HotColdSplitting.h"
  112. #include "llvm/Transforms/IPO/IROutliner.h"
  113. #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
  114. #include "llvm/Transforms/IPO/Inliner.h"
  115. #include "llvm/Transforms/IPO/Internalize.h"
  116. #include "llvm/Transforms/IPO/LoopExtractor.h"
  117. #include "llvm/Transforms/IPO/LowerTypeTests.h"
  118. #include "llvm/Transforms/IPO/MergeFunctions.h"
  119. #include "llvm/Transforms/IPO/ModuleInliner.h"
  120. #include "llvm/Transforms/IPO/OpenMPOpt.h"
  121. #include "llvm/Transforms/IPO/PartialInlining.h"
  122. #include "llvm/Transforms/IPO/SCCP.h"
  123. #include "llvm/Transforms/IPO/SampleProfile.h"
  124. #include "llvm/Transforms/IPO/SampleProfileProbe.h"
  125. #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
  126. #include "llvm/Transforms/IPO/StripSymbols.h"
  127. #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
  128. #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
  129. #include "llvm/Transforms/InstCombine/InstCombine.h"
  130. #include "llvm/Transforms/Instrumentation.h"
  131. #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
  132. #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
  133. #include "llvm/Transforms/Instrumentation/CGProfile.h"
  134. #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
  135. #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
  136. #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
  137. #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
  138. #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
  139. #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
  140. #include "llvm/Transforms/Instrumentation/KCFI.h"
  141. #include "llvm/Transforms/Instrumentation/MemProfiler.h"
  142. #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
  143. #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
  144. #include "llvm/Transforms/Instrumentation/PoisonChecking.h"
  145. #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
  146. #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
  147. #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
  148. #include "llvm/Transforms/ObjCARC.h"
  149. #include "llvm/Transforms/Scalar/ADCE.h"
  150. #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
  151. #include "llvm/Transforms/Scalar/AnnotationRemarks.h"
  152. #include "llvm/Transforms/Scalar/BDCE.h"
  153. #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
  154. #include "llvm/Transforms/Scalar/ConstantHoisting.h"
  155. #include "llvm/Transforms/Scalar/ConstraintElimination.h"
  156. #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
  157. #include "llvm/Transforms/Scalar/DCE.h"
  158. #include "llvm/Transforms/Scalar/DFAJumpThreading.h"
  159. #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
  160. #include "llvm/Transforms/Scalar/DivRemPairs.h"
  161. #include "llvm/Transforms/Scalar/EarlyCSE.h"
  162. #include "llvm/Transforms/Scalar/FlattenCFG.h"
  163. #include "llvm/Transforms/Scalar/Float2Int.h"
  164. #include "llvm/Transforms/Scalar/GVN.h"
  165. #include "llvm/Transforms/Scalar/GuardWidening.h"
  166. #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
  167. #include "llvm/Transforms/Scalar/IndVarSimplify.h"
  168. #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
  169. #include "llvm/Transforms/Scalar/InferAddressSpaces.h"
  170. #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
  171. #include "llvm/Transforms/Scalar/JumpThreading.h"
  172. #include "llvm/Transforms/Scalar/LICM.h"
  173. #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
  174. #include "llvm/Transforms/Scalar/LoopBoundSplit.h"
  175. #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
  176. #include "llvm/Transforms/Scalar/LoopDeletion.h"
  177. #include "llvm/Transforms/Scalar/LoopDistribute.h"
  178. #include "llvm/Transforms/Scalar/LoopFlatten.h"
  179. #include "llvm/Transforms/Scalar/LoopFuse.h"
  180. #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
  181. #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
  182. #include "llvm/Transforms/Scalar/LoopInterchange.h"
  183. #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
  184. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  185. #include "llvm/Transforms/Scalar/LoopPredication.h"
  186. #include "llvm/Transforms/Scalar/LoopReroll.h"
  187. #include "llvm/Transforms/Scalar/LoopRotation.h"
  188. #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
  189. #include "llvm/Transforms/Scalar/LoopSink.h"
  190. #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
  191. #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
  192. #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
  193. #include "llvm/Transforms/Scalar/LoopVersioningLICM.h"
  194. #include "llvm/Transforms/Scalar/LowerAtomicPass.h"
  195. #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
  196. #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
  197. #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
  198. #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
  199. #include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
  200. #include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
  201. #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
  202. #include "llvm/Transforms/Scalar/MergeICmps.h"
  203. #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
  204. #include "llvm/Transforms/Scalar/NaryReassociate.h"
  205. #include "llvm/Transforms/Scalar/NewGVN.h"
  206. #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
  207. #include "llvm/Transforms/Scalar/Reassociate.h"
  208. #include "llvm/Transforms/Scalar/Reg2Mem.h"
  209. #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
  210. #include "llvm/Transforms/Scalar/SCCP.h"
  211. #include "llvm/Transforms/Scalar/SROA.h"
  212. #include "llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h"
  213. #include "llvm/Transforms/Scalar/Scalarizer.h"
  214. #include "llvm/Transforms/Scalar/SeparateConstOffsetFromGEP.h"
  215. #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
  216. #include "llvm/Transforms/Scalar/SimplifyCFG.h"
  217. #include "llvm/Transforms/Scalar/Sink.h"
  218. #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
  219. #include "llvm/Transforms/Scalar/StraightLineStrengthReduce.h"
  220. #include "llvm/Transforms/Scalar/StructurizeCFG.h"
  221. #include "llvm/Transforms/Scalar/TLSVariableHoist.h"
  222. #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
  223. #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
  224. #include "llvm/Transforms/Utils/AddDiscriminators.h"
  225. #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
  226. #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
  227. #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
  228. #include "llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h"
  229. #include "llvm/Transforms/Utils/Debugify.h"
  230. #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
  231. #include "llvm/Transforms/Utils/FixIrreducible.h"
  232. #include "llvm/Transforms/Utils/HelloWorld.h"
  233. #include "llvm/Transforms/Utils/InjectTLIMappings.h"
  234. #include "llvm/Transforms/Utils/InstructionNamer.h"
  235. #include "llvm/Transforms/Utils/LCSSA.h"
  236. #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
  237. #include "llvm/Transforms/Utils/LoopSimplify.h"
  238. #include "llvm/Transforms/Utils/LoopVersioning.h"
  239. #include "llvm/Transforms/Utils/LowerGlobalDtors.h"
  240. #include "llvm/Transforms/Utils/LowerIFunc.h"
  241. #include "llvm/Transforms/Utils/LowerInvoke.h"
  242. #include "llvm/Transforms/Utils/LowerSwitch.h"
  243. #include "llvm/Transforms/Utils/Mem2Reg.h"
  244. #include "llvm/Transforms/Utils/MetaRenamer.h"
  245. #include "llvm/Transforms/Utils/NameAnonGlobals.h"
  246. #include "llvm/Transforms/Utils/PredicateInfo.h"
  247. #include "llvm/Transforms/Utils/RelLookupTableConverter.h"
  248. #include "llvm/Transforms/Utils/StripGCRelocates.h"
  249. #include "llvm/Transforms/Utils/StripNonLineTableDebugInfo.h"
  250. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  251. #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
  252. #include "llvm/Transforms/Utils/UnifyLoopExits.h"
  253. #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
  254. #include "llvm/Transforms/Vectorize/LoopVectorize.h"
  255. #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
  256. #include "llvm/Transforms/Vectorize/VectorCombine.h"
  257. #include <optional>
  258. using namespace llvm;
  259. static const Regex DefaultAliasRegex(
  260. "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
  261. namespace llvm {
  262. cl::opt<bool> PrintPipelinePasses(
  263. "print-pipeline-passes",
  264. cl::desc("Print a '-passes' compatible string describing the pipeline "
  265. "(best-effort only)."));
  266. } // namespace llvm
  267. namespace {
  268. // The following passes/analyses have custom names, otherwise their name will
  269. // include `(anonymous namespace)`. These are special since they are only for
  270. // testing purposes and don't live in a header file.
  271. /// No-op module pass which does nothing.
  272. struct NoOpModulePass : PassInfoMixin<NoOpModulePass> {
  273. PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
  274. return PreservedAnalyses::all();
  275. }
  276. static StringRef name() { return "NoOpModulePass"; }
  277. };
  278. /// No-op module analysis.
  279. class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
  280. friend AnalysisInfoMixin<NoOpModuleAnalysis>;
  281. static AnalysisKey Key;
  282. public:
  283. struct Result {};
  284. Result run(Module &, ModuleAnalysisManager &) { return Result(); }
  285. static StringRef name() { return "NoOpModuleAnalysis"; }
  286. };
  287. /// No-op CGSCC pass which does nothing.
  288. struct NoOpCGSCCPass : PassInfoMixin<NoOpCGSCCPass> {
  289. PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
  290. LazyCallGraph &, CGSCCUpdateResult &UR) {
  291. return PreservedAnalyses::all();
  292. }
  293. static StringRef name() { return "NoOpCGSCCPass"; }
  294. };
  295. /// No-op CGSCC analysis.
  296. class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
  297. friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
  298. static AnalysisKey Key;
  299. public:
  300. struct Result {};
  301. Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
  302. return Result();
  303. }
  304. static StringRef name() { return "NoOpCGSCCAnalysis"; }
  305. };
  306. /// No-op function pass which does nothing.
  307. struct NoOpFunctionPass : PassInfoMixin<NoOpFunctionPass> {
  308. PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
  309. return PreservedAnalyses::all();
  310. }
  311. static StringRef name() { return "NoOpFunctionPass"; }
  312. };
  313. /// No-op function analysis.
  314. class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
  315. friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
  316. static AnalysisKey Key;
  317. public:
  318. struct Result {};
  319. Result run(Function &, FunctionAnalysisManager &) { return Result(); }
  320. static StringRef name() { return "NoOpFunctionAnalysis"; }
  321. };
  322. /// No-op loop nest pass which does nothing.
  323. struct NoOpLoopNestPass : PassInfoMixin<NoOpLoopNestPass> {
  324. PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &,
  325. LoopStandardAnalysisResults &, LPMUpdater &) {
  326. return PreservedAnalyses::all();
  327. }
  328. static StringRef name() { return "NoOpLoopNestPass"; }
  329. };
  330. /// No-op loop pass which does nothing.
  331. struct NoOpLoopPass : PassInfoMixin<NoOpLoopPass> {
  332. PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
  333. LoopStandardAnalysisResults &, LPMUpdater &) {
  334. return PreservedAnalyses::all();
  335. }
  336. static StringRef name() { return "NoOpLoopPass"; }
  337. };
  338. /// No-op loop analysis.
  339. class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
  340. friend AnalysisInfoMixin<NoOpLoopAnalysis>;
  341. static AnalysisKey Key;
  342. public:
  343. struct Result {};
  344. Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
  345. return Result();
  346. }
  347. static StringRef name() { return "NoOpLoopAnalysis"; }
  348. };
  349. AnalysisKey NoOpModuleAnalysis::Key;
  350. AnalysisKey NoOpCGSCCAnalysis::Key;
  351. AnalysisKey NoOpFunctionAnalysis::Key;
  352. AnalysisKey NoOpLoopAnalysis::Key;
  353. /// Whether or not we should populate a PassInstrumentationCallbacks's class to
  354. /// pass name map.
  355. ///
  356. /// This is for optimization purposes so we don't populate it if we never use
  357. /// it. This should be updated if new pass instrumentation wants to use the map.
  358. /// We currently only use this for --print-before/after.
  359. bool shouldPopulateClassToPassNames() {
  360. return PrintPipelinePasses || !printBeforePasses().empty() ||
  361. !printAfterPasses().empty() || !isFilterPassesEmpty();
  362. }
  363. // A pass for testing -print-on-crash.
  364. // DO NOT USE THIS EXCEPT FOR TESTING!
  365. class TriggerCrashPass : public PassInfoMixin<TriggerCrashPass> {
  366. public:
  367. PreservedAnalyses run(Module &, ModuleAnalysisManager &) {
  368. abort();
  369. return PreservedAnalyses::all();
  370. }
  371. static StringRef name() { return "TriggerCrashPass"; }
  372. };
  373. } // namespace
  374. PassBuilder::PassBuilder(TargetMachine *TM, PipelineTuningOptions PTO,
  375. std::optional<PGOOptions> PGOOpt,
  376. PassInstrumentationCallbacks *PIC)
  377. : TM(TM), PTO(PTO), PGOOpt(PGOOpt), PIC(PIC) {
  378. if (TM)
  379. TM->registerPassBuilderCallbacks(*this);
  380. if (PIC && shouldPopulateClassToPassNames()) {
  381. #define MODULE_PASS(NAME, CREATE_PASS) \
  382. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  383. #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  384. PIC->addClassToPassName(CLASS, NAME);
  385. #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
  386. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  387. #define FUNCTION_PASS(NAME, CREATE_PASS) \
  388. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  389. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  390. PIC->addClassToPassName(CLASS, NAME);
  391. #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
  392. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  393. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  394. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  395. #define LOOP_PASS(NAME, CREATE_PASS) \
  396. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  397. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  398. PIC->addClassToPassName(CLASS, NAME);
  399. #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
  400. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  401. #define CGSCC_PASS(NAME, CREATE_PASS) \
  402. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  403. #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  404. PIC->addClassToPassName(CLASS, NAME);
  405. #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
  406. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  407. #include "PassRegistry.def"
  408. }
  409. }
  410. void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
  411. #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
  412. MAM.registerPass([&] { return CREATE_PASS; });
  413. #include "PassRegistry.def"
  414. for (auto &C : ModuleAnalysisRegistrationCallbacks)
  415. C(MAM);
  416. }
  417. void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
  418. #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
  419. CGAM.registerPass([&] { return CREATE_PASS; });
  420. #include "PassRegistry.def"
  421. for (auto &C : CGSCCAnalysisRegistrationCallbacks)
  422. C(CGAM);
  423. }
  424. void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
  425. // We almost always want the default alias analysis pipeline.
  426. // If a user wants a different one, they can register their own before calling
  427. // registerFunctionAnalyses().
  428. FAM.registerPass([&] { return buildDefaultAAPipeline(); });
  429. #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
  430. FAM.registerPass([&] { return CREATE_PASS; });
  431. #include "PassRegistry.def"
  432. for (auto &C : FunctionAnalysisRegistrationCallbacks)
  433. C(FAM);
  434. }
  435. void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
  436. #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
  437. LAM.registerPass([&] { return CREATE_PASS; });
  438. #include "PassRegistry.def"
  439. for (auto &C : LoopAnalysisRegistrationCallbacks)
  440. C(LAM);
  441. }
  442. static std::optional<int> parseRepeatPassName(StringRef Name) {
  443. if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
  444. return std::nullopt;
  445. int Count;
  446. if (Name.getAsInteger(0, Count) || Count <= 0)
  447. return std::nullopt;
  448. return Count;
  449. }
  450. static std::optional<int> parseDevirtPassName(StringRef Name) {
  451. if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
  452. return std::nullopt;
  453. int Count;
  454. if (Name.getAsInteger(0, Count) || Count < 0)
  455. return std::nullopt;
  456. return Count;
  457. }
  458. static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
  459. if (!Name.consume_front(PassName))
  460. return false;
  461. // normal pass name w/o parameters == default parameters
  462. if (Name.empty())
  463. return true;
  464. return Name.startswith("<") && Name.endswith(">");
  465. }
  466. namespace {
  467. /// This performs customized parsing of pass name with parameters.
  468. ///
  469. /// We do not need parametrization of passes in textual pipeline very often,
  470. /// yet on a rare occasion ability to specify parameters right there can be
  471. /// useful.
  472. ///
  473. /// \p Name - parameterized specification of a pass from a textual pipeline
  474. /// is a string in a form of :
  475. /// PassName '<' parameter-list '>'
  476. ///
  477. /// Parameter list is being parsed by the parser callable argument, \p Parser,
  478. /// It takes a string-ref of parameters and returns either StringError or a
  479. /// parameter list in a form of a custom parameters type, all wrapped into
  480. /// Expected<> template class.
  481. ///
  482. template <typename ParametersParseCallableT>
  483. auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
  484. StringRef PassName) -> decltype(Parser(StringRef{})) {
  485. using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
  486. StringRef Params = Name;
  487. if (!Params.consume_front(PassName)) {
  488. assert(false &&
  489. "unable to strip pass name from parametrized pass specification");
  490. }
  491. if (!Params.empty() &&
  492. (!Params.consume_front("<") || !Params.consume_back(">"))) {
  493. assert(false && "invalid format for parametrized pass name");
  494. }
  495. Expected<ParametersT> Result = Parser(Params);
  496. assert((Result || Result.template errorIsA<StringError>()) &&
  497. "Pass parameter parser can only return StringErrors.");
  498. return Result;
  499. }
  500. /// Parser of parameters for LoopUnroll pass.
  501. Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
  502. LoopUnrollOptions UnrollOpts;
  503. while (!Params.empty()) {
  504. StringRef ParamName;
  505. std::tie(ParamName, Params) = Params.split(';');
  506. int OptLevel = StringSwitch<int>(ParamName)
  507. .Case("O0", 0)
  508. .Case("O1", 1)
  509. .Case("O2", 2)
  510. .Case("O3", 3)
  511. .Default(-1);
  512. if (OptLevel >= 0) {
  513. UnrollOpts.setOptLevel(OptLevel);
  514. continue;
  515. }
  516. if (ParamName.consume_front("full-unroll-max=")) {
  517. int Count;
  518. if (ParamName.getAsInteger(0, Count))
  519. return make_error<StringError>(
  520. formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
  521. inconvertibleErrorCode());
  522. UnrollOpts.setFullUnrollMaxCount(Count);
  523. continue;
  524. }
  525. bool Enable = !ParamName.consume_front("no-");
  526. if (ParamName == "partial") {
  527. UnrollOpts.setPartial(Enable);
  528. } else if (ParamName == "peeling") {
  529. UnrollOpts.setPeeling(Enable);
  530. } else if (ParamName == "profile-peeling") {
  531. UnrollOpts.setProfileBasedPeeling(Enable);
  532. } else if (ParamName == "runtime") {
  533. UnrollOpts.setRuntime(Enable);
  534. } else if (ParamName == "upperbound") {
  535. UnrollOpts.setUpperBound(Enable);
  536. } else {
  537. return make_error<StringError>(
  538. formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
  539. inconvertibleErrorCode());
  540. }
  541. }
  542. return UnrollOpts;
  543. }
  544. Expected<bool> parseSinglePassOption(StringRef Params, StringRef OptionName,
  545. StringRef PassName) {
  546. bool Result = false;
  547. while (!Params.empty()) {
  548. StringRef ParamName;
  549. std::tie(ParamName, Params) = Params.split(';');
  550. if (ParamName == OptionName) {
  551. Result = true;
  552. } else {
  553. return make_error<StringError>(
  554. formatv("invalid {1} pass parameter '{0}' ", ParamName, PassName)
  555. .str(),
  556. inconvertibleErrorCode());
  557. }
  558. }
  559. return Result;
  560. }
  561. Expected<bool> parseInlinerPassOptions(StringRef Params) {
  562. return parseSinglePassOption(Params, "only-mandatory", "InlinerPass");
  563. }
  564. Expected<bool> parseCoroSplitPassOptions(StringRef Params) {
  565. return parseSinglePassOption(Params, "reuse-storage", "CoroSplitPass");
  566. }
  567. Expected<bool> parseEarlyCSEPassOptions(StringRef Params) {
  568. return parseSinglePassOption(Params, "memssa", "EarlyCSE");
  569. }
  570. Expected<bool> parseEntryExitInstrumenterPassOptions(StringRef Params) {
  571. return parseSinglePassOption(Params, "post-inline", "EntryExitInstrumenter");
  572. }
  573. Expected<bool> parseLoopExtractorPassOptions(StringRef Params) {
  574. return parseSinglePassOption(Params, "single", "LoopExtractor");
  575. }
  576. Expected<bool> parseLowerMatrixIntrinsicsPassOptions(StringRef Params) {
  577. return parseSinglePassOption(Params, "minimal", "LowerMatrixIntrinsics");
  578. }
  579. Expected<AddressSanitizerOptions> parseASanPassOptions(StringRef Params) {
  580. AddressSanitizerOptions Result;
  581. while (!Params.empty()) {
  582. StringRef ParamName;
  583. std::tie(ParamName, Params) = Params.split(';');
  584. if (ParamName == "kernel") {
  585. Result.CompileKernel = true;
  586. } else {
  587. return make_error<StringError>(
  588. formatv("invalid AddressSanitizer pass parameter '{0}' ", ParamName)
  589. .str(),
  590. inconvertibleErrorCode());
  591. }
  592. }
  593. return Result;
  594. }
  595. Expected<HWAddressSanitizerOptions> parseHWASanPassOptions(StringRef Params) {
  596. HWAddressSanitizerOptions Result;
  597. while (!Params.empty()) {
  598. StringRef ParamName;
  599. std::tie(ParamName, Params) = Params.split(';');
  600. if (ParamName == "recover") {
  601. Result.Recover = true;
  602. } else if (ParamName == "kernel") {
  603. Result.CompileKernel = true;
  604. } else {
  605. return make_error<StringError>(
  606. formatv("invalid HWAddressSanitizer pass parameter '{0}' ", ParamName)
  607. .str(),
  608. inconvertibleErrorCode());
  609. }
  610. }
  611. return Result;
  612. }
  613. Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
  614. MemorySanitizerOptions Result;
  615. while (!Params.empty()) {
  616. StringRef ParamName;
  617. std::tie(ParamName, Params) = Params.split(';');
  618. if (ParamName == "recover") {
  619. Result.Recover = true;
  620. } else if (ParamName == "kernel") {
  621. Result.Kernel = true;
  622. } else if (ParamName.consume_front("track-origins=")) {
  623. if (ParamName.getAsInteger(0, Result.TrackOrigins))
  624. return make_error<StringError>(
  625. formatv("invalid argument to MemorySanitizer pass track-origins "
  626. "parameter: '{0}' ",
  627. ParamName)
  628. .str(),
  629. inconvertibleErrorCode());
  630. } else if (ParamName == "eager-checks") {
  631. Result.EagerChecks = true;
  632. } else {
  633. return make_error<StringError>(
  634. formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
  635. .str(),
  636. inconvertibleErrorCode());
  637. }
  638. }
  639. return Result;
  640. }
  641. /// Parser of parameters for SimplifyCFG pass.
  642. Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
  643. SimplifyCFGOptions Result;
  644. while (!Params.empty()) {
  645. StringRef ParamName;
  646. std::tie(ParamName, Params) = Params.split(';');
  647. bool Enable = !ParamName.consume_front("no-");
  648. if (ParamName == "forward-switch-cond") {
  649. Result.forwardSwitchCondToPhi(Enable);
  650. } else if (ParamName == "switch-range-to-icmp") {
  651. Result.convertSwitchRangeToICmp(Enable);
  652. } else if (ParamName == "switch-to-lookup") {
  653. Result.convertSwitchToLookupTable(Enable);
  654. } else if (ParamName == "keep-loops") {
  655. Result.needCanonicalLoops(Enable);
  656. } else if (ParamName == "hoist-common-insts") {
  657. Result.hoistCommonInsts(Enable);
  658. } else if (ParamName == "sink-common-insts") {
  659. Result.sinkCommonInsts(Enable);
  660. } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
  661. APInt BonusInstThreshold;
  662. if (ParamName.getAsInteger(0, BonusInstThreshold))
  663. return make_error<StringError>(
  664. formatv("invalid argument to SimplifyCFG pass bonus-threshold "
  665. "parameter: '{0}' ",
  666. ParamName).str(),
  667. inconvertibleErrorCode());
  668. Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
  669. } else {
  670. return make_error<StringError>(
  671. formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
  672. inconvertibleErrorCode());
  673. }
  674. }
  675. return Result;
  676. }
  677. /// Parser of parameters for LoopVectorize pass.
  678. Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
  679. LoopVectorizeOptions Opts;
  680. while (!Params.empty()) {
  681. StringRef ParamName;
  682. std::tie(ParamName, Params) = Params.split(';');
  683. bool Enable = !ParamName.consume_front("no-");
  684. if (ParamName == "interleave-forced-only") {
  685. Opts.setInterleaveOnlyWhenForced(Enable);
  686. } else if (ParamName == "vectorize-forced-only") {
  687. Opts.setVectorizeOnlyWhenForced(Enable);
  688. } else {
  689. return make_error<StringError>(
  690. formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
  691. inconvertibleErrorCode());
  692. }
  693. }
  694. return Opts;
  695. }
  696. Expected<std::pair<bool, bool>> parseLoopUnswitchOptions(StringRef Params) {
  697. std::pair<bool, bool> Result = {false, true};
  698. while (!Params.empty()) {
  699. StringRef ParamName;
  700. std::tie(ParamName, Params) = Params.split(';');
  701. bool Enable = !ParamName.consume_front("no-");
  702. if (ParamName == "nontrivial") {
  703. Result.first = Enable;
  704. } else if (ParamName == "trivial") {
  705. Result.second = Enable;
  706. } else {
  707. return make_error<StringError>(
  708. formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
  709. .str(),
  710. inconvertibleErrorCode());
  711. }
  712. }
  713. return Result;
  714. }
  715. Expected<LICMOptions> parseLICMOptions(StringRef Params) {
  716. LICMOptions Result;
  717. while (!Params.empty()) {
  718. StringRef ParamName;
  719. std::tie(ParamName, Params) = Params.split(';');
  720. bool Enable = !ParamName.consume_front("no-");
  721. if (ParamName == "allowspeculation") {
  722. Result.AllowSpeculation = Enable;
  723. } else {
  724. return make_error<StringError>(
  725. formatv("invalid LICM pass parameter '{0}' ", ParamName).str(),
  726. inconvertibleErrorCode());
  727. }
  728. }
  729. return Result;
  730. }
  731. Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) {
  732. bool Result = false;
  733. while (!Params.empty()) {
  734. StringRef ParamName;
  735. std::tie(ParamName, Params) = Params.split(';');
  736. bool Enable = !ParamName.consume_front("no-");
  737. if (ParamName == "split-footer-bb") {
  738. Result = Enable;
  739. } else {
  740. return make_error<StringError>(
  741. formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
  742. ParamName)
  743. .str(),
  744. inconvertibleErrorCode());
  745. }
  746. }
  747. return Result;
  748. }
  749. Expected<GVNOptions> parseGVNOptions(StringRef Params) {
  750. GVNOptions Result;
  751. while (!Params.empty()) {
  752. StringRef ParamName;
  753. std::tie(ParamName, Params) = Params.split(';');
  754. bool Enable = !ParamName.consume_front("no-");
  755. if (ParamName == "pre") {
  756. Result.setPRE(Enable);
  757. } else if (ParamName == "load-pre") {
  758. Result.setLoadPRE(Enable);
  759. } else if (ParamName == "split-backedge-load-pre") {
  760. Result.setLoadPRESplitBackedge(Enable);
  761. } else if (ParamName == "memdep") {
  762. Result.setMemDep(Enable);
  763. } else {
  764. return make_error<StringError>(
  765. formatv("invalid GVN pass parameter '{0}' ", ParamName).str(),
  766. inconvertibleErrorCode());
  767. }
  768. }
  769. return Result;
  770. }
  771. Expected<IPSCCPOptions> parseIPSCCPOptions(StringRef Params) {
  772. IPSCCPOptions Result;
  773. while (!Params.empty()) {
  774. StringRef ParamName;
  775. std::tie(ParamName, Params) = Params.split(';');
  776. bool Enable = !ParamName.consume_front("no-");
  777. if (ParamName == "func-spec")
  778. Result.setFuncSpec(Enable);
  779. else
  780. return make_error<StringError>(
  781. formatv("invalid IPSCCP pass parameter '{0}' ", ParamName).str(),
  782. inconvertibleErrorCode());
  783. }
  784. return Result;
  785. }
  786. Expected<SROAOptions> parseSROAOptions(StringRef Params) {
  787. if (Params.empty() || Params == "modify-cfg")
  788. return SROAOptions::ModifyCFG;
  789. if (Params == "preserve-cfg")
  790. return SROAOptions::PreserveCFG;
  791. return make_error<StringError>(
  792. formatv("invalid SROA pass parameter '{0}' (either preserve-cfg or "
  793. "modify-cfg can be specified)",
  794. Params)
  795. .str(),
  796. inconvertibleErrorCode());
  797. }
  798. Expected<StackLifetime::LivenessType>
  799. parseStackLifetimeOptions(StringRef Params) {
  800. StackLifetime::LivenessType Result = StackLifetime::LivenessType::May;
  801. while (!Params.empty()) {
  802. StringRef ParamName;
  803. std::tie(ParamName, Params) = Params.split(';');
  804. if (ParamName == "may") {
  805. Result = StackLifetime::LivenessType::May;
  806. } else if (ParamName == "must") {
  807. Result = StackLifetime::LivenessType::Must;
  808. } else {
  809. return make_error<StringError>(
  810. formatv("invalid StackLifetime parameter '{0}' ", ParamName).str(),
  811. inconvertibleErrorCode());
  812. }
  813. }
  814. return Result;
  815. }
  816. Expected<bool> parseDependenceAnalysisPrinterOptions(StringRef Params) {
  817. return parseSinglePassOption(Params, "normalized-results",
  818. "DependenceAnalysisPrinter");
  819. }
  820. } // namespace
  821. /// Tests whether a pass name starts with a valid prefix for a default pipeline
  822. /// alias.
  823. static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
  824. return Name.startswith("default") || Name.startswith("thinlto") ||
  825. Name.startswith("lto");
  826. }
  827. /// Tests whether registered callbacks will accept a given pass name.
  828. ///
  829. /// When parsing a pipeline text, the type of the outermost pipeline may be
  830. /// omitted, in which case the type is automatically determined from the first
  831. /// pass name in the text. This may be a name that is handled through one of the
  832. /// callbacks. We check this through the oridinary parsing callbacks by setting
  833. /// up a dummy PassManager in order to not force the client to also handle this
  834. /// type of query.
  835. template <typename PassManagerT, typename CallbacksT>
  836. static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
  837. if (!Callbacks.empty()) {
  838. PassManagerT DummyPM;
  839. for (auto &CB : Callbacks)
  840. if (CB(Name, DummyPM, {}))
  841. return true;
  842. }
  843. return false;
  844. }
  845. template <typename CallbacksT>
  846. static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
  847. // Manually handle aliases for pre-configured pipeline fragments.
  848. if (startsWithDefaultPipelineAliasPrefix(Name))
  849. return DefaultAliasRegex.match(Name);
  850. // Explicitly handle pass manager names.
  851. if (Name == "module")
  852. return true;
  853. if (Name == "cgscc")
  854. return true;
  855. if (Name == "function" || Name == "function<eager-inv>")
  856. return true;
  857. if (Name == "coro-cond")
  858. return true;
  859. // Explicitly handle custom-parsed pass names.
  860. if (parseRepeatPassName(Name))
  861. return true;
  862. #define MODULE_PASS(NAME, CREATE_PASS) \
  863. if (Name == NAME) \
  864. return true;
  865. #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  866. if (checkParametrizedPassName(Name, NAME)) \
  867. return true;
  868. #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
  869. if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
  870. return true;
  871. #include "PassRegistry.def"
  872. return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
  873. }
  874. template <typename CallbacksT>
  875. static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
  876. // Explicitly handle pass manager names.
  877. if (Name == "cgscc")
  878. return true;
  879. if (Name == "function" || Name == "function<eager-inv>")
  880. return true;
  881. // Explicitly handle custom-parsed pass names.
  882. if (parseRepeatPassName(Name))
  883. return true;
  884. if (parseDevirtPassName(Name))
  885. return true;
  886. #define CGSCC_PASS(NAME, CREATE_PASS) \
  887. if (Name == NAME) \
  888. return true;
  889. #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  890. if (checkParametrizedPassName(Name, NAME)) \
  891. return true;
  892. #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
  893. if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
  894. return true;
  895. #include "PassRegistry.def"
  896. return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
  897. }
  898. template <typename CallbacksT>
  899. static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
  900. // Explicitly handle pass manager names.
  901. if (Name == "function" || Name == "function<eager-inv>")
  902. return true;
  903. if (Name == "loop" || Name == "loop-mssa")
  904. return true;
  905. // Explicitly handle custom-parsed pass names.
  906. if (parseRepeatPassName(Name))
  907. return true;
  908. #define FUNCTION_PASS(NAME, CREATE_PASS) \
  909. if (Name == NAME) \
  910. return true;
  911. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  912. if (checkParametrizedPassName(Name, NAME)) \
  913. return true;
  914. #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
  915. if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
  916. return true;
  917. #include "PassRegistry.def"
  918. return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
  919. }
  920. template <typename CallbacksT>
  921. static bool isLoopNestPassName(StringRef Name, CallbacksT &Callbacks,
  922. bool &UseMemorySSA) {
  923. UseMemorySSA = false;
  924. // Explicitly handle custom-parsed pass names.
  925. if (parseRepeatPassName(Name))
  926. return true;
  927. if (checkParametrizedPassName(Name, "lnicm")) {
  928. UseMemorySSA = true;
  929. return true;
  930. }
  931. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  932. if (Name == NAME) \
  933. return true;
  934. #include "PassRegistry.def"
  935. return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
  936. }
  937. template <typename CallbacksT>
  938. static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks,
  939. bool &UseMemorySSA) {
  940. UseMemorySSA = false;
  941. // Explicitly handle custom-parsed pass names.
  942. if (parseRepeatPassName(Name))
  943. return true;
  944. if (checkParametrizedPassName(Name, "licm")) {
  945. UseMemorySSA = true;
  946. return true;
  947. }
  948. #define LOOP_PASS(NAME, CREATE_PASS) \
  949. if (Name == NAME) \
  950. return true;
  951. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  952. if (checkParametrizedPassName(Name, NAME)) \
  953. return true;
  954. #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
  955. if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
  956. return true;
  957. #include "PassRegistry.def"
  958. return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
  959. }
  960. std::optional<std::vector<PassBuilder::PipelineElement>>
  961. PassBuilder::parsePipelineText(StringRef Text) {
  962. std::vector<PipelineElement> ResultPipeline;
  963. SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
  964. &ResultPipeline};
  965. for (;;) {
  966. std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
  967. size_t Pos = Text.find_first_of(",()");
  968. Pipeline.push_back({Text.substr(0, Pos), {}});
  969. // If we have a single terminating name, we're done.
  970. if (Pos == Text.npos)
  971. break;
  972. char Sep = Text[Pos];
  973. Text = Text.substr(Pos + 1);
  974. if (Sep == ',')
  975. // Just a name ending in a comma, continue.
  976. continue;
  977. if (Sep == '(') {
  978. // Push the inner pipeline onto the stack to continue processing.
  979. PipelineStack.push_back(&Pipeline.back().InnerPipeline);
  980. continue;
  981. }
  982. assert(Sep == ')' && "Bogus separator!");
  983. // When handling the close parenthesis, we greedily consume them to avoid
  984. // empty strings in the pipeline.
  985. do {
  986. // If we try to pop the outer pipeline we have unbalanced parentheses.
  987. if (PipelineStack.size() == 1)
  988. return std::nullopt;
  989. PipelineStack.pop_back();
  990. } while (Text.consume_front(")"));
  991. // Check if we've finished parsing.
  992. if (Text.empty())
  993. break;
  994. // Otherwise, the end of an inner pipeline always has to be followed by
  995. // a comma, and then we can continue.
  996. if (!Text.consume_front(","))
  997. return std::nullopt;
  998. }
  999. if (PipelineStack.size() > 1)
  1000. // Unbalanced paretheses.
  1001. return std::nullopt;
  1002. assert(PipelineStack.back() == &ResultPipeline &&
  1003. "Wrong pipeline at the bottom of the stack!");
  1004. return {std::move(ResultPipeline)};
  1005. }
  1006. Error PassBuilder::parseModulePass(ModulePassManager &MPM,
  1007. const PipelineElement &E) {
  1008. auto &Name = E.Name;
  1009. auto &InnerPipeline = E.InnerPipeline;
  1010. // First handle complex passes like the pass managers which carry pipelines.
  1011. if (!InnerPipeline.empty()) {
  1012. if (Name == "module") {
  1013. ModulePassManager NestedMPM;
  1014. if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
  1015. return Err;
  1016. MPM.addPass(std::move(NestedMPM));
  1017. return Error::success();
  1018. }
  1019. if (Name == "coro-cond") {
  1020. ModulePassManager NestedMPM;
  1021. if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
  1022. return Err;
  1023. MPM.addPass(CoroConditionalWrapper(std::move(NestedMPM)));
  1024. return Error::success();
  1025. }
  1026. if (Name == "cgscc") {
  1027. CGSCCPassManager CGPM;
  1028. if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline))
  1029. return Err;
  1030. MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
  1031. return Error::success();
  1032. }
  1033. if (Name == "function" || Name == "function<eager-inv>") {
  1034. FunctionPassManager FPM;
  1035. if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
  1036. return Err;
  1037. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
  1038. Name != "function"));
  1039. return Error::success();
  1040. }
  1041. if (auto Count = parseRepeatPassName(Name)) {
  1042. ModulePassManager NestedMPM;
  1043. if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
  1044. return Err;
  1045. MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
  1046. return Error::success();
  1047. }
  1048. for (auto &C : ModulePipelineParsingCallbacks)
  1049. if (C(Name, MPM, InnerPipeline))
  1050. return Error::success();
  1051. // Normal passes can't have pipelines.
  1052. return make_error<StringError>(
  1053. formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
  1054. inconvertibleErrorCode());
  1055. ;
  1056. }
  1057. // Manually handle aliases for pre-configured pipeline fragments.
  1058. if (startsWithDefaultPipelineAliasPrefix(Name)) {
  1059. SmallVector<StringRef, 3> Matches;
  1060. if (!DefaultAliasRegex.match(Name, &Matches))
  1061. return make_error<StringError>(
  1062. formatv("unknown default pipeline alias '{0}'", Name).str(),
  1063. inconvertibleErrorCode());
  1064. assert(Matches.size() == 3 && "Must capture two matched strings!");
  1065. OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
  1066. .Case("O0", OptimizationLevel::O0)
  1067. .Case("O1", OptimizationLevel::O1)
  1068. .Case("O2", OptimizationLevel::O2)
  1069. .Case("O3", OptimizationLevel::O3)
  1070. .Case("Os", OptimizationLevel::Os)
  1071. .Case("Oz", OptimizationLevel::Oz);
  1072. if (L == OptimizationLevel::O0 && Matches[1] != "thinlto" &&
  1073. Matches[1] != "lto") {
  1074. MPM.addPass(buildO0DefaultPipeline(L, Matches[1] == "thinlto-pre-link" ||
  1075. Matches[1] == "lto-pre-link"));
  1076. return Error::success();
  1077. }
  1078. // This is consistent with old pass manager invoked via opt, but
  1079. // inconsistent with clang. Clang doesn't enable loop vectorization
  1080. // but does enable slp vectorization at Oz.
  1081. PTO.LoopVectorization =
  1082. L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
  1083. PTO.SLPVectorization =
  1084. L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
  1085. if (Matches[1] == "default") {
  1086. MPM.addPass(buildPerModuleDefaultPipeline(L));
  1087. } else if (Matches[1] == "thinlto-pre-link") {
  1088. MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L));
  1089. } else if (Matches[1] == "thinlto") {
  1090. MPM.addPass(buildThinLTODefaultPipeline(L, nullptr));
  1091. } else if (Matches[1] == "lto-pre-link") {
  1092. MPM.addPass(buildLTOPreLinkDefaultPipeline(L));
  1093. } else {
  1094. assert(Matches[1] == "lto" && "Not one of the matched options!");
  1095. MPM.addPass(buildLTODefaultPipeline(L, nullptr));
  1096. }
  1097. return Error::success();
  1098. }
  1099. // Finally expand the basic registered passes from the .inc file.
  1100. #define MODULE_PASS(NAME, CREATE_PASS) \
  1101. if (Name == NAME) { \
  1102. MPM.addPass(CREATE_PASS); \
  1103. return Error::success(); \
  1104. }
  1105. #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1106. if (checkParametrizedPassName(Name, NAME)) { \
  1107. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1108. if (!Params) \
  1109. return Params.takeError(); \
  1110. MPM.addPass(CREATE_PASS(Params.get())); \
  1111. return Error::success(); \
  1112. }
  1113. #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
  1114. if (Name == "require<" NAME ">") { \
  1115. MPM.addPass( \
  1116. RequireAnalysisPass< \
  1117. std::remove_reference_t<decltype(CREATE_PASS)>, Module>()); \
  1118. return Error::success(); \
  1119. } \
  1120. if (Name == "invalidate<" NAME ">") { \
  1121. MPM.addPass(InvalidateAnalysisPass< \
  1122. std::remove_reference_t<decltype(CREATE_PASS)>>()); \
  1123. return Error::success(); \
  1124. }
  1125. #define CGSCC_PASS(NAME, CREATE_PASS) \
  1126. if (Name == NAME) { \
  1127. MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS)); \
  1128. return Error::success(); \
  1129. }
  1130. #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1131. if (checkParametrizedPassName(Name, NAME)) { \
  1132. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1133. if (!Params) \
  1134. return Params.takeError(); \
  1135. MPM.addPass( \
  1136. createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS(Params.get()))); \
  1137. return Error::success(); \
  1138. }
  1139. #define FUNCTION_PASS(NAME, CREATE_PASS) \
  1140. if (Name == NAME) { \
  1141. MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS)); \
  1142. return Error::success(); \
  1143. }
  1144. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1145. if (checkParametrizedPassName(Name, NAME)) { \
  1146. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1147. if (!Params) \
  1148. return Params.takeError(); \
  1149. MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
  1150. return Error::success(); \
  1151. }
  1152. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  1153. if (Name == NAME) { \
  1154. MPM.addPass(createModuleToFunctionPassAdaptor( \
  1155. createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
  1156. return Error::success(); \
  1157. }
  1158. #define LOOP_PASS(NAME, CREATE_PASS) \
  1159. if (Name == NAME) { \
  1160. MPM.addPass(createModuleToFunctionPassAdaptor( \
  1161. createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
  1162. return Error::success(); \
  1163. }
  1164. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1165. if (checkParametrizedPassName(Name, NAME)) { \
  1166. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1167. if (!Params) \
  1168. return Params.takeError(); \
  1169. MPM.addPass( \
  1170. createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor( \
  1171. CREATE_PASS(Params.get()), false, false))); \
  1172. return Error::success(); \
  1173. }
  1174. #include "PassRegistry.def"
  1175. for (auto &C : ModulePipelineParsingCallbacks)
  1176. if (C(Name, MPM, InnerPipeline))
  1177. return Error::success();
  1178. return make_error<StringError>(
  1179. formatv("unknown module pass '{0}'", Name).str(),
  1180. inconvertibleErrorCode());
  1181. }
  1182. Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
  1183. const PipelineElement &E) {
  1184. auto &Name = E.Name;
  1185. auto &InnerPipeline = E.InnerPipeline;
  1186. // First handle complex passes like the pass managers which carry pipelines.
  1187. if (!InnerPipeline.empty()) {
  1188. if (Name == "cgscc") {
  1189. CGSCCPassManager NestedCGPM;
  1190. if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
  1191. return Err;
  1192. // Add the nested pass manager with the appropriate adaptor.
  1193. CGPM.addPass(std::move(NestedCGPM));
  1194. return Error::success();
  1195. }
  1196. if (Name == "function" || Name == "function<eager-inv>") {
  1197. FunctionPassManager FPM;
  1198. if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
  1199. return Err;
  1200. // Add the nested pass manager with the appropriate adaptor.
  1201. CGPM.addPass(
  1202. createCGSCCToFunctionPassAdaptor(std::move(FPM), Name != "function"));
  1203. return Error::success();
  1204. }
  1205. if (auto Count = parseRepeatPassName(Name)) {
  1206. CGSCCPassManager NestedCGPM;
  1207. if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
  1208. return Err;
  1209. CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
  1210. return Error::success();
  1211. }
  1212. if (auto MaxRepetitions = parseDevirtPassName(Name)) {
  1213. CGSCCPassManager NestedCGPM;
  1214. if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
  1215. return Err;
  1216. CGPM.addPass(
  1217. createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
  1218. return Error::success();
  1219. }
  1220. for (auto &C : CGSCCPipelineParsingCallbacks)
  1221. if (C(Name, CGPM, InnerPipeline))
  1222. return Error::success();
  1223. // Normal passes can't have pipelines.
  1224. return make_error<StringError>(
  1225. formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
  1226. inconvertibleErrorCode());
  1227. }
  1228. // Now expand the basic registered passes from the .inc file.
  1229. #define CGSCC_PASS(NAME, CREATE_PASS) \
  1230. if (Name == NAME) { \
  1231. CGPM.addPass(CREATE_PASS); \
  1232. return Error::success(); \
  1233. }
  1234. #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1235. if (checkParametrizedPassName(Name, NAME)) { \
  1236. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1237. if (!Params) \
  1238. return Params.takeError(); \
  1239. CGPM.addPass(CREATE_PASS(Params.get())); \
  1240. return Error::success(); \
  1241. }
  1242. #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
  1243. if (Name == "require<" NAME ">") { \
  1244. CGPM.addPass(RequireAnalysisPass< \
  1245. std::remove_reference_t<decltype(CREATE_PASS)>, \
  1246. LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
  1247. CGSCCUpdateResult &>()); \
  1248. return Error::success(); \
  1249. } \
  1250. if (Name == "invalidate<" NAME ">") { \
  1251. CGPM.addPass(InvalidateAnalysisPass< \
  1252. std::remove_reference_t<decltype(CREATE_PASS)>>()); \
  1253. return Error::success(); \
  1254. }
  1255. #define FUNCTION_PASS(NAME, CREATE_PASS) \
  1256. if (Name == NAME) { \
  1257. CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS)); \
  1258. return Error::success(); \
  1259. }
  1260. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1261. if (checkParametrizedPassName(Name, NAME)) { \
  1262. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1263. if (!Params) \
  1264. return Params.takeError(); \
  1265. CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
  1266. return Error::success(); \
  1267. }
  1268. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  1269. if (Name == NAME) { \
  1270. CGPM.addPass(createCGSCCToFunctionPassAdaptor( \
  1271. createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
  1272. return Error::success(); \
  1273. }
  1274. #define LOOP_PASS(NAME, CREATE_PASS) \
  1275. if (Name == NAME) { \
  1276. CGPM.addPass(createCGSCCToFunctionPassAdaptor( \
  1277. createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
  1278. return Error::success(); \
  1279. }
  1280. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1281. if (checkParametrizedPassName(Name, NAME)) { \
  1282. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1283. if (!Params) \
  1284. return Params.takeError(); \
  1285. CGPM.addPass( \
  1286. createCGSCCToFunctionPassAdaptor(createFunctionToLoopPassAdaptor( \
  1287. CREATE_PASS(Params.get()), false, false))); \
  1288. return Error::success(); \
  1289. }
  1290. #include "PassRegistry.def"
  1291. for (auto &C : CGSCCPipelineParsingCallbacks)
  1292. if (C(Name, CGPM, InnerPipeline))
  1293. return Error::success();
  1294. return make_error<StringError>(
  1295. formatv("unknown cgscc pass '{0}'", Name).str(),
  1296. inconvertibleErrorCode());
  1297. }
  1298. Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
  1299. const PipelineElement &E) {
  1300. auto &Name = E.Name;
  1301. auto &InnerPipeline = E.InnerPipeline;
  1302. // First handle complex passes like the pass managers which carry pipelines.
  1303. if (!InnerPipeline.empty()) {
  1304. if (Name == "function") {
  1305. FunctionPassManager NestedFPM;
  1306. if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
  1307. return Err;
  1308. // Add the nested pass manager with the appropriate adaptor.
  1309. FPM.addPass(std::move(NestedFPM));
  1310. return Error::success();
  1311. }
  1312. if (Name == "loop" || Name == "loop-mssa") {
  1313. LoopPassManager LPM;
  1314. if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline))
  1315. return Err;
  1316. // Add the nested pass manager with the appropriate adaptor.
  1317. bool UseMemorySSA = (Name == "loop-mssa");
  1318. bool UseBFI = llvm::any_of(InnerPipeline, [](auto Pipeline) {
  1319. return Pipeline.Name.contains("simple-loop-unswitch");
  1320. });
  1321. bool UseBPI = llvm::any_of(InnerPipeline, [](auto Pipeline) {
  1322. return Pipeline.Name == "loop-predication";
  1323. });
  1324. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
  1325. UseBFI, UseBPI));
  1326. return Error::success();
  1327. }
  1328. if (auto Count = parseRepeatPassName(Name)) {
  1329. FunctionPassManager NestedFPM;
  1330. if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
  1331. return Err;
  1332. FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
  1333. return Error::success();
  1334. }
  1335. for (auto &C : FunctionPipelineParsingCallbacks)
  1336. if (C(Name, FPM, InnerPipeline))
  1337. return Error::success();
  1338. // Normal passes can't have pipelines.
  1339. return make_error<StringError>(
  1340. formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
  1341. inconvertibleErrorCode());
  1342. }
  1343. // Now expand the basic registered passes from the .inc file.
  1344. #define FUNCTION_PASS(NAME, CREATE_PASS) \
  1345. if (Name == NAME) { \
  1346. FPM.addPass(CREATE_PASS); \
  1347. return Error::success(); \
  1348. }
  1349. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1350. if (checkParametrizedPassName(Name, NAME)) { \
  1351. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1352. if (!Params) \
  1353. return Params.takeError(); \
  1354. FPM.addPass(CREATE_PASS(Params.get())); \
  1355. return Error::success(); \
  1356. }
  1357. #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
  1358. if (Name == "require<" NAME ">") { \
  1359. FPM.addPass( \
  1360. RequireAnalysisPass< \
  1361. std::remove_reference_t<decltype(CREATE_PASS)>, Function>()); \
  1362. return Error::success(); \
  1363. } \
  1364. if (Name == "invalidate<" NAME ">") { \
  1365. FPM.addPass(InvalidateAnalysisPass< \
  1366. std::remove_reference_t<decltype(CREATE_PASS)>>()); \
  1367. return Error::success(); \
  1368. }
  1369. // FIXME: UseMemorySSA is set to false. Maybe we could do things like:
  1370. // bool UseMemorySSA = !("canon-freeze" || "loop-predication" ||
  1371. // "guard-widening");
  1372. // The risk is that it may become obsolete if we're not careful.
  1373. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  1374. if (Name == NAME) { \
  1375. FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)); \
  1376. return Error::success(); \
  1377. }
  1378. #define LOOP_PASS(NAME, CREATE_PASS) \
  1379. if (Name == NAME) { \
  1380. FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)); \
  1381. return Error::success(); \
  1382. }
  1383. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1384. if (checkParametrizedPassName(Name, NAME)) { \
  1385. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1386. if (!Params) \
  1387. return Params.takeError(); \
  1388. FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS(Params.get()), \
  1389. false, false)); \
  1390. return Error::success(); \
  1391. }
  1392. #include "PassRegistry.def"
  1393. for (auto &C : FunctionPipelineParsingCallbacks)
  1394. if (C(Name, FPM, InnerPipeline))
  1395. return Error::success();
  1396. return make_error<StringError>(
  1397. formatv("unknown function pass '{0}'", Name).str(),
  1398. inconvertibleErrorCode());
  1399. }
  1400. Error PassBuilder::parseLoopPass(LoopPassManager &LPM,
  1401. const PipelineElement &E) {
  1402. StringRef Name = E.Name;
  1403. auto &InnerPipeline = E.InnerPipeline;
  1404. // First handle complex passes like the pass managers which carry pipelines.
  1405. if (!InnerPipeline.empty()) {
  1406. if (Name == "loop") {
  1407. LoopPassManager NestedLPM;
  1408. if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
  1409. return Err;
  1410. // Add the nested pass manager with the appropriate adaptor.
  1411. LPM.addPass(std::move(NestedLPM));
  1412. return Error::success();
  1413. }
  1414. if (auto Count = parseRepeatPassName(Name)) {
  1415. LoopPassManager NestedLPM;
  1416. if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
  1417. return Err;
  1418. LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
  1419. return Error::success();
  1420. }
  1421. for (auto &C : LoopPipelineParsingCallbacks)
  1422. if (C(Name, LPM, InnerPipeline))
  1423. return Error::success();
  1424. // Normal passes can't have pipelines.
  1425. return make_error<StringError>(
  1426. formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
  1427. inconvertibleErrorCode());
  1428. }
  1429. // Now expand the basic registered passes from the .inc file.
  1430. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  1431. if (Name == NAME) { \
  1432. LPM.addPass(CREATE_PASS); \
  1433. return Error::success(); \
  1434. }
  1435. #define LOOP_PASS(NAME, CREATE_PASS) \
  1436. if (Name == NAME) { \
  1437. LPM.addPass(CREATE_PASS); \
  1438. return Error::success(); \
  1439. }
  1440. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1441. if (checkParametrizedPassName(Name, NAME)) { \
  1442. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1443. if (!Params) \
  1444. return Params.takeError(); \
  1445. LPM.addPass(CREATE_PASS(Params.get())); \
  1446. return Error::success(); \
  1447. }
  1448. #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
  1449. if (Name == "require<" NAME ">") { \
  1450. LPM.addPass(RequireAnalysisPass< \
  1451. std::remove_reference_t<decltype(CREATE_PASS)>, Loop, \
  1452. LoopAnalysisManager, LoopStandardAnalysisResults &, \
  1453. LPMUpdater &>()); \
  1454. return Error::success(); \
  1455. } \
  1456. if (Name == "invalidate<" NAME ">") { \
  1457. LPM.addPass(InvalidateAnalysisPass< \
  1458. std::remove_reference_t<decltype(CREATE_PASS)>>()); \
  1459. return Error::success(); \
  1460. }
  1461. #include "PassRegistry.def"
  1462. for (auto &C : LoopPipelineParsingCallbacks)
  1463. if (C(Name, LPM, InnerPipeline))
  1464. return Error::success();
  1465. return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
  1466. inconvertibleErrorCode());
  1467. }
  1468. bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
  1469. #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
  1470. if (Name == NAME) { \
  1471. AA.registerModuleAnalysis< \
  1472. std::remove_reference_t<decltype(CREATE_PASS)>>(); \
  1473. return true; \
  1474. }
  1475. #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
  1476. if (Name == NAME) { \
  1477. AA.registerFunctionAnalysis< \
  1478. std::remove_reference_t<decltype(CREATE_PASS)>>(); \
  1479. return true; \
  1480. }
  1481. #include "PassRegistry.def"
  1482. for (auto &C : AAParsingCallbacks)
  1483. if (C(Name, AA))
  1484. return true;
  1485. return false;
  1486. }
  1487. Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
  1488. ArrayRef<PipelineElement> Pipeline) {
  1489. for (const auto &Element : Pipeline) {
  1490. if (auto Err = parseLoopPass(LPM, Element))
  1491. return Err;
  1492. }
  1493. return Error::success();
  1494. }
  1495. Error PassBuilder::parseFunctionPassPipeline(
  1496. FunctionPassManager &FPM, ArrayRef<PipelineElement> Pipeline) {
  1497. for (const auto &Element : Pipeline) {
  1498. if (auto Err = parseFunctionPass(FPM, Element))
  1499. return Err;
  1500. }
  1501. return Error::success();
  1502. }
  1503. Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
  1504. ArrayRef<PipelineElement> Pipeline) {
  1505. for (const auto &Element : Pipeline) {
  1506. if (auto Err = parseCGSCCPass(CGPM, Element))
  1507. return Err;
  1508. }
  1509. return Error::success();
  1510. }
  1511. void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
  1512. FunctionAnalysisManager &FAM,
  1513. CGSCCAnalysisManager &CGAM,
  1514. ModuleAnalysisManager &MAM) {
  1515. MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
  1516. MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
  1517. CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
  1518. FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
  1519. FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
  1520. FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
  1521. LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
  1522. }
  1523. Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
  1524. ArrayRef<PipelineElement> Pipeline) {
  1525. for (const auto &Element : Pipeline) {
  1526. if (auto Err = parseModulePass(MPM, Element))
  1527. return Err;
  1528. }
  1529. return Error::success();
  1530. }
  1531. // Primary pass pipeline description parsing routine for a \c ModulePassManager
  1532. // FIXME: Should this routine accept a TargetMachine or require the caller to
  1533. // pre-populate the analysis managers with target-specific stuff?
  1534. Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
  1535. StringRef PipelineText) {
  1536. auto Pipeline = parsePipelineText(PipelineText);
  1537. if (!Pipeline || Pipeline->empty())
  1538. return make_error<StringError>(
  1539. formatv("invalid pipeline '{0}'", PipelineText).str(),
  1540. inconvertibleErrorCode());
  1541. // If the first name isn't at the module layer, wrap the pipeline up
  1542. // automatically.
  1543. StringRef FirstName = Pipeline->front().Name;
  1544. if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
  1545. bool UseMemorySSA;
  1546. if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
  1547. Pipeline = {{"cgscc", std::move(*Pipeline)}};
  1548. } else if (isFunctionPassName(FirstName,
  1549. FunctionPipelineParsingCallbacks)) {
  1550. Pipeline = {{"function", std::move(*Pipeline)}};
  1551. } else if (isLoopNestPassName(FirstName, LoopPipelineParsingCallbacks,
  1552. UseMemorySSA)) {
  1553. Pipeline = {{"function", {{UseMemorySSA ? "loop-mssa" : "loop",
  1554. std::move(*Pipeline)}}}};
  1555. } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks,
  1556. UseMemorySSA)) {
  1557. Pipeline = {{"function", {{UseMemorySSA ? "loop-mssa" : "loop",
  1558. std::move(*Pipeline)}}}};
  1559. } else {
  1560. for (auto &C : TopLevelPipelineParsingCallbacks)
  1561. if (C(MPM, *Pipeline))
  1562. return Error::success();
  1563. // Unknown pass or pipeline name!
  1564. auto &InnerPipeline = Pipeline->front().InnerPipeline;
  1565. return make_error<StringError>(
  1566. formatv("unknown {0} name '{1}'",
  1567. (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
  1568. .str(),
  1569. inconvertibleErrorCode());
  1570. }
  1571. }
  1572. if (auto Err = parseModulePassPipeline(MPM, *Pipeline))
  1573. return Err;
  1574. return Error::success();
  1575. }
  1576. // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
  1577. Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
  1578. StringRef PipelineText) {
  1579. auto Pipeline = parsePipelineText(PipelineText);
  1580. if (!Pipeline || Pipeline->empty())
  1581. return make_error<StringError>(
  1582. formatv("invalid pipeline '{0}'", PipelineText).str(),
  1583. inconvertibleErrorCode());
  1584. StringRef FirstName = Pipeline->front().Name;
  1585. if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
  1586. return make_error<StringError>(
  1587. formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
  1588. PipelineText)
  1589. .str(),
  1590. inconvertibleErrorCode());
  1591. if (auto Err = parseCGSCCPassPipeline(CGPM, *Pipeline))
  1592. return Err;
  1593. return Error::success();
  1594. }
  1595. // Primary pass pipeline description parsing routine for a \c
  1596. // FunctionPassManager
  1597. Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
  1598. StringRef PipelineText) {
  1599. auto Pipeline = parsePipelineText(PipelineText);
  1600. if (!Pipeline || Pipeline->empty())
  1601. return make_error<StringError>(
  1602. formatv("invalid pipeline '{0}'", PipelineText).str(),
  1603. inconvertibleErrorCode());
  1604. StringRef FirstName = Pipeline->front().Name;
  1605. if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
  1606. return make_error<StringError>(
  1607. formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
  1608. PipelineText)
  1609. .str(),
  1610. inconvertibleErrorCode());
  1611. if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline))
  1612. return Err;
  1613. return Error::success();
  1614. }
  1615. // Primary pass pipeline description parsing routine for a \c LoopPassManager
  1616. Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
  1617. StringRef PipelineText) {
  1618. auto Pipeline = parsePipelineText(PipelineText);
  1619. if (!Pipeline || Pipeline->empty())
  1620. return make_error<StringError>(
  1621. formatv("invalid pipeline '{0}'", PipelineText).str(),
  1622. inconvertibleErrorCode());
  1623. if (auto Err = parseLoopPassPipeline(CGPM, *Pipeline))
  1624. return Err;
  1625. return Error::success();
  1626. }
  1627. Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
  1628. // If the pipeline just consists of the word 'default' just replace the AA
  1629. // manager with our default one.
  1630. if (PipelineText == "default") {
  1631. AA = buildDefaultAAPipeline();
  1632. return Error::success();
  1633. }
  1634. while (!PipelineText.empty()) {
  1635. StringRef Name;
  1636. std::tie(Name, PipelineText) = PipelineText.split(',');
  1637. if (!parseAAPassName(AA, Name))
  1638. return make_error<StringError>(
  1639. formatv("unknown alias analysis name '{0}'", Name).str(),
  1640. inconvertibleErrorCode());
  1641. }
  1642. return Error::success();
  1643. }
  1644. static void printPassName(StringRef PassName, raw_ostream &OS) {
  1645. OS << " " << PassName << "\n";
  1646. }
  1647. static void printPassName(StringRef PassName, StringRef Params,
  1648. raw_ostream &OS) {
  1649. OS << " " << PassName << "<" << Params << ">\n";
  1650. }
  1651. void PassBuilder::printPassNames(raw_ostream &OS) {
  1652. // TODO: print pass descriptions when they are available
  1653. OS << "Module passes:\n";
  1654. #define MODULE_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1655. #include "PassRegistry.def"
  1656. OS << "Module passes with params:\n";
  1657. #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1658. printPassName(NAME, PARAMS, OS);
  1659. #include "PassRegistry.def"
  1660. OS << "Module analyses:\n";
  1661. #define MODULE_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1662. #include "PassRegistry.def"
  1663. OS << "Module alias analyses:\n";
  1664. #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1665. #include "PassRegistry.def"
  1666. OS << "CGSCC passes:\n";
  1667. #define CGSCC_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1668. #include "PassRegistry.def"
  1669. OS << "CGSCC passes with params:\n";
  1670. #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1671. printPassName(NAME, PARAMS, OS);
  1672. #include "PassRegistry.def"
  1673. OS << "CGSCC analyses:\n";
  1674. #define CGSCC_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1675. #include "PassRegistry.def"
  1676. OS << "Function passes:\n";
  1677. #define FUNCTION_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1678. #include "PassRegistry.def"
  1679. OS << "Function passes with params:\n";
  1680. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1681. printPassName(NAME, PARAMS, OS);
  1682. #include "PassRegistry.def"
  1683. OS << "Function analyses:\n";
  1684. #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1685. #include "PassRegistry.def"
  1686. OS << "Function alias analyses:\n";
  1687. #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1688. #include "PassRegistry.def"
  1689. OS << "LoopNest passes:\n";
  1690. #define LOOPNEST_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1691. #include "PassRegistry.def"
  1692. OS << "Loop passes:\n";
  1693. #define LOOP_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1694. #include "PassRegistry.def"
  1695. OS << "Loop passes with params:\n";
  1696. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1697. printPassName(NAME, PARAMS, OS);
  1698. #include "PassRegistry.def"
  1699. OS << "Loop analyses:\n";
  1700. #define LOOP_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1701. #include "PassRegistry.def"
  1702. }
  1703. void PassBuilder::registerParseTopLevelPipelineCallback(
  1704. const std::function<bool(ModulePassManager &, ArrayRef<PipelineElement>)>
  1705. &C) {
  1706. TopLevelPipelineParsingCallbacks.push_back(C);
  1707. }