blob: 2072fc3aa26102246df85c0149ebec0e7e3916e6 [file] [log] [blame]
Chandler Carruth1ff77242015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth66445382014-01-11 08:16:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chandler Carruth66445382014-01-11 08:16:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9///
Chandler Carruth1ff77242015-03-07 09:02:36 +000010/// 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.
Chandler Carruth66445382014-01-11 08:16:35 +000014///
15//===----------------------------------------------------------------------===//
16
Chandler Carruth1ff77242015-03-07 09:02:36 +000017#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000018#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000019#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000020#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000021#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000022#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000024#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000025#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000026#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000028#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000029#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000030#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000031#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000032#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000033#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000034#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000035#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000036#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000037#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000038#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000039#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000040#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000041#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000042#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000043#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000044#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000045#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000046#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000049#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000050#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000051#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000052#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000053#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000054#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000055#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000057#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000058#include "llvm/IR/PassManager.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000059#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000060#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000061#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000062#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000063#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000064#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000065#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000066#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000067#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000068#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000069#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000070#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000071#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000072#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000073#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000074#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000075#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000076#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000077#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000078#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000079#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000080#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000081#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000082#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000083#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000084#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000085#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000086#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000087#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000088#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000089#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000090#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000091#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000092#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000093#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000094#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000095#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
96#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000097#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +000098#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000099#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000100#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000101#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000102#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000103#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000104#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000105#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000106#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000107#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000108#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000109#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000110#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000111#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000112#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000113#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000114#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000115#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000116#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000117#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000118#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000119#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000120#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000121#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000122#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000123#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000124#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000125#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000126#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000127#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000128#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000129#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000130#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000131#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000132#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000133#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000134#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000135#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000136#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000137#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000138#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000139#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000140#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000141#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000142#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000143#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000144#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000145#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000146#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000147#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000148#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000149#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000150#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000151#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000152#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000153#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000154#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000155#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000156#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000157#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000158#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000159#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000160#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000161#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000162#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000163#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000164#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000165#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000166#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000167#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000168#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000169#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000170
Chandler Carruth66445382014-01-11 08:16:35 +0000171using namespace llvm;
172
Chandler Carruth719ffe12017-02-12 05:38:04 +0000173static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
174 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000175static cl::opt<bool>
176 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
177 cl::Hidden, cl::ZeroOrMore,
178 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000179
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000180static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000181 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000182 cl::Hidden, cl::ZeroOrMore,
183 cl::desc("Run NewGVN instead of GVN"));
184
Geoff Berry3cca1da2017-06-10 15:20:03 +0000185static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000186 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
187 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000188
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000189static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000190 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
191 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000192
Davide Italianobe1b6a92017-06-03 23:18:29 +0000193static cl::opt<bool> EnableGVNSink(
194 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
195 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
196
David Green963401d2018-07-01 12:47:30 +0000197static cl::opt<bool> EnableUnrollAndJam(
198 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
199 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
200
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000201static cl::opt<bool> EnableSyntheticCounts(
202 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
203 cl::desc("Run synthetic function entry count generation "
204 "pass"));
205
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000206static Regex DefaultAliasRegex(
207 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000208
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000209static cl::opt<bool>
210 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
211 cl::desc("Enable control height reduction optimization (CHR)"));
212
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000213extern cl::opt<bool> EnableHotColdSplit;
214
Wei Mi3bcccdf2019-01-17 20:48:34 +0000215extern cl::opt<bool> FlattenedProfileUsed;
216
Chandler Carruthe3f50642016-12-22 06:59:15 +0000217static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
218 switch (Level) {
219 case PassBuilder::O0:
220 case PassBuilder::O1:
221 case PassBuilder::O2:
222 case PassBuilder::O3:
223 return false;
224
225 case PassBuilder::Os:
226 case PassBuilder::Oz:
227 return true;
228 }
229 llvm_unreachable("Invalid optimization level!");
230}
231
Chandler Carruth66445382014-01-11 08:16:35 +0000232namespace {
233
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000234/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000235struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000236 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000237 return PreservedAnalyses::all();
238 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000239 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000240};
241
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000242/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000243class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
244 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000245 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000246
247public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000248 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000249 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000250 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000251};
252
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000253/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000254struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000255 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
256 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000257 return PreservedAnalyses::all();
258 }
259 static StringRef name() { return "NoOpCGSCCPass"; }
260};
261
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000262/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000263class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
264 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000265 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000266
267public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000268 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000269 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000270 return Result();
271 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000272 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000273};
274
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000275/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000276struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000277 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000278 return PreservedAnalyses::all();
279 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000280 static StringRef name() { return "NoOpFunctionPass"; }
281};
282
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000283/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000284class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
285 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000286 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000287
288public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000289 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000290 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000291 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000292};
293
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000294/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000295struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000296 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
297 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000298 return PreservedAnalyses::all();
299 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000300 static StringRef name() { return "NoOpLoopPass"; }
301};
302
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000303/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000304class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
305 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000306 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000307
308public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000309 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000310 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
311 return Result();
312 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000313 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000314};
315
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000316AnalysisKey NoOpModuleAnalysis::Key;
317AnalysisKey NoOpCGSCCAnalysis::Key;
318AnalysisKey NoOpFunctionAnalysis::Key;
319AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000320
Chandler Carruth66445382014-01-11 08:16:35 +0000321} // End anonymous namespace.
322
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000323void PassBuilder::invokePeepholeEPCallbacks(
324 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
325 for (auto &C : PeepholeEPCallbacks)
326 C(FPM, Level);
327}
328
Chandler Carruth1ff77242015-03-07 09:02:36 +0000329void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000330#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000331 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000332#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000333
334 for (auto &C : ModuleAnalysisRegistrationCallbacks)
335 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000336}
337
Chandler Carruth1ff77242015-03-07 09:02:36 +0000338void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000339#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000340 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000341#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000342
343 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
344 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000345}
346
Chandler Carruth1ff77242015-03-07 09:02:36 +0000347void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000348#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000349 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000350#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000351
352 for (auto &C : FunctionAnalysisRegistrationCallbacks)
353 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000354}
355
Justin Bognereecc3c82016-02-25 07:23:08 +0000356void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000357#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000358 LAM.registerPass([&] { return CREATE_PASS; });
359#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000360
361 for (auto &C : LoopAnalysisRegistrationCallbacks)
362 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000363}
364
Chandler Carruthe3f50642016-12-22 06:59:15 +0000365FunctionPassManager
366PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000367 ThinLTOPhase Phase,
368 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000369 assert(Level != O0 && "Must request optimizations!");
370 FunctionPassManager FPM(DebugLogging);
371
372 // Form SSA out of local memory accesses after breaking apart aggregates into
373 // scalars.
374 FPM.addPass(SROA());
375
376 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000377 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000378
Davide Italianoc3688312017-06-01 23:08:14 +0000379 // Hoisting of scalars and load expressions.
380 if (EnableGVNHoist)
381 FPM.addPass(GVNHoistPass());
382
Davide Italianobe1b6a92017-06-03 23:18:29 +0000383 // Global value numbering based sinking.
384 if (EnableGVNSink) {
385 FPM.addPass(GVNSinkPass());
386 FPM.addPass(SimplifyCFGPass());
387 }
388
Chandler Carruthe3f50642016-12-22 06:59:15 +0000389 // Speculative execution if the target has divergent branches; otherwise nop.
390 FPM.addPass(SpeculativeExecutionPass());
391
392 // Optimize based on known information about branches, and cleanup afterward.
393 FPM.addPass(JumpThreadingPass());
394 FPM.addPass(CorrelatedValuePropagationPass());
395 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000396 if (Level == O3)
397 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000398 FPM.addPass(InstCombinePass());
399
400 if (!isOptimizingForSize(Level))
401 FPM.addPass(LibCallsShrinkWrapPass());
402
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000403 invokePeepholeEPCallbacks(FPM, Level);
404
Rong Xue1f42452017-10-23 22:21:29 +0000405 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
406 // using the size value profile. Don't perform this when optimizing for size.
407 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
408 !isOptimizingForSize(Level))
409 FPM.addPass(PGOMemOPSizeOpt());
410
Chandler Carruthe3f50642016-12-22 06:59:15 +0000411 FPM.addPass(TailCallElimPass());
412 FPM.addPass(SimplifyCFGPass());
413
414 // Form canonically associated expression trees, and simplify the trees using
415 // basic mathematical properties. For example, this will form (nearly)
416 // minimal multiplication trees.
417 FPM.addPass(ReassociatePass());
418
419 // Add the primary loop simplification pipeline.
420 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000421 // some function passes in between them. These can and should be removed
422 // and/or replaced by scheduling the loop pass equivalents in the correct
423 // positions. But those equivalent passes aren't powerful enough yet.
424 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
425 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
426 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
427 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000428 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
429
Chandler Carruth71fd2702018-05-30 02:46:45 +0000430 // Simplify the loop body. We do this initially to clean up after other loop
431 // passes run, either when iterating on a loop or on inner loops with
432 // implications on the outer loop.
433 LPM1.addPass(LoopInstSimplifyPass());
434 LPM1.addPass(LoopSimplifyCFGPass());
435
Chandler Carruthe3f50642016-12-22 06:59:15 +0000436 // Rotate Loop - disable header duplication at -Oz
437 LPM1.addPass(LoopRotatePass(Level != Oz));
438 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000439 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000440 LPM2.addPass(IndVarSimplifyPass());
441 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000442
443 for (auto &C : LateLoopOptimizationsEPCallbacks)
444 C(LPM2, Level);
445
Chandler Carruth79b733b2017-01-26 23:21:17 +0000446 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000447 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000448 // because it changes IR to makes profile annotation in back compile
449 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000450 if (Phase != ThinLTOPhase::PreLink ||
451 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000452 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000453
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000454 for (auto &C : LoopOptimizerEndEPCallbacks)
455 C(LPM2, Level);
456
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000457 // We provide the opt remark emitter pass for LICM to use. We only need to do
458 // this once as it is immutable.
459 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000460 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000461 FPM.addPass(SimplifyCFGPass());
462 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000463 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000464
465 // Eliminate redundancies.
466 if (Level != O1) {
467 // These passes add substantial compile time so skip them at O1.
468 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000469 if (RunNewGVN)
470 FPM.addPass(NewGVNPass());
471 else
472 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000473 }
474
475 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
476 FPM.addPass(MemCpyOptPass());
477
478 // Sparse conditional constant propagation.
479 // FIXME: It isn't clear why we do this *after* loop passes rather than
480 // before...
481 FPM.addPass(SCCPPass());
482
483 // Delete dead bit computations (instcombine runs after to fold away the dead
484 // computations, and then ADCE will run later to exploit any new DCE
485 // opportunities that creates).
486 FPM.addPass(BDCEPass());
487
488 // Run instcombine after redundancy and dead bit elimination to exploit
489 // opportunities opened up by them.
490 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000491 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000492
493 // Re-consider control flow based optimizations after redundancy elimination,
494 // redo DCE, etc.
495 FPM.addPass(JumpThreadingPass());
496 FPM.addPass(CorrelatedValuePropagationPass());
497 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000498 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000499
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000500 for (auto &C : ScalarOptimizerLateEPCallbacks)
501 C(FPM, Level);
502
Chandler Carruthe3f50642016-12-22 06:59:15 +0000503 // Finally, do an expensive DCE pass to catch all the dead code exposed by
504 // the simplifications and basic cleanup after all the simplifications.
505 FPM.addPass(ADCEPass());
506 FPM.addPass(SimplifyCFGPass());
507 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000508 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000509
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000510 if (EnableCHR && Level == O3 && PGOOpt &&
511 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
512 FPM.addPass(ControlHeightReductionPass());
513
Chandler Carruthe3f50642016-12-22 06:59:15 +0000514 return FPM;
515}
516
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000517void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
518 PassBuilder::OptimizationLevel Level,
519 bool RunProfileGen,
520 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000521 std::string ProfileUseFile,
522 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000523 // Generally running simplification passes and the inliner with an high
524 // threshold results in smaller executables, but there may be cases where
525 // the size grows, so let's be conservative here and skip this simplification
526 // at -Os/Oz.
527 if (!isOptimizingForSize(Level)) {
528 InlineParams IP;
529
530 // In the old pass manager, this is a cl::opt. Should still this be one?
531 IP.DefaultThreshold = 75;
532
533 // FIXME: The hint threshold has the same value used by the regular inliner.
534 // This should probably be lowered after performance testing.
535 // FIXME: this comment is cargo culted from the old pass manager, revisit).
536 IP.HintThreshold = 325;
537
538 CGSCCPassManager CGPipeline(DebugLogging);
539
540 CGPipeline.addPass(InlinerPass(IP));
541
542 FunctionPassManager FPM;
543 FPM.addPass(SROA());
544 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
545 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
546 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000547 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000548
Davide Italiano513dfaa2017-02-13 15:26:22 +0000549 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
550
551 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
552 }
553
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000554 // Delete anything that is now dead to make sure that we don't instrument
555 // dead code. Instrumentation can end up keeping dead code around and
556 // dramatically increase code size.
557 MPM.addPass(GlobalDCEPass());
558
Davide Italiano513dfaa2017-02-13 15:26:22 +0000559 if (RunProfileGen) {
560 MPM.addPass(PGOInstrumentationGen());
561
Xinliang David Lib67530e2017-06-25 00:26:43 +0000562 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000563 FPM.addPass(
564 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000565 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
566
Davide Italiano513dfaa2017-02-13 15:26:22 +0000567 // Add the profile lowering pass.
568 InstrProfOptions Options;
569 if (!ProfileGenFile.empty())
570 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000571 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000572 MPM.addPass(InstrProfiling(Options));
573 }
574
575 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000576 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000577}
578
Easwaran Raman8249fac2017-06-28 13:33:49 +0000579static InlineParams
580getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
581 auto O3 = PassBuilder::O3;
582 unsigned OptLevel = Level > O3 ? 2 : Level;
583 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
584 return getInlineParams(OptLevel, SizeLevel);
585}
586
Chandler Carruthe3f50642016-12-22 06:59:15 +0000587ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000588PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000589 ThinLTOPhase Phase,
590 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000591 ModulePassManager MPM(DebugLogging);
592
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000593 bool HasSampleProfile = PGOOpt && !PGOOpt->SampleProfileFile.empty();
594
595 // In ThinLTO mode, when flattened profile is used, all the available
596 // profile information will be annotated in PreLink phase so there is
597 // no need to load the profile again in PostLink.
598 bool LoadSampleProfile =
599 HasSampleProfile &&
600 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
601
602 // During the ThinLTO backend phase we perform early indirect call promotion
603 // here, before globalopt. Otherwise imported available_externally functions
604 // look unreferenced and are removed. If we are going to load the sample
605 // profile then defer until later.
606 // TODO: See if we can move later and consolidate with the location where
607 // we perform ICP when we are loading a sample profile.
608 // TODO: We pass HasSampleProfile (whether there was a sample profile file
609 // passed to the compile) to the SamplePGO flag of ICP. This is used to
610 // determine whether the new direct calls are annotated with prof metadata.
611 // Ideally this should be determined from whether the IR is annotated with
612 // sample profile, and not whether the a sample profile was provided on the
613 // command line. E.g. for flattened profiles where we will not be reloading
614 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
615 // provide the sample profile file.
616 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
617 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
618
Chandler Carruthe3f50642016-12-22 06:59:15 +0000619 // Do basic inference of function attributes from known properties of system
620 // libraries and other oracles.
621 MPM.addPass(InferFunctionAttrsPass());
622
623 // Create an early function pass manager to cleanup the output of the
624 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000625 FunctionPassManager EarlyFPM(DebugLogging);
626 EarlyFPM.addPass(SimplifyCFGPass());
627 EarlyFPM.addPass(SROA());
628 EarlyFPM.addPass(EarlyCSEPass());
629 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000630 if (Level == O3)
631 EarlyFPM.addPass(CallSiteSplittingPass());
632
Dehao Chen08f88312017-08-07 20:23:20 +0000633 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
634 // to convert bitcast to direct calls so that they can be inlined during the
635 // profile annotation prepration step.
636 // More details about SamplePGO design can be found in:
637 // https://research.google.com/pubs/pub45290.html
638 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000639 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000640 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000641 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000642
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000643 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000644 // Annotate sample profile right after early FPM to ensure freshness of
645 // the debug info.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000646 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
647 PGOOpt->ProfileRemappingFile,
648 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000649 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
650 // for the profile annotation to be accurate in the ThinLTO backend.
651 if (Phase != ThinLTOPhase::PreLink)
652 // We perform early indirect call promotion here, before globalopt.
653 // This is important for the ThinLTO backend phase because otherwise
654 // imported available_externally functions look unreferenced and are
655 // removed.
656 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000657 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000658 }
659
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000660 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000661 // and prior to optimizing globals.
662 // FIXME: This position in the pipeline hasn't been carefully considered in
663 // years, it should be re-analyzed.
664 MPM.addPass(IPSCCPPass());
665
Matthew Simpsoncb585582017-10-25 13:40:08 +0000666 // Attach metadata to indirect call sites indicating the set of functions
667 // they may target at run-time. This should follow IPSCCP.
668 MPM.addPass(CalledValuePropagationPass());
669
Chandler Carruthe3f50642016-12-22 06:59:15 +0000670 // Optimize globals to try and fold them into constants.
671 MPM.addPass(GlobalOptPass());
672
673 // Promote any localized globals to SSA registers.
674 // FIXME: Should this instead by a run of SROA?
675 // FIXME: We should probably run instcombine and simplify-cfg afterward to
676 // delete control flows that are dead once globals have been folded to
677 // constants.
678 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
679
680 // Remove any dead arguments exposed by cleanups and constand folding
681 // globals.
682 MPM.addPass(DeadArgumentEliminationPass());
683
684 // Create a small function pass pipeline to cleanup after all the global
685 // optimizations.
686 FunctionPassManager GlobalCleanupPM(DebugLogging);
687 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000688 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
689
Chandler Carruthe3f50642016-12-22 06:59:15 +0000690 GlobalCleanupPM.addPass(SimplifyCFGPass());
691 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
692
Dehao Chen89d32262017-08-02 01:28:31 +0000693 // Add all the requested passes for instrumentation PGO, if requested.
694 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
695 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
696 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000697 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
698 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000699 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000700 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000701
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000702 // Synthesize function entry counts for non-PGO compilation.
703 if (EnableSyntheticCounts && !PGOOpt)
704 MPM.addPass(SyntheticCountsPropagation());
705
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000706 // Require the GlobalsAA analysis for the module so we can query it within
707 // the CGSCC pipeline.
708 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000709
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000710 // Require the ProfileSummaryAnalysis for the module so we can query it within
711 // the inliner pass.
712 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
713
Chandler Carruthe3f50642016-12-22 06:59:15 +0000714 // Now begin the main postorder CGSCC pipeline.
715 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
716 // manager and trying to emulate its precise behavior. Much of this doesn't
717 // make a lot of sense and we should revisit the core CGSCC structure.
718 CGSCCPassManager MainCGPipeline(DebugLogging);
719
720 // Note: historically, the PruneEH pass was run first to deduce nounwind and
721 // generally clean up exception handling overhead. It isn't clear this is
722 // valuable as the inliner doesn't currently care whether it is inlining an
723 // invoke or a call.
724
725 // Run the inliner first. The theory is that we are walking bottom-up and so
726 // the callees have already been fully optimized, and we want to inline them
727 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000728 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000729 // because it makes profile annotation in the backend inaccurate.
730 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000731 if (Phase == ThinLTOPhase::PreLink &&
732 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000733 IP.HotCallSiteThreshold = 0;
734 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000735
736 // Now deduce any function attributes based in the current code.
737 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
738
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000739 // When at O3 add argument promotion to the pass pipeline.
740 // FIXME: It isn't at all clear why this should be limited to O3.
741 if (Level == O3)
742 MainCGPipeline.addPass(ArgumentPromotionPass());
743
Chandler Carruthe3f50642016-12-22 06:59:15 +0000744 // Lastly, add the core function simplification pipeline nested inside the
745 // CGSCC walk.
746 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000747 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000748
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000749 for (auto &C : CGSCCOptimizerLateEPCallbacks)
750 C(MainCGPipeline, Level);
751
Chandler Carruth719ffe12017-02-12 05:38:04 +0000752 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
753 // to detect when we devirtualize indirect calls and iterate the SCC passes
754 // in that case to try and catch knock-on inlining or function attrs
755 // opportunities. Then we add it to the module pipeline by walking the SCCs
756 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000757 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000758 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000759 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000760
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000761 return MPM;
762}
763
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000764ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
765 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000766 ModulePassManager MPM(DebugLogging);
767
768 // Optimize globals now that the module is fully simplified.
769 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000770 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000771
Xinliang David Li126157c2017-05-22 16:41:57 +0000772 // Run partial inlining pass to partially inline functions that have
773 // large bodies.
774 if (RunPartialInlining)
775 MPM.addPass(PartialInlinerPass());
776
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000777 // Remove avail extern fns and globals definitions since we aren't compiling
778 // an object file for later LTO. For LTO we want to preserve these so they
779 // are eligible for inlining at link-time. Note if they are unreferenced they
780 // will be removed by GlobalDCE later, so this only impacts referenced
781 // available externally globals. Eventually they will be suppressed during
782 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
783 // may make globals referenced by available external functions dead and saves
784 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000785 MPM.addPass(EliminateAvailableExternallyPass());
786
787 // Do RPO function attribute inference across the module to forward-propagate
788 // attributes where applicable.
789 // FIXME: Is this really an optimization rather than a canonicalization?
790 MPM.addPass(ReversePostOrderFunctionAttrsPass());
791
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000792 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000793 // useful as the above will have inlined, DCE'ed, and function-attr
794 // propagated everything. We should at this point have a reasonably minimal
795 // and richly annotated call graph. By computing aliasing and mod/ref
796 // information for all local globals here, the late loop passes and notably
797 // the vectorizer will be able to use them to help recognize vectorizable
798 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000799 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000800
801 FunctionPassManager OptimizePM(DebugLogging);
802 OptimizePM.addPass(Float2IntPass());
803 // FIXME: We need to run some loop optimizations to re-rotate loops after
804 // simplify-cfg and others undo their rotation.
805
806 // Optimize the loop execution. These passes operate on entire loop nests
807 // rather than on each loop in an inside-out manner, and so they are actually
808 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000809
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000810 for (auto &C : VectorizerStartEPCallbacks)
811 C(OptimizePM, Level);
812
Chandler Carrutha95ff382017-01-27 00:50:21 +0000813 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000814 OptimizePM.addPass(
815 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000816
817 // Distribute loops to allow partial vectorization. I.e. isolate dependences
818 // into separate loop that would otherwise inhibit vectorization. This is
819 // currently only performed for loops marked with the metadata
820 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000821 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000822
823 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000824 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000825
Chandler Carruthbaabda92017-01-27 01:32:26 +0000826 // Eliminate loads by forwarding stores from the previous iteration to loads
827 // of the current iteration.
828 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000829
830 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000831 OptimizePM.addPass(InstCombinePass());
832
Chandler Carrutha95ff382017-01-27 00:50:21 +0000833 // Now that we've formed fast to execute loop structures, we do further
834 // optimizations. These are run afterward as they might block doing complex
835 // analyses and transforms such as what are needed for loop vectorization.
836
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000837 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
838 // GVN, loop transforms, and others have already run, so it's now better to
839 // convert to more optimized IR using more aggressive simplify CFG options.
840 // The extra sinking transform can create larger basic blocks, so do this
841 // before SLP vectorization.
842 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
843 forwardSwitchCondToPhi(true).
844 convertSwitchToLookupTable(true).
845 needCanonicalLoops(false).
846 sinkCommonInsts(true)));
847
Chandler Carruthe3f50642016-12-22 06:59:15 +0000848 // Optimize parallel scalar instruction chains into SIMD instructions.
849 OptimizePM.addPass(SLPVectorizerPass());
850
Chandler Carruthe3f50642016-12-22 06:59:15 +0000851 OptimizePM.addPass(InstCombinePass());
852
853 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000854 // execution resources of an out-of-order processor. We also then need to
855 // clean up redundancies and loop invariant code.
856 // FIXME: It would be really good to use a loop-integrated instruction
857 // combiner for cleanup here so that the unrolling and LICM can be pipelined
858 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000859 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
860 if (EnableUnrollAndJam) {
861 OptimizePM.addPass(
862 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
863 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000864 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000865 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000866 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000867 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000868 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000869
870 // Now that we've vectorized and unrolled loops, we may have more refined
871 // alignment information, try to re-derive it here.
872 OptimizePM.addPass(AlignmentFromAssumptionsPass());
873
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000874 // Split out cold code. Splitting is done late to avoid hiding context from
875 // other optimizations and inadvertently regressing performance. The tradeoff
876 // is that this has a higher code size cost than splitting early.
877 if (EnableHotColdSplit && !LTOPreLink)
878 MPM.addPass(HotColdSplittingPass());
879
Chandler Carrutha95ff382017-01-27 00:50:21 +0000880 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
881 // canonicalization pass that enables other optimizations. As a result,
882 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
883 // result too early.
884 OptimizePM.addPass(LoopSinkPass());
885
886 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000887 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000888
Sanjay Patel6fd43912017-09-09 13:38:18 +0000889 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
890 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
891 // flattening of blocks.
892 OptimizePM.addPass(DivRemPairsPass());
893
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000894 // LoopSink (and other loop passes since the last simplifyCFG) might have
895 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
896 OptimizePM.addPass(SimplifyCFGPass());
897
Chandler Carruthc34f7892017-11-28 11:32:31 +0000898 // Optimize PHIs by speculating around them when profitable. Note that this
899 // pass needs to be run after any PRE or similar pass as it is essentially
900 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
901 OptimizePM.addPass(SpeculateAroundPHIsPass());
902
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000903 for (auto &C : OptimizerLastEPCallbacks)
904 C(OptimizePM, Level);
905
Chandler Carrutha95ff382017-01-27 00:50:21 +0000906 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000907 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
908
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000909 MPM.addPass(CGProfilePass());
910
Chandler Carruthe3f50642016-12-22 06:59:15 +0000911 // Now we need to do some global optimization transforms.
912 // FIXME: It would seem like these should come first in the optimization
913 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
914 // ordering here.
915 MPM.addPass(GlobalDCEPass());
916 MPM.addPass(ConstantMergePass());
917
918 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000919}
920
Chandler Carruthe3f50642016-12-22 06:59:15 +0000921ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000922PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000923 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000924 assert(Level != O0 && "Must request optimizations for the default pipeline!");
925
926 ModulePassManager MPM(DebugLogging);
927
928 // Force any function attributes we want the rest of the pipeline to observe.
929 MPM.addPass(ForceFunctionAttrsPass());
930
David Blaikie0c64f5a2018-01-23 01:25:20 +0000931 // Apply module pipeline start EP callback.
932 for (auto &C : PipelineStartEPCallbacks)
933 C(MPM);
934
Dehao Chen08f88312017-08-07 20:23:20 +0000935 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000936 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
937
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000938 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000939 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
940 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000941
942 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000943 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000944
945 return MPM;
946}
947
948ModulePassManager
949PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
950 bool DebugLogging) {
951 assert(Level != O0 && "Must request optimizations for the default pipeline!");
952
953 ModulePassManager MPM(DebugLogging);
954
955 // Force any function attributes we want the rest of the pipeline to observe.
956 MPM.addPass(ForceFunctionAttrsPass());
957
Dehao Chen08f88312017-08-07 20:23:20 +0000958 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000959 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
960
David Blaikie0c64f5a2018-01-23 01:25:20 +0000961 // Apply module pipeline start EP callback.
962 for (auto &C : PipelineStartEPCallbacks)
963 C(MPM);
964
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000965 // If we are planning to perform ThinLTO later, we don't bloat the code with
966 // unrolling/vectorization/... now. Just simplify the module as much as we
967 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000968 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
969 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000970
971 // Run partial inlining pass to partially inline functions that have
972 // large bodies.
973 // FIXME: It isn't clear whether this is really the right place to run this
974 // in ThinLTO. Because there is another canonicalization and simplification
975 // phase that will run after the thin link, running this here ends up with
976 // less information than will be available later and it may grow functions in
977 // ways that aren't beneficial.
978 if (RunPartialInlining)
979 MPM.addPass(PartialInlinerPass());
980
981 // Reduce the size of the IR as much as possible.
982 MPM.addPass(GlobalOptPass());
983
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000984 return MPM;
985}
986
Teresa Johnson28023db2018-07-19 14:51:32 +0000987ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
988 OptimizationLevel Level, bool DebugLogging,
989 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000990 ModulePassManager MPM(DebugLogging);
991
Teresa Johnson28023db2018-07-19 14:51:32 +0000992 if (ImportSummary) {
993 // These passes import type identifier resolutions for whole-program
994 // devirtualization and CFI. They must run early because other passes may
995 // disturb the specific instruction patterns that these passes look for,
996 // creating dependencies on resolutions that may not appear in the summary.
997 //
998 // For example, GVN may transform the pattern assume(type.test) appearing in
999 // two basic blocks into assume(phi(type.test, type.test)), which would
1000 // transform a dependency on a WPD resolution into a dependency on a type
1001 // identifier resolution for CFI.
1002 //
1003 // Also, WPD has access to more precise information than ICP and can
1004 // devirtualize more effectively, so it should operate on the IR first.
1005 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1006 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1007 }
1008
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001009 // Force any function attributes we want the rest of the pipeline to observe.
1010 MPM.addPass(ForceFunctionAttrsPass());
1011
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001012 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001013 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1014 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001015
1016 // Now add the optimization pipeline.
1017 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1018
1019 return MPM;
1020}
1021
1022ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001023PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1024 bool DebugLogging) {
1025 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001026 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001027 return buildPerModuleDefaultPipeline(Level, DebugLogging,
1028 /*LTOPreLink=*/true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001029}
1030
Teresa Johnson28023db2018-07-19 14:51:32 +00001031ModulePassManager
1032PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1033 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001034 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1035 ModulePassManager MPM(DebugLogging);
1036
Xin Tong642c8d32018-11-15 18:06:42 +00001037 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1038 // Load sample profile before running the LTO optimization pipeline.
1039 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1040 PGOOpt->ProfileRemappingFile,
1041 false /* ThinLTOPhase::PreLink */));
1042 }
1043
Davide Italiano089a9122017-01-24 00:57:39 +00001044 // Remove unused virtual tables to improve the quality of code generated by
1045 // whole-program devirtualization and bitset lowering.
1046 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001047
Davide Italiano089a9122017-01-24 00:57:39 +00001048 // Force any function attributes we want the rest of the pipeline to observe.
1049 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001050
Davide Italiano089a9122017-01-24 00:57:39 +00001051 // Do basic inference of function attributes from known properties of system
1052 // libraries and other oracles.
1053 MPM.addPass(InferFunctionAttrsPass());
1054
1055 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001056 FunctionPassManager EarlyFPM(DebugLogging);
1057 EarlyFPM.addPass(CallSiteSplittingPass());
1058 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1059
Davide Italiano089a9122017-01-24 00:57:39 +00001060 // Indirect call promotion. This should promote all the targets that are
1061 // left by the earlier promotion pass that promotes intra-module targets.
1062 // This two-step promotion is to save the compile time. For LTO, it should
1063 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001064 MPM.addPass(PGOIndirectCallPromotion(
1065 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001066 // Propagate constants at call sites into the functions they call. This
1067 // opens opportunities for globalopt (and inlining) by substituting function
1068 // pointers passed as arguments to direct uses of functions.
1069 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001070
1071 // Attach metadata to indirect call sites indicating the set of functions
1072 // they may target at run-time. This should follow IPSCCP.
1073 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001074 }
1075
1076 // Now deduce any function attributes based in the current code.
1077 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1078 PostOrderFunctionAttrsPass()));
1079
1080 // Do RPO function attribute inference across the module to forward-propagate
1081 // attributes where applicable.
1082 // FIXME: Is this really an optimization rather than a canonicalization?
1083 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1084
1085 // Use inragne annotations on GEP indices to split globals where beneficial.
1086 MPM.addPass(GlobalSplitPass());
1087
1088 // Run whole program optimization of virtual call when the list of callees
1089 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001090 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001091
1092 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001093 if (Level == 1) {
1094 // The LowerTypeTestsPass needs to run to lower type metadata and the
1095 // type.test intrinsics. The pass does nothing if CFI is disabled.
1096 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001097 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001098 }
Davide Italiano089a9122017-01-24 00:57:39 +00001099
1100 // Optimize globals to try and fold them into constants.
1101 MPM.addPass(GlobalOptPass());
1102
1103 // Promote any localized globals to SSA registers.
1104 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1105
1106 // Linking modules together can lead to duplicate global constant, only
1107 // keep one copy of each constant.
1108 MPM.addPass(ConstantMergePass());
1109
1110 // Remove unused arguments from functions.
1111 MPM.addPass(DeadArgumentEliminationPass());
1112
1113 // Reduce the code after globalopt and ipsccp. Both can open up significant
1114 // simplification opportunities, and both can propagate functions through
1115 // function pointers. When this happens, we often have to resolve varargs
1116 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001117 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001118 if (Level == O3)
1119 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001120 PeepholeFPM.addPass(InstCombinePass());
1121 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1122
1123 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001124
1125 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1126 // generally clean up exception handling overhead. It isn't clear this is
1127 // valuable as the inliner doesn't currently care whether it is inlining an
1128 // invoke or a call.
1129 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001130 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1131 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001132
1133 // Optimize globals again after we ran the inliner.
1134 MPM.addPass(GlobalOptPass());
1135
1136 // Garbage collect dead functions.
1137 // FIXME: Add ArgumentPromotion pass after once it's ported.
1138 MPM.addPass(GlobalDCEPass());
1139
1140 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001141 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001142 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001143 invokePeepholeEPCallbacks(FPM, Level);
1144
Davide Italiano089a9122017-01-24 00:57:39 +00001145 FPM.addPass(JumpThreadingPass());
1146
1147 // Break up allocas
1148 FPM.addPass(SROA());
1149
1150 // Run a few AA driver optimizations here and now to cleanup the code.
1151 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1152
1153 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1154 PostOrderFunctionAttrsPass()));
1155 // FIXME: here we run IP alias analysis in the legacy PM.
1156
1157 FunctionPassManager MainFPM;
1158
1159 // FIXME: once we fix LoopPass Manager, add LICM here.
1160 // FIXME: once we provide support for enabling MLSM, add it here.
1161 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001162 if (RunNewGVN)
1163 MainFPM.addPass(NewGVNPass());
1164 else
1165 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001166
1167 // Remove dead memcpy()'s.
1168 MainFPM.addPass(MemCpyOptPass());
1169
1170 // Nuke dead stores.
1171 MainFPM.addPass(DSEPass());
1172
1173 // FIXME: at this point, we run a bunch of loop passes:
1174 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1175 // loopVectorize. Enable them once the remaining issue with LPM
1176 // are sorted out.
1177
1178 MainFPM.addPass(InstCombinePass());
1179 MainFPM.addPass(SimplifyCFGPass());
1180 MainFPM.addPass(SCCPPass());
1181 MainFPM.addPass(InstCombinePass());
1182 MainFPM.addPass(BDCEPass());
1183
1184 // FIXME: We may want to run SLPVectorizer here.
1185 // After vectorization, assume intrinsics may tell us more
1186 // about pointer alignments.
1187#if 0
1188 MainFPM.add(AlignmentFromAssumptionsPass());
1189#endif
1190
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001191 // FIXME: Conditionally run LoadCombine here, after it's ported
1192 // (in case we still have this pass, given its questionable usefulness).
1193
Davide Italiano089a9122017-01-24 00:57:39 +00001194 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001195 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001196 MainFPM.addPass(JumpThreadingPass());
1197 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1198
1199 // Create a function that performs CFI checks for cross-DSO calls with
1200 // targets in the current module.
1201 MPM.addPass(CrossDSOCFIPass());
1202
1203 // Lower type metadata and the type.test intrinsic. This pass supports
1204 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1205 // to be run at link time if CFI is enabled. This pass does nothing if
1206 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001207 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001208
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001209 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1210 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1211 if (EnableHotColdSplit)
1212 MPM.addPass(HotColdSplittingPass());
1213
Davide Italiano089a9122017-01-24 00:57:39 +00001214 // Add late LTO optimization passes.
1215 // Delete basic blocks, which optimization passes may have killed.
1216 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1217
1218 // Drop bodies of available eternally objects to improve GlobalDCE.
1219 MPM.addPass(EliminateAvailableExternallyPass());
1220
1221 // Now that we have optimized the program, discard unreachable functions.
1222 MPM.addPass(GlobalDCEPass());
1223
1224 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001225 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001226}
1227
Chandler Carruth060ad612016-12-23 20:38:19 +00001228AAManager PassBuilder::buildDefaultAAPipeline() {
1229 AAManager AA;
1230
1231 // The order in which these are registered determines their priority when
1232 // being queried.
1233
1234 // First we register the basic alias analysis that provides the majority of
1235 // per-function local AA logic. This is a stateless, on-demand local set of
1236 // AA techniques.
1237 AA.registerFunctionAnalysis<BasicAA>();
1238
1239 // Next we query fast, specialized alias analyses that wrap IR-embedded
1240 // information about aliasing.
1241 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1242 AA.registerFunctionAnalysis<TypeBasedAA>();
1243
1244 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001245 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1246 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001247 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001248 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001249
1250 return AA;
1251}
1252
Chandler Carruth241bf242016-08-03 07:44:48 +00001253static Optional<int> parseRepeatPassName(StringRef Name) {
1254 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1255 return None;
1256 int Count;
1257 if (Name.getAsInteger(0, Count) || Count <= 0)
1258 return None;
1259 return Count;
1260}
1261
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001262static Optional<int> parseDevirtPassName(StringRef Name) {
1263 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1264 return None;
1265 int Count;
1266 if (Name.getAsInteger(0, Count) || Count <= 0)
1267 return None;
1268 return Count;
1269}
1270
Fedor Sergeevb7871402019-01-10 10:01:53 +00001271static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1272 if (!Name.consume_front(PassName))
1273 return false;
1274 // normal pass name w/o parameters == default parameters
1275 if (Name.empty())
1276 return true;
1277 return Name.startswith("<") && Name.endswith(">");
1278}
1279
1280namespace {
1281
1282/// This performs customized parsing of pass name with parameters.
1283///
1284/// We do not need parametrization of passes in textual pipeline very often,
1285/// yet on a rare occasion ability to specify parameters right there can be
1286/// useful.
1287///
1288/// \p Name - parameterized specification of a pass from a textual pipeline
1289/// is a string in a form of :
1290/// PassName '<' parameter-list '>'
1291///
1292/// Parameter list is being parsed by the parser callable argument, \p Parser,
1293/// It takes a string-ref of parameters and returns either StringError or a
1294/// parameter list in a form of a custom parameters type, all wrapped into
1295/// Expected<> template class.
1296///
1297template <typename ParametersParseCallableT>
1298auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1299 StringRef PassName) -> decltype(Parser(StringRef{})) {
1300 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1301
1302 StringRef Params = Name;
1303 if (!Params.consume_front(PassName)) {
1304 assert(false &&
1305 "unable to strip pass name from parametrized pass specification");
1306 }
1307 if (Params.empty())
1308 return ParametersT{};
1309 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1310 assert(false && "invalid format for parametrized pass name");
1311 }
1312
1313 Expected<ParametersT> Result = Parser(Params);
1314 assert((Result || Result.template errorIsA<StringError>()) &&
1315 "Pass parameter parser can only return StringErrors.");
1316 return std::move(Result);
1317}
1318
1319/// Parser of parameters for LoopUnroll pass.
1320Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1321 LoopUnrollOptions UnrollOpts;
1322 while (!Params.empty()) {
1323 StringRef ParamName;
1324 std::tie(ParamName, Params) = Params.split(';');
1325 int OptLevel = StringSwitch<int>(ParamName)
1326 .Case("O0", 0)
1327 .Case("O1", 1)
1328 .Case("O2", 2)
1329 .Case("O3", 3)
1330 .Default(-1);
1331 if (OptLevel >= 0) {
1332 UnrollOpts.setOptLevel(OptLevel);
1333 continue;
1334 }
1335
1336 bool Enable = !ParamName.consume_front("no-");
1337 if (ParamName == "partial") {
1338 UnrollOpts.setPartial(Enable);
1339 } else if (ParamName == "peeling") {
1340 UnrollOpts.setPeeling(Enable);
1341 } else if (ParamName == "runtime") {
1342 UnrollOpts.setRuntime(Enable);
1343 } else if (ParamName == "upperbound") {
1344 UnrollOpts.setUpperBound(Enable);
1345 } else {
1346 return make_error<StringError>(
1347 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1348 inconvertibleErrorCode());
1349 }
1350 }
1351 return UnrollOpts;
1352}
1353
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001354Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1355 MemorySanitizerOptions Result;
1356 while (!Params.empty()) {
1357 StringRef ParamName;
1358 std::tie(ParamName, Params) = Params.split(';');
1359
1360 if (ParamName == "recover") {
1361 Result.Recover = true;
1362 } else if (ParamName == "kernel") {
1363 Result.Kernel = true;
1364 } else if (ParamName.consume_front("track-origins=")) {
1365 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1366 return make_error<StringError>(
1367 formatv("invalid argument to MemorySanitizer pass track-origins "
1368 "parameter: '{0}' ",
1369 ParamName)
1370 .str(),
1371 inconvertibleErrorCode());
1372 } else {
1373 return make_error<StringError>(
1374 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1375 .str(),
1376 inconvertibleErrorCode());
1377 }
1378 }
1379 return Result;
1380}
1381
Fedor Sergeevb7871402019-01-10 10:01:53 +00001382} // namespace
1383
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001384/// Tests whether a pass name starts with a valid prefix for a default pipeline
1385/// alias.
1386static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1387 return Name.startswith("default") || Name.startswith("thinlto") ||
1388 Name.startswith("lto");
1389}
1390
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001391/// Tests whether registered callbacks will accept a given pass name.
1392///
1393/// When parsing a pipeline text, the type of the outermost pipeline may be
1394/// omitted, in which case the type is automatically determined from the first
1395/// pass name in the text. This may be a name that is handled through one of the
1396/// callbacks. We check this through the oridinary parsing callbacks by setting
1397/// up a dummy PassManager in order to not force the client to also handle this
1398/// type of query.
1399template <typename PassManagerT, typename CallbacksT>
1400static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1401 if (!Callbacks.empty()) {
1402 PassManagerT DummyPM;
1403 for (auto &CB : Callbacks)
1404 if (CB(Name, DummyPM, {}))
1405 return true;
1406 }
1407 return false;
1408}
1409
1410template <typename CallbacksT>
1411static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001412 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001413 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001414 return DefaultAliasRegex.match(Name);
1415
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001416 // Explicitly handle pass manager names.
1417 if (Name == "module")
1418 return true;
1419 if (Name == "cgscc")
1420 return true;
1421 if (Name == "function")
1422 return true;
1423
Chandler Carruth241bf242016-08-03 07:44:48 +00001424 // Explicitly handle custom-parsed pass names.
1425 if (parseRepeatPassName(Name))
1426 return true;
1427
Chandler Carruth74a8a222016-06-17 07:15:29 +00001428#define MODULE_PASS(NAME, CREATE_PASS) \
1429 if (Name == NAME) \
1430 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001431#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001432 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001433 return true;
1434#include "PassRegistry.def"
1435
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001436 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001437}
1438
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001439template <typename CallbacksT>
1440static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001441 // Explicitly handle pass manager names.
1442 if (Name == "cgscc")
1443 return true;
1444 if (Name == "function")
1445 return true;
1446
Chandler Carruth241bf242016-08-03 07:44:48 +00001447 // Explicitly handle custom-parsed pass names.
1448 if (parseRepeatPassName(Name))
1449 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001450 if (parseDevirtPassName(Name))
1451 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001452
Chandler Carruth74a8a222016-06-17 07:15:29 +00001453#define CGSCC_PASS(NAME, CREATE_PASS) \
1454 if (Name == NAME) \
1455 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001456#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001457 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001458 return true;
1459#include "PassRegistry.def"
1460
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001461 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001462}
1463
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001464template <typename CallbacksT>
1465static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001466 // Explicitly handle pass manager names.
1467 if (Name == "function")
1468 return true;
1469 if (Name == "loop")
1470 return true;
1471
Chandler Carruth241bf242016-08-03 07:44:48 +00001472 // Explicitly handle custom-parsed pass names.
1473 if (parseRepeatPassName(Name))
1474 return true;
1475
Chandler Carruth74a8a222016-06-17 07:15:29 +00001476#define FUNCTION_PASS(NAME, CREATE_PASS) \
1477 if (Name == NAME) \
1478 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001479#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1480 if (checkParametrizedPassName(Name, NAME)) \
1481 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001482#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001483 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001484 return true;
1485#include "PassRegistry.def"
1486
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001487 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001488}
1489
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001490template <typename CallbacksT>
1491static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001492 // Explicitly handle pass manager names.
1493 if (Name == "loop")
1494 return true;
1495
Chandler Carruth241bf242016-08-03 07:44:48 +00001496 // Explicitly handle custom-parsed pass names.
1497 if (parseRepeatPassName(Name))
1498 return true;
1499
Chandler Carruth74a8a222016-06-17 07:15:29 +00001500#define LOOP_PASS(NAME, CREATE_PASS) \
1501 if (Name == NAME) \
1502 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001503#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1504 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1505 return true;
1506#include "PassRegistry.def"
1507
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001508 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001509}
1510
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001511Optional<std::vector<PassBuilder::PipelineElement>>
1512PassBuilder::parsePipelineText(StringRef Text) {
1513 std::vector<PipelineElement> ResultPipeline;
1514
1515 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1516 &ResultPipeline};
1517 for (;;) {
1518 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1519 size_t Pos = Text.find_first_of(",()");
1520 Pipeline.push_back({Text.substr(0, Pos), {}});
1521
1522 // If we have a single terminating name, we're done.
1523 if (Pos == Text.npos)
1524 break;
1525
1526 char Sep = Text[Pos];
1527 Text = Text.substr(Pos + 1);
1528 if (Sep == ',')
1529 // Just a name ending in a comma, continue.
1530 continue;
1531
1532 if (Sep == '(') {
1533 // Push the inner pipeline onto the stack to continue processing.
1534 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1535 continue;
1536 }
1537
1538 assert(Sep == ')' && "Bogus separator!");
1539 // When handling the close parenthesis, we greedily consume them to avoid
1540 // empty strings in the pipeline.
1541 do {
1542 // If we try to pop the outer pipeline we have unbalanced parentheses.
1543 if (PipelineStack.size() == 1)
1544 return None;
1545
1546 PipelineStack.pop_back();
1547 } while (Text.consume_front(")"));
1548
1549 // Check if we've finished parsing.
1550 if (Text.empty())
1551 break;
1552
1553 // Otherwise, the end of an inner pipeline always has to be followed by
1554 // a comma, and then we can continue.
1555 if (!Text.consume_front(","))
1556 return None;
1557 }
1558
1559 if (PipelineStack.size() > 1)
1560 // Unbalanced paretheses.
1561 return None;
1562
1563 assert(PipelineStack.back() == &ResultPipeline &&
1564 "Wrong pipeline at the bottom of the stack!");
1565 return {std::move(ResultPipeline)};
1566}
1567
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001568Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1569 const PipelineElement &E,
1570 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001571 auto &Name = E.Name;
1572 auto &InnerPipeline = E.InnerPipeline;
1573
1574 // First handle complex passes like the pass managers which carry pipelines.
1575 if (!InnerPipeline.empty()) {
1576 if (Name == "module") {
1577 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001578 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1579 VerifyEachPass, DebugLogging))
1580 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001581 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001582 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001583 }
1584 if (Name == "cgscc") {
1585 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001586 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1587 DebugLogging))
1588 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001589 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001590 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001591 }
1592 if (Name == "function") {
1593 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001594 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1595 VerifyEachPass, DebugLogging))
1596 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001597 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001598 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001599 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001600 if (auto Count = parseRepeatPassName(Name)) {
1601 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001602 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1603 VerifyEachPass, DebugLogging))
1604 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001605 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001606 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001607 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001608
1609 for (auto &C : ModulePipelineParsingCallbacks)
1610 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001611 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001612
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001613 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001614 return make_error<StringError>(
1615 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1616 inconvertibleErrorCode());
1617 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001618 }
1619
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001620 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001621 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001622 SmallVector<StringRef, 3> Matches;
1623 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001624 return make_error<StringError>(
1625 formatv("unknown default pipeline alias '{0}'", Name).str(),
1626 inconvertibleErrorCode());
1627
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001628 assert(Matches.size() == 3 && "Must capture two matched strings!");
1629
Jordan Rosef85a95f2016-07-25 18:34:51 +00001630 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001631 .Case("O0", O0)
1632 .Case("O1", O1)
1633 .Case("O2", O2)
1634 .Case("O3", O3)
1635 .Case("Os", Os)
1636 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001637 if (L == O0)
1638 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001639 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001640
1641 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001642 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001643 } else if (Matches[1] == "thinlto-pre-link") {
1644 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1645 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001646 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001647 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001648 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001649 } else {
1650 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001651 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001652 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001653 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001654 }
1655
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001656 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001657#define MODULE_PASS(NAME, CREATE_PASS) \
1658 if (Name == NAME) { \
1659 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001660 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001661 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001662#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1663 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001664 MPM.addPass( \
1665 RequireAnalysisPass< \
1666 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001667 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001668 } \
1669 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001670 MPM.addPass(InvalidateAnalysisPass< \
1671 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001672 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001673 }
1674#include "PassRegistry.def"
1675
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001676 for (auto &C : ModulePipelineParsingCallbacks)
1677 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001678 return Error::success();
1679 return make_error<StringError>(
1680 formatv("unknown module pass '{0}'", Name).str(),
1681 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001682}
1683
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001684Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1685 const PipelineElement &E, bool VerifyEachPass,
1686 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001687 auto &Name = E.Name;
1688 auto &InnerPipeline = E.InnerPipeline;
1689
1690 // First handle complex passes like the pass managers which carry pipelines.
1691 if (!InnerPipeline.empty()) {
1692 if (Name == "cgscc") {
1693 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001694 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1695 VerifyEachPass, DebugLogging))
1696 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001697 // Add the nested pass manager with the appropriate adaptor.
1698 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001699 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001700 }
1701 if (Name == "function") {
1702 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001703 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1704 VerifyEachPass, DebugLogging))
1705 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001706 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001707 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001708 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001709 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001710 if (auto Count = parseRepeatPassName(Name)) {
1711 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001712 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1713 VerifyEachPass, DebugLogging))
1714 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001715 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001716 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001717 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001718 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1719 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001720 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1721 VerifyEachPass, DebugLogging))
1722 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001723 CGPM.addPass(
1724 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001725 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001726 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001727
1728 for (auto &C : CGSCCPipelineParsingCallbacks)
1729 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001730 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001731
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001732 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001733 return make_error<StringError>(
1734 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1735 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001736 }
1737
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001738// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001739#define CGSCC_PASS(NAME, CREATE_PASS) \
1740 if (Name == NAME) { \
1741 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001742 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001743 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001744#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1745 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001746 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001747 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001748 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1749 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001750 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001751 } \
1752 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001753 CGPM.addPass(InvalidateAnalysisPass< \
1754 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001755 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001756 }
1757#include "PassRegistry.def"
1758
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001759 for (auto &C : CGSCCPipelineParsingCallbacks)
1760 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001761 return Error::success();
1762 return make_error<StringError>(
1763 formatv("unknown cgscc pass '{0}'", Name).str(),
1764 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001765}
1766
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001767Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1768 const PipelineElement &E,
1769 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001770 auto &Name = E.Name;
1771 auto &InnerPipeline = E.InnerPipeline;
1772
1773 // First handle complex passes like the pass managers which carry pipelines.
1774 if (!InnerPipeline.empty()) {
1775 if (Name == "function") {
1776 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001777 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1778 VerifyEachPass, DebugLogging))
1779 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001780 // Add the nested pass manager with the appropriate adaptor.
1781 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001782 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001783 }
1784 if (Name == "loop") {
1785 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001786 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1787 DebugLogging))
1788 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001789 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001790 FPM.addPass(
1791 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001792 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001793 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001794 if (auto Count = parseRepeatPassName(Name)) {
1795 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001796 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1797 VerifyEachPass, DebugLogging))
1798 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001799 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001800 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001801 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001802
1803 for (auto &C : FunctionPipelineParsingCallbacks)
1804 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001805 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001806
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001807 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001808 return make_error<StringError>(
1809 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1810 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001811 }
1812
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001813// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001814#define FUNCTION_PASS(NAME, CREATE_PASS) \
1815 if (Name == NAME) { \
1816 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001817 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001818 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001819#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1820 if (checkParametrizedPassName(Name, NAME)) { \
1821 auto Params = parsePassParameters(PARSER, Name, NAME); \
1822 if (!Params) \
1823 return Params.takeError(); \
1824 FPM.addPass(CREATE_PASS(Params.get())); \
1825 return Error::success(); \
1826 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001827#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1828 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001829 FPM.addPass( \
1830 RequireAnalysisPass< \
1831 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001832 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001833 } \
1834 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001835 FPM.addPass(InvalidateAnalysisPass< \
1836 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001837 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001838 }
1839#include "PassRegistry.def"
1840
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001841 for (auto &C : FunctionPipelineParsingCallbacks)
1842 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001843 return Error::success();
1844 return make_error<StringError>(
1845 formatv("unknown function pass '{0}'", Name).str(),
1846 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001847}
1848
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001849Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1850 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001851 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001852 auto &InnerPipeline = E.InnerPipeline;
1853
1854 // First handle complex passes like the pass managers which carry pipelines.
1855 if (!InnerPipeline.empty()) {
1856 if (Name == "loop") {
1857 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001858 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1859 VerifyEachPass, DebugLogging))
1860 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001861 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001862 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001863 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001864 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001865 if (auto Count = parseRepeatPassName(Name)) {
1866 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001867 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1868 VerifyEachPass, DebugLogging))
1869 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001870 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001871 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001872 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001873
1874 for (auto &C : LoopPipelineParsingCallbacks)
1875 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001876 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001877
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001878 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001879 return make_error<StringError>(
1880 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1881 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001882 }
1883
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001884// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001885#define LOOP_PASS(NAME, CREATE_PASS) \
1886 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001887 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001888 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001889 }
1890#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1891 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001892 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001893 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1894 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1895 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001896 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001897 } \
1898 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001899 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001900 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001901 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001902 }
1903#include "PassRegistry.def"
1904
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001905 for (auto &C : LoopPipelineParsingCallbacks)
1906 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001907 return Error::success();
1908 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1909 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001910}
1911
Chandler Carruthedf59962016-02-18 09:45:17 +00001912bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001913#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1914 if (Name == NAME) { \
1915 AA.registerModuleAnalysis< \
1916 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1917 return true; \
1918 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001919#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1920 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001921 AA.registerFunctionAnalysis< \
1922 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001923 return true; \
1924 }
1925#include "PassRegistry.def"
1926
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001927 for (auto &C : AAParsingCallbacks)
1928 if (C(Name, AA))
1929 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001930 return false;
1931}
1932
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001933Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001934 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001935 bool VerifyEachPass,
1936 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001937 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001938 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1939 return Err;
1940 // FIXME: No verifier support for Loop passes!
1941 }
1942 return Error::success();
1943}
1944
1945Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1946 ArrayRef<PipelineElement> Pipeline,
1947 bool VerifyEachPass,
1948 bool DebugLogging) {
1949 for (const auto &Element : Pipeline) {
1950 if (auto Err =
1951 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1952 return Err;
1953 if (VerifyEachPass)
1954 FPM.addPass(VerifierPass());
1955 }
1956 return Error::success();
1957}
1958
1959Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1960 ArrayRef<PipelineElement> Pipeline,
1961 bool VerifyEachPass,
1962 bool DebugLogging) {
1963 for (const auto &Element : Pipeline) {
1964 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1965 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001966 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001967 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001968 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001969}
1970
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001971void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1972 FunctionAnalysisManager &FAM,
1973 CGSCCAnalysisManager &CGAM,
1974 ModuleAnalysisManager &MAM) {
1975 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1976 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001977 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1978 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1979 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1980 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1981 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1982}
1983
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001984Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1985 ArrayRef<PipelineElement> Pipeline,
1986 bool VerifyEachPass,
1987 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001988 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001989 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1990 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001991 if (VerifyEachPass)
1992 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001993 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001994 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001995}
1996
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001997// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001998// FIXME: Should this routine accept a TargetMachine or require the caller to
1999// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002000Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2001 StringRef PipelineText,
2002 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002003 auto Pipeline = parsePipelineText(PipelineText);
2004 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002005 return make_error<StringError>(
2006 formatv("invalid pipeline '{0}'", PipelineText).str(),
2007 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002008
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002009 // If the first name isn't at the module layer, wrap the pipeline up
2010 // automatically.
2011 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002012
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002013 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2014 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002015 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002016 } else if (isFunctionPassName(FirstName,
2017 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002018 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002019 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002020 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002021 } else {
2022 for (auto &C : TopLevelPipelineParsingCallbacks)
2023 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002024 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002025
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002026 // Unknown pass or pipeline name!
2027 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2028 return make_error<StringError>(
2029 formatv("unknown {0} name '{1}'",
2030 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2031 .str(),
2032 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002033 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002034 }
2035
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002036 if (auto Err =
2037 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2038 return Err;
2039 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002040}
Chandler Carruthedf59962016-02-18 09:45:17 +00002041
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002042// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002043Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2044 StringRef PipelineText,
2045 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002046 auto Pipeline = parsePipelineText(PipelineText);
2047 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002048 return make_error<StringError>(
2049 formatv("invalid pipeline '{0}'", PipelineText).str(),
2050 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002051
2052 StringRef FirstName = Pipeline->front().Name;
2053 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002054 return make_error<StringError>(
2055 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2056 PipelineText)
2057 .str(),
2058 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002059
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002060 if (auto Err =
2061 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2062 return Err;
2063 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002064}
2065
2066// Primary pass pipeline description parsing routine for a \c
2067// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002068Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2069 StringRef PipelineText,
2070 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002071 auto Pipeline = parsePipelineText(PipelineText);
2072 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002073 return make_error<StringError>(
2074 formatv("invalid pipeline '{0}'", PipelineText).str(),
2075 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002076
2077 StringRef FirstName = Pipeline->front().Name;
2078 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002079 return make_error<StringError>(
2080 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2081 PipelineText)
2082 .str(),
2083 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002084
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002085 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2086 DebugLogging))
2087 return Err;
2088 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002089}
2090
2091// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002092Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2093 StringRef PipelineText,
2094 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002095 auto Pipeline = parsePipelineText(PipelineText);
2096 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002097 return make_error<StringError>(
2098 formatv("invalid pipeline '{0}'", PipelineText).str(),
2099 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002100
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002101 if (auto Err =
2102 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2103 return Err;
2104
2105 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002106}
2107
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002108Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002109 // If the pipeline just consists of the word 'default' just replace the AA
2110 // manager with our default one.
2111 if (PipelineText == "default") {
2112 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002113 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002114 }
2115
Chandler Carruthedf59962016-02-18 09:45:17 +00002116 while (!PipelineText.empty()) {
2117 StringRef Name;
2118 std::tie(Name, PipelineText) = PipelineText.split(',');
2119 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002120 return make_error<StringError>(
2121 formatv("unknown alias analysis name '{0}'", Name).str(),
2122 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002123 }
2124
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002125 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002126}