blob: e1d0a47fb6d185a20ee9e810751a7bbb5aef45a2 [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//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10///
Chandler Carruth1ff77242015-03-07 09:02:36 +000011/// This file provides the implementation of the PassBuilder based on our
12/// static pass registry as well as related functionality. It also provides
13/// helpers to aid in analyzing, debugging, and testing passes and pass
14/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000015///
16//===----------------------------------------------------------------------===//
17
Chandler Carruth1ff77242015-03-07 09:02:36 +000018#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000019#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000020#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000021#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000022#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000023#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000025#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000026#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000027#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
28#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000029#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000030#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000031#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000032#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000033#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000034#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000035#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000036#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000037#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000038#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000039#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000040#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000041#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000042#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000043#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000044#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000045#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000046#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000047#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000048#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000049#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000050#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000051#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000052#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000053#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000054#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000055#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000056#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000057#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000058#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000059#include "llvm/IR/PassManager.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000091#include "llvm/Transforms/Instrumentation.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"
Justin Bogner19b67992015-10-30 23:13:18 +000099#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000100#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000101#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000102#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000103#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000104#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000105#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000106#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000107#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000108#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000109#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000110#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000111#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000112#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000113#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000114#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000115#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000116#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000117#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000118#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000119#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000120#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000121#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000122#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000123#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000124#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000125#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000126#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000127#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000128#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000129#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000130#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000131#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000132#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000133#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000134#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000135#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000136#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000137#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000138#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000139#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000140#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000141#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000142#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000143#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000144#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000145#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000146#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000147#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000148#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000149#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000150#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000151#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000152#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000153#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000154#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000155#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000156#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000157#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000158#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000159#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000160#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000161#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000162#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000163#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000164#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000165#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000166#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000167#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000168
Chandler Carruth66445382014-01-11 08:16:35 +0000169using namespace llvm;
170
Chandler Carruth719ffe12017-02-12 05:38:04 +0000171static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
172 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000173static cl::opt<bool>
174 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
175 cl::Hidden, cl::ZeroOrMore,
176 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000177
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000178static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000179 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000180 cl::Hidden, cl::ZeroOrMore,
181 cl::desc("Run NewGVN instead of GVN"));
182
Geoff Berry3cca1da2017-06-10 15:20:03 +0000183static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000184 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
185 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000186
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000187static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000188 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
189 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000190
Davide Italianobe1b6a92017-06-03 23:18:29 +0000191static cl::opt<bool> EnableGVNSink(
192 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
193 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
194
David Green963401d2018-07-01 12:47:30 +0000195static cl::opt<bool> EnableUnrollAndJam(
196 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
197 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
198
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000199static cl::opt<bool> EnableSyntheticCounts(
200 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
201 cl::desc("Run synthetic function entry count generation "
202 "pass"));
203
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000204static Regex DefaultAliasRegex(
205 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000206
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000207static cl::opt<bool>
208 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
209 cl::desc("Enable control height reduction optimization (CHR)"));
210
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000211extern cl::opt<bool> EnableHotColdSplit;
212
Chandler Carruthe3f50642016-12-22 06:59:15 +0000213static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
214 switch (Level) {
215 case PassBuilder::O0:
216 case PassBuilder::O1:
217 case PassBuilder::O2:
218 case PassBuilder::O3:
219 return false;
220
221 case PassBuilder::Os:
222 case PassBuilder::Oz:
223 return true;
224 }
225 llvm_unreachable("Invalid optimization level!");
226}
227
Chandler Carruth66445382014-01-11 08:16:35 +0000228namespace {
229
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000230/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000231struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000232 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000233 return PreservedAnalyses::all();
234 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000235 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000236};
237
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000238/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000239class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
240 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000241 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000242
243public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000244 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000245 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000246 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000247};
248
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000249/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000250struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000251 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
252 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000253 return PreservedAnalyses::all();
254 }
255 static StringRef name() { return "NoOpCGSCCPass"; }
256};
257
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000258/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000259class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
260 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000261 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000262
263public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000264 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000265 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000266 return Result();
267 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000268 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000269};
270
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000271/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000272struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000273 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000274 return PreservedAnalyses::all();
275 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000276 static StringRef name() { return "NoOpFunctionPass"; }
277};
278
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000279/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000280class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
281 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000282 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000283
284public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000285 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000286 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000287 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000288};
289
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000290/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000291struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000292 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
293 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000294 return PreservedAnalyses::all();
295 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000296 static StringRef name() { return "NoOpLoopPass"; }
297};
298
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000299/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000300class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
301 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000302 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000303
304public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000305 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000306 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
307 return Result();
308 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000309 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000310};
311
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000312AnalysisKey NoOpModuleAnalysis::Key;
313AnalysisKey NoOpCGSCCAnalysis::Key;
314AnalysisKey NoOpFunctionAnalysis::Key;
315AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000316
Chandler Carruth66445382014-01-11 08:16:35 +0000317} // End anonymous namespace.
318
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000319void PassBuilder::invokePeepholeEPCallbacks(
320 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
321 for (auto &C : PeepholeEPCallbacks)
322 C(FPM, Level);
323}
324
Chandler Carruth1ff77242015-03-07 09:02:36 +0000325void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000326#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000327 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000328#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000329
330 for (auto &C : ModuleAnalysisRegistrationCallbacks)
331 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000332}
333
Chandler Carruth1ff77242015-03-07 09:02:36 +0000334void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000335#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000336 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000337#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000338
339 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
340 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000341}
342
Chandler Carruth1ff77242015-03-07 09:02:36 +0000343void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000344#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000345 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000346#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000347
348 for (auto &C : FunctionAnalysisRegistrationCallbacks)
349 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000350}
351
Justin Bognereecc3c82016-02-25 07:23:08 +0000352void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000353#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000354 LAM.registerPass([&] { return CREATE_PASS; });
355#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000356
357 for (auto &C : LoopAnalysisRegistrationCallbacks)
358 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000359}
360
Chandler Carruthe3f50642016-12-22 06:59:15 +0000361FunctionPassManager
362PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000363 ThinLTOPhase Phase,
364 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000365 assert(Level != O0 && "Must request optimizations!");
366 FunctionPassManager FPM(DebugLogging);
367
368 // Form SSA out of local memory accesses after breaking apart aggregates into
369 // scalars.
370 FPM.addPass(SROA());
371
372 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000373 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000374
Davide Italianoc3688312017-06-01 23:08:14 +0000375 // Hoisting of scalars and load expressions.
376 if (EnableGVNHoist)
377 FPM.addPass(GVNHoistPass());
378
Davide Italianobe1b6a92017-06-03 23:18:29 +0000379 // Global value numbering based sinking.
380 if (EnableGVNSink) {
381 FPM.addPass(GVNSinkPass());
382 FPM.addPass(SimplifyCFGPass());
383 }
384
Chandler Carruthe3f50642016-12-22 06:59:15 +0000385 // Speculative execution if the target has divergent branches; otherwise nop.
386 FPM.addPass(SpeculativeExecutionPass());
387
388 // Optimize based on known information about branches, and cleanup afterward.
389 FPM.addPass(JumpThreadingPass());
390 FPM.addPass(CorrelatedValuePropagationPass());
391 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000392 if (Level == O3)
393 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000394 FPM.addPass(InstCombinePass());
395
396 if (!isOptimizingForSize(Level))
397 FPM.addPass(LibCallsShrinkWrapPass());
398
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000399 invokePeepholeEPCallbacks(FPM, Level);
400
Rong Xue1f42452017-10-23 22:21:29 +0000401 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
402 // using the size value profile. Don't perform this when optimizing for size.
403 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
404 !isOptimizingForSize(Level))
405 FPM.addPass(PGOMemOPSizeOpt());
406
Chandler Carruthe3f50642016-12-22 06:59:15 +0000407 FPM.addPass(TailCallElimPass());
408 FPM.addPass(SimplifyCFGPass());
409
410 // Form canonically associated expression trees, and simplify the trees using
411 // basic mathematical properties. For example, this will form (nearly)
412 // minimal multiplication trees.
413 FPM.addPass(ReassociatePass());
414
415 // Add the primary loop simplification pipeline.
416 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000417 // some function passes in between them. These can and should be removed
418 // and/or replaced by scheduling the loop pass equivalents in the correct
419 // positions. But those equivalent passes aren't powerful enough yet.
420 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
421 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
422 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
423 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000424 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
425
Chandler Carruth71fd2702018-05-30 02:46:45 +0000426 // Simplify the loop body. We do this initially to clean up after other loop
427 // passes run, either when iterating on a loop or on inner loops with
428 // implications on the outer loop.
429 LPM1.addPass(LoopInstSimplifyPass());
430 LPM1.addPass(LoopSimplifyCFGPass());
431
Chandler Carruthe3f50642016-12-22 06:59:15 +0000432 // Rotate Loop - disable header duplication at -Oz
433 LPM1.addPass(LoopRotatePass(Level != Oz));
434 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000435 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000436 LPM2.addPass(IndVarSimplifyPass());
437 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000438
439 for (auto &C : LateLoopOptimizationsEPCallbacks)
440 C(LPM2, Level);
441
Chandler Carruth79b733b2017-01-26 23:21:17 +0000442 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000443 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000444 // because it changes IR to makes profile annotation in back compile
445 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000446 if (Phase != ThinLTOPhase::PreLink ||
447 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000448 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000449
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000450 for (auto &C : LoopOptimizerEndEPCallbacks)
451 C(LPM2, Level);
452
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000453 // We provide the opt remark emitter pass for LICM to use. We only need to do
454 // this once as it is immutable.
455 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000456 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000457 FPM.addPass(SimplifyCFGPass());
458 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000459 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000460
461 // Eliminate redundancies.
462 if (Level != O1) {
463 // These passes add substantial compile time so skip them at O1.
464 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000465 if (RunNewGVN)
466 FPM.addPass(NewGVNPass());
467 else
468 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000469 }
470
471 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
472 FPM.addPass(MemCpyOptPass());
473
474 // Sparse conditional constant propagation.
475 // FIXME: It isn't clear why we do this *after* loop passes rather than
476 // before...
477 FPM.addPass(SCCPPass());
478
479 // Delete dead bit computations (instcombine runs after to fold away the dead
480 // computations, and then ADCE will run later to exploit any new DCE
481 // opportunities that creates).
482 FPM.addPass(BDCEPass());
483
484 // Run instcombine after redundancy and dead bit elimination to exploit
485 // opportunities opened up by them.
486 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000487 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000488
489 // Re-consider control flow based optimizations after redundancy elimination,
490 // redo DCE, etc.
491 FPM.addPass(JumpThreadingPass());
492 FPM.addPass(CorrelatedValuePropagationPass());
493 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000494 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000495
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000496 for (auto &C : ScalarOptimizerLateEPCallbacks)
497 C(FPM, Level);
498
Chandler Carruthe3f50642016-12-22 06:59:15 +0000499 // Finally, do an expensive DCE pass to catch all the dead code exposed by
500 // the simplifications and basic cleanup after all the simplifications.
501 FPM.addPass(ADCEPass());
502 FPM.addPass(SimplifyCFGPass());
503 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000504 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000505
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000506 if (EnableCHR && Level == O3 && PGOOpt &&
507 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
508 FPM.addPass(ControlHeightReductionPass());
509
Chandler Carruthe3f50642016-12-22 06:59:15 +0000510 return FPM;
511}
512
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000513void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
514 PassBuilder::OptimizationLevel Level,
515 bool RunProfileGen,
516 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000517 std::string ProfileUseFile,
518 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000519 // Generally running simplification passes and the inliner with an high
520 // threshold results in smaller executables, but there may be cases where
521 // the size grows, so let's be conservative here and skip this simplification
522 // at -Os/Oz.
523 if (!isOptimizingForSize(Level)) {
524 InlineParams IP;
525
526 // In the old pass manager, this is a cl::opt. Should still this be one?
527 IP.DefaultThreshold = 75;
528
529 // FIXME: The hint threshold has the same value used by the regular inliner.
530 // This should probably be lowered after performance testing.
531 // FIXME: this comment is cargo culted from the old pass manager, revisit).
532 IP.HintThreshold = 325;
533
534 CGSCCPassManager CGPipeline(DebugLogging);
535
536 CGPipeline.addPass(InlinerPass(IP));
537
538 FunctionPassManager FPM;
539 FPM.addPass(SROA());
540 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
541 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
542 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000543 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000544
Davide Italiano513dfaa2017-02-13 15:26:22 +0000545 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
546
547 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
548 }
549
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000550 // Delete anything that is now dead to make sure that we don't instrument
551 // dead code. Instrumentation can end up keeping dead code around and
552 // dramatically increase code size.
553 MPM.addPass(GlobalDCEPass());
554
Davide Italiano513dfaa2017-02-13 15:26:22 +0000555 if (RunProfileGen) {
556 MPM.addPass(PGOInstrumentationGen());
557
Xinliang David Lib67530e2017-06-25 00:26:43 +0000558 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000559 FPM.addPass(
560 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000561 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
562
Davide Italiano513dfaa2017-02-13 15:26:22 +0000563 // Add the profile lowering pass.
564 InstrProfOptions Options;
565 if (!ProfileGenFile.empty())
566 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000567 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000568 MPM.addPass(InstrProfiling(Options));
569 }
570
571 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000572 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000573}
574
Easwaran Raman8249fac2017-06-28 13:33:49 +0000575static InlineParams
576getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
577 auto O3 = PassBuilder::O3;
578 unsigned OptLevel = Level > O3 ? 2 : Level;
579 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
580 return getInlineParams(OptLevel, SizeLevel);
581}
582
Chandler Carruthe3f50642016-12-22 06:59:15 +0000583ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000584PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000585 ThinLTOPhase Phase,
586 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000587 ModulePassManager MPM(DebugLogging);
588
Chandler Carruthe3f50642016-12-22 06:59:15 +0000589 // Do basic inference of function attributes from known properties of system
590 // libraries and other oracles.
591 MPM.addPass(InferFunctionAttrsPass());
592
593 // Create an early function pass manager to cleanup the output of the
594 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000595 FunctionPassManager EarlyFPM(DebugLogging);
596 EarlyFPM.addPass(SimplifyCFGPass());
597 EarlyFPM.addPass(SROA());
598 EarlyFPM.addPass(EarlyCSEPass());
599 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000600 if (Level == O3)
601 EarlyFPM.addPass(CallSiteSplittingPass());
602
Dehao Chen08f88312017-08-07 20:23:20 +0000603 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
604 // to convert bitcast to direct calls so that they can be inlined during the
605 // profile annotation prepration step.
606 // More details about SamplePGO design can be found in:
607 // https://research.google.com/pubs/pub45290.html
608 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
609 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
610 Phase == ThinLTOPhase::PostLink)
611 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000612 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000613
Dehao Chen08f88312017-08-07 20:23:20 +0000614 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
615 // Annotate sample profile right after early FPM to ensure freshness of
616 // the debug info.
Dehao Chend26dae02017-10-01 05:24:51 +0000617 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000618 PGOOpt->ProfileRemappingFile,
Dehao Chend26dae02017-10-01 05:24:51 +0000619 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000620 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
621 // for the profile annotation to be accurate in the ThinLTO backend.
622 if (Phase != ThinLTOPhase::PreLink)
623 // We perform early indirect call promotion here, before globalopt.
624 // This is important for the ThinLTO backend phase because otherwise
625 // imported available_externally functions look unreferenced and are
626 // removed.
627 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
628 true));
629 }
630
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000631 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000632 // and prior to optimizing globals.
633 // FIXME: This position in the pipeline hasn't been carefully considered in
634 // years, it should be re-analyzed.
635 MPM.addPass(IPSCCPPass());
636
Matthew Simpsoncb585582017-10-25 13:40:08 +0000637 // Attach metadata to indirect call sites indicating the set of functions
638 // they may target at run-time. This should follow IPSCCP.
639 MPM.addPass(CalledValuePropagationPass());
640
Chandler Carruthe3f50642016-12-22 06:59:15 +0000641 // Optimize globals to try and fold them into constants.
642 MPM.addPass(GlobalOptPass());
643
644 // Promote any localized globals to SSA registers.
645 // FIXME: Should this instead by a run of SROA?
646 // FIXME: We should probably run instcombine and simplify-cfg afterward to
647 // delete control flows that are dead once globals have been folded to
648 // constants.
649 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
650
651 // Remove any dead arguments exposed by cleanups and constand folding
652 // globals.
653 MPM.addPass(DeadArgumentEliminationPass());
654
655 // Create a small function pass pipeline to cleanup after all the global
656 // optimizations.
657 FunctionPassManager GlobalCleanupPM(DebugLogging);
658 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000659 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
660
Chandler Carruthe3f50642016-12-22 06:59:15 +0000661 GlobalCleanupPM.addPass(SimplifyCFGPass());
662 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
663
Dehao Chen89d32262017-08-02 01:28:31 +0000664 // Add all the requested passes for instrumentation PGO, if requested.
665 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
666 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
667 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000668 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
669 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000670 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000671 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000672
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000673 // Synthesize function entry counts for non-PGO compilation.
674 if (EnableSyntheticCounts && !PGOOpt)
675 MPM.addPass(SyntheticCountsPropagation());
676
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000677 // Require the GlobalsAA analysis for the module so we can query it within
678 // the CGSCC pipeline.
679 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000680
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000681 // Require the ProfileSummaryAnalysis for the module so we can query it within
682 // the inliner pass.
683 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
684
Chandler Carruthe3f50642016-12-22 06:59:15 +0000685 // Now begin the main postorder CGSCC pipeline.
686 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
687 // manager and trying to emulate its precise behavior. Much of this doesn't
688 // make a lot of sense and we should revisit the core CGSCC structure.
689 CGSCCPassManager MainCGPipeline(DebugLogging);
690
691 // Note: historically, the PruneEH pass was run first to deduce nounwind and
692 // generally clean up exception handling overhead. It isn't clear this is
693 // valuable as the inliner doesn't currently care whether it is inlining an
694 // invoke or a call.
695
696 // Run the inliner first. The theory is that we are walking bottom-up and so
697 // the callees have already been fully optimized, and we want to inline them
698 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000699 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000700 // because it makes profile annotation in the backend inaccurate.
701 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000702 if (Phase == ThinLTOPhase::PreLink &&
703 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000704 IP.HotCallSiteThreshold = 0;
705 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000706
707 // Now deduce any function attributes based in the current code.
708 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
709
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000710 // When at O3 add argument promotion to the pass pipeline.
711 // FIXME: It isn't at all clear why this should be limited to O3.
712 if (Level == O3)
713 MainCGPipeline.addPass(ArgumentPromotionPass());
714
Chandler Carruthe3f50642016-12-22 06:59:15 +0000715 // Lastly, add the core function simplification pipeline nested inside the
716 // CGSCC walk.
717 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000718 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000719
Teresa Johnsond7253352018-10-23 22:57:40 +0000720 // We only want to do hot cold splitting once for ThinLTO, during the
721 // post-link ThinLTO.
722 if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink)
Aditya Kumard9e2e382018-10-21 18:11:56 +0000723 MPM.addPass(HotColdSplittingPass());
724
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000725 for (auto &C : CGSCCOptimizerLateEPCallbacks)
726 C(MainCGPipeline, Level);
727
Chandler Carruth719ffe12017-02-12 05:38:04 +0000728 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
729 // to detect when we devirtualize indirect calls and iterate the SCC passes
730 // in that case to try and catch knock-on inlining or function attrs
731 // opportunities. Then we add it to the module pipeline by walking the SCCs
732 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000733 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000734 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000735 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000736
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000737 return MPM;
738}
739
740ModulePassManager
741PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
742 bool DebugLogging) {
743 ModulePassManager MPM(DebugLogging);
744
745 // Optimize globals now that the module is fully simplified.
746 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000747 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000748
Xinliang David Li126157c2017-05-22 16:41:57 +0000749 // Run partial inlining pass to partially inline functions that have
750 // large bodies.
751 if (RunPartialInlining)
752 MPM.addPass(PartialInlinerPass());
753
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000754 // Remove avail extern fns and globals definitions since we aren't compiling
755 // an object file for later LTO. For LTO we want to preserve these so they
756 // are eligible for inlining at link-time. Note if they are unreferenced they
757 // will be removed by GlobalDCE later, so this only impacts referenced
758 // available externally globals. Eventually they will be suppressed during
759 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
760 // may make globals referenced by available external functions dead and saves
761 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000762 MPM.addPass(EliminateAvailableExternallyPass());
763
764 // Do RPO function attribute inference across the module to forward-propagate
765 // attributes where applicable.
766 // FIXME: Is this really an optimization rather than a canonicalization?
767 MPM.addPass(ReversePostOrderFunctionAttrsPass());
768
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000769 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000770 // useful as the above will have inlined, DCE'ed, and function-attr
771 // propagated everything. We should at this point have a reasonably minimal
772 // and richly annotated call graph. By computing aliasing and mod/ref
773 // information for all local globals here, the late loop passes and notably
774 // the vectorizer will be able to use them to help recognize vectorizable
775 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000776 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000777
778 FunctionPassManager OptimizePM(DebugLogging);
779 OptimizePM.addPass(Float2IntPass());
780 // FIXME: We need to run some loop optimizations to re-rotate loops after
781 // simplify-cfg and others undo their rotation.
782
783 // Optimize the loop execution. These passes operate on entire loop nests
784 // rather than on each loop in an inside-out manner, and so they are actually
785 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000786
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000787 for (auto &C : VectorizerStartEPCallbacks)
788 C(OptimizePM, Level);
789
Chandler Carrutha95ff382017-01-27 00:50:21 +0000790 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000791 OptimizePM.addPass(
792 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000793
794 // Distribute loops to allow partial vectorization. I.e. isolate dependences
795 // into separate loop that would otherwise inhibit vectorization. This is
796 // currently only performed for loops marked with the metadata
797 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000798 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000799
800 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000801 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000802
Chandler Carruthbaabda92017-01-27 01:32:26 +0000803 // Eliminate loads by forwarding stores from the previous iteration to loads
804 // of the current iteration.
805 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000806
807 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000808 OptimizePM.addPass(InstCombinePass());
809
Chandler Carrutha95ff382017-01-27 00:50:21 +0000810 // Now that we've formed fast to execute loop structures, we do further
811 // optimizations. These are run afterward as they might block doing complex
812 // analyses and transforms such as what are needed for loop vectorization.
813
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000814 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
815 // GVN, loop transforms, and others have already run, so it's now better to
816 // convert to more optimized IR using more aggressive simplify CFG options.
817 // The extra sinking transform can create larger basic blocks, so do this
818 // before SLP vectorization.
819 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
820 forwardSwitchCondToPhi(true).
821 convertSwitchToLookupTable(true).
822 needCanonicalLoops(false).
823 sinkCommonInsts(true)));
824
Chandler Carruthe3f50642016-12-22 06:59:15 +0000825 // Optimize parallel scalar instruction chains into SIMD instructions.
826 OptimizePM.addPass(SLPVectorizerPass());
827
Chandler Carruthe3f50642016-12-22 06:59:15 +0000828 OptimizePM.addPass(InstCombinePass());
829
830 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000831 // execution resources of an out-of-order processor. We also then need to
832 // clean up redundancies and loop invariant code.
833 // FIXME: It would be really good to use a loop-integrated instruction
834 // combiner for cleanup here so that the unrolling and LICM can be pipelined
835 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000836 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
837 if (EnableUnrollAndJam) {
838 OptimizePM.addPass(
839 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
840 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000841 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000842 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000843 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000844 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000845 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000846
847 // Now that we've vectorized and unrolled loops, we may have more refined
848 // alignment information, try to re-derive it here.
849 OptimizePM.addPass(AlignmentFromAssumptionsPass());
850
Chandler Carrutha95ff382017-01-27 00:50:21 +0000851 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
852 // canonicalization pass that enables other optimizations. As a result,
853 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
854 // result too early.
855 OptimizePM.addPass(LoopSinkPass());
856
857 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000858 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000859
Sanjay Patel6fd43912017-09-09 13:38:18 +0000860 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
861 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
862 // flattening of blocks.
863 OptimizePM.addPass(DivRemPairsPass());
864
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000865 // LoopSink (and other loop passes since the last simplifyCFG) might have
866 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
867 OptimizePM.addPass(SimplifyCFGPass());
868
Chandler Carruthc34f7892017-11-28 11:32:31 +0000869 // Optimize PHIs by speculating around them when profitable. Note that this
870 // pass needs to be run after any PRE or similar pass as it is essentially
871 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
872 OptimizePM.addPass(SpeculateAroundPHIsPass());
873
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000874 for (auto &C : OptimizerLastEPCallbacks)
875 C(OptimizePM, Level);
876
Chandler Carrutha95ff382017-01-27 00:50:21 +0000877 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000878 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
879
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000880 MPM.addPass(CGProfilePass());
881
Chandler Carruthe3f50642016-12-22 06:59:15 +0000882 // Now we need to do some global optimization transforms.
883 // FIXME: It would seem like these should come first in the optimization
884 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
885 // ordering here.
886 MPM.addPass(GlobalDCEPass());
887 MPM.addPass(ConstantMergePass());
888
889 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000890}
891
Chandler Carruthe3f50642016-12-22 06:59:15 +0000892ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000893PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
894 bool DebugLogging) {
895 assert(Level != O0 && "Must request optimizations for the default pipeline!");
896
897 ModulePassManager MPM(DebugLogging);
898
899 // Force any function attributes we want the rest of the pipeline to observe.
900 MPM.addPass(ForceFunctionAttrsPass());
901
David Blaikie0c64f5a2018-01-23 01:25:20 +0000902 // Apply module pipeline start EP callback.
903 for (auto &C : PipelineStartEPCallbacks)
904 C(MPM);
905
Dehao Chen08f88312017-08-07 20:23:20 +0000906 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000907 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
908
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000909 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000910 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
911 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000912
913 // Now add the optimization pipeline.
914 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
915
916 return MPM;
917}
918
919ModulePassManager
920PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
921 bool DebugLogging) {
922 assert(Level != O0 && "Must request optimizations for the default pipeline!");
923
924 ModulePassManager MPM(DebugLogging);
925
926 // Force any function attributes we want the rest of the pipeline to observe.
927 MPM.addPass(ForceFunctionAttrsPass());
928
Dehao Chen08f88312017-08-07 20:23:20 +0000929 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000930 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
931
David Blaikie0c64f5a2018-01-23 01:25:20 +0000932 // Apply module pipeline start EP callback.
933 for (auto &C : PipelineStartEPCallbacks)
934 C(MPM);
935
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000936 // If we are planning to perform ThinLTO later, we don't bloat the code with
937 // unrolling/vectorization/... now. Just simplify the module as much as we
938 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000939 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
940 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000941
942 // Run partial inlining pass to partially inline functions that have
943 // large bodies.
944 // FIXME: It isn't clear whether this is really the right place to run this
945 // in ThinLTO. Because there is another canonicalization and simplification
946 // phase that will run after the thin link, running this here ends up with
947 // less information than will be available later and it may grow functions in
948 // ways that aren't beneficial.
949 if (RunPartialInlining)
950 MPM.addPass(PartialInlinerPass());
951
952 // Reduce the size of the IR as much as possible.
953 MPM.addPass(GlobalOptPass());
954
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000955 return MPM;
956}
957
Teresa Johnson28023db2018-07-19 14:51:32 +0000958ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
959 OptimizationLevel Level, bool DebugLogging,
960 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000961 ModulePassManager MPM(DebugLogging);
962
Teresa Johnson28023db2018-07-19 14:51:32 +0000963 if (ImportSummary) {
964 // These passes import type identifier resolutions for whole-program
965 // devirtualization and CFI. They must run early because other passes may
966 // disturb the specific instruction patterns that these passes look for,
967 // creating dependencies on resolutions that may not appear in the summary.
968 //
969 // For example, GVN may transform the pattern assume(type.test) appearing in
970 // two basic blocks into assume(phi(type.test, type.test)), which would
971 // transform a dependency on a WPD resolution into a dependency on a type
972 // identifier resolution for CFI.
973 //
974 // Also, WPD has access to more precise information than ICP and can
975 // devirtualize more effectively, so it should operate on the IR first.
976 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
977 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
978 }
979
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000980 // Force any function attributes we want the rest of the pipeline to observe.
981 MPM.addPass(ForceFunctionAttrsPass());
982
983 // During the ThinLTO backend phase we perform early indirect call promotion
984 // here, before globalopt. Otherwise imported available_externally functions
985 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000986 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
987 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000988 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000989 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
990 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000991
992 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000993 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
994 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000995
996 // Now add the optimization pipeline.
997 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
998
999 return MPM;
1000}
1001
1002ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001003PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1004 bool DebugLogging) {
1005 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001006 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +00001007 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001008}
1009
Teresa Johnson28023db2018-07-19 14:51:32 +00001010ModulePassManager
1011PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1012 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001013 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1014 ModulePassManager MPM(DebugLogging);
1015
Xin Tong642c8d32018-11-15 18:06:42 +00001016 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1017 // Load sample profile before running the LTO optimization pipeline.
1018 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1019 PGOOpt->ProfileRemappingFile,
1020 false /* ThinLTOPhase::PreLink */));
1021 }
1022
Davide Italiano089a9122017-01-24 00:57:39 +00001023 // Remove unused virtual tables to improve the quality of code generated by
1024 // whole-program devirtualization and bitset lowering.
1025 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001026
Davide Italiano089a9122017-01-24 00:57:39 +00001027 // Force any function attributes we want the rest of the pipeline to observe.
1028 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001029
Davide Italiano089a9122017-01-24 00:57:39 +00001030 // Do basic inference of function attributes from known properties of system
1031 // libraries and other oracles.
1032 MPM.addPass(InferFunctionAttrsPass());
1033
1034 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001035 FunctionPassManager EarlyFPM(DebugLogging);
1036 EarlyFPM.addPass(CallSiteSplittingPass());
1037 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1038
Davide Italiano089a9122017-01-24 00:57:39 +00001039 // Indirect call promotion. This should promote all the targets that are
1040 // left by the earlier promotion pass that promotes intra-module targets.
1041 // This two-step promotion is to save the compile time. For LTO, it should
1042 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001043 MPM.addPass(PGOIndirectCallPromotion(
1044 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001045 // Propagate constants at call sites into the functions they call. This
1046 // opens opportunities for globalopt (and inlining) by substituting function
1047 // pointers passed as arguments to direct uses of functions.
1048 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001049
1050 // Attach metadata to indirect call sites indicating the set of functions
1051 // they may target at run-time. This should follow IPSCCP.
1052 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001053 }
1054
1055 // Now deduce any function attributes based in the current code.
1056 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1057 PostOrderFunctionAttrsPass()));
1058
1059 // Do RPO function attribute inference across the module to forward-propagate
1060 // attributes where applicable.
1061 // FIXME: Is this really an optimization rather than a canonicalization?
1062 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1063
1064 // Use inragne annotations on GEP indices to split globals where beneficial.
1065 MPM.addPass(GlobalSplitPass());
1066
1067 // Run whole program optimization of virtual call when the list of callees
1068 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001069 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001070
1071 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001072 if (Level == 1) {
1073 // The LowerTypeTestsPass needs to run to lower type metadata and the
1074 // type.test intrinsics. The pass does nothing if CFI is disabled.
1075 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001076 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001077 }
Davide Italiano089a9122017-01-24 00:57:39 +00001078
1079 // Optimize globals to try and fold them into constants.
1080 MPM.addPass(GlobalOptPass());
1081
1082 // Promote any localized globals to SSA registers.
1083 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1084
1085 // Linking modules together can lead to duplicate global constant, only
1086 // keep one copy of each constant.
1087 MPM.addPass(ConstantMergePass());
1088
1089 // Remove unused arguments from functions.
1090 MPM.addPass(DeadArgumentEliminationPass());
1091
1092 // Reduce the code after globalopt and ipsccp. Both can open up significant
1093 // simplification opportunities, and both can propagate functions through
1094 // function pointers. When this happens, we often have to resolve varargs
1095 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001096 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001097 if (Level == O3)
1098 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001099 PeepholeFPM.addPass(InstCombinePass());
1100 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1101
1102 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001103
1104 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1105 // generally clean up exception handling overhead. It isn't clear this is
1106 // valuable as the inliner doesn't currently care whether it is inlining an
1107 // invoke or a call.
1108 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001109 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1110 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001111
1112 // Optimize globals again after we ran the inliner.
1113 MPM.addPass(GlobalOptPass());
1114
1115 // Garbage collect dead functions.
1116 // FIXME: Add ArgumentPromotion pass after once it's ported.
1117 MPM.addPass(GlobalDCEPass());
1118
1119 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001120 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001121 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001122 invokePeepholeEPCallbacks(FPM, Level);
1123
Davide Italiano089a9122017-01-24 00:57:39 +00001124 FPM.addPass(JumpThreadingPass());
1125
1126 // Break up allocas
1127 FPM.addPass(SROA());
1128
1129 // Run a few AA driver optimizations here and now to cleanup the code.
1130 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1131
1132 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1133 PostOrderFunctionAttrsPass()));
1134 // FIXME: here we run IP alias analysis in the legacy PM.
1135
1136 FunctionPassManager MainFPM;
1137
1138 // FIXME: once we fix LoopPass Manager, add LICM here.
1139 // FIXME: once we provide support for enabling MLSM, add it here.
1140 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001141 if (RunNewGVN)
1142 MainFPM.addPass(NewGVNPass());
1143 else
1144 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001145
1146 // Remove dead memcpy()'s.
1147 MainFPM.addPass(MemCpyOptPass());
1148
1149 // Nuke dead stores.
1150 MainFPM.addPass(DSEPass());
1151
1152 // FIXME: at this point, we run a bunch of loop passes:
1153 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1154 // loopVectorize. Enable them once the remaining issue with LPM
1155 // are sorted out.
1156
1157 MainFPM.addPass(InstCombinePass());
1158 MainFPM.addPass(SimplifyCFGPass());
1159 MainFPM.addPass(SCCPPass());
1160 MainFPM.addPass(InstCombinePass());
1161 MainFPM.addPass(BDCEPass());
1162
1163 // FIXME: We may want to run SLPVectorizer here.
1164 // After vectorization, assume intrinsics may tell us more
1165 // about pointer alignments.
1166#if 0
1167 MainFPM.add(AlignmentFromAssumptionsPass());
1168#endif
1169
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001170 // FIXME: Conditionally run LoadCombine here, after it's ported
1171 // (in case we still have this pass, given its questionable usefulness).
1172
Davide Italiano089a9122017-01-24 00:57:39 +00001173 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001174 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001175 MainFPM.addPass(JumpThreadingPass());
1176 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1177
1178 // Create a function that performs CFI checks for cross-DSO calls with
1179 // targets in the current module.
1180 MPM.addPass(CrossDSOCFIPass());
1181
1182 // Lower type metadata and the type.test intrinsic. This pass supports
1183 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1184 // to be run at link time if CFI is enabled. This pass does nothing if
1185 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001186 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001187
1188 // Add late LTO optimization passes.
1189 // Delete basic blocks, which optimization passes may have killed.
1190 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1191
1192 // Drop bodies of available eternally objects to improve GlobalDCE.
1193 MPM.addPass(EliminateAvailableExternallyPass());
1194
1195 // Now that we have optimized the program, discard unreachable functions.
1196 MPM.addPass(GlobalDCEPass());
1197
1198 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001199 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001200}
1201
Chandler Carruth060ad612016-12-23 20:38:19 +00001202AAManager PassBuilder::buildDefaultAAPipeline() {
1203 AAManager AA;
1204
1205 // The order in which these are registered determines their priority when
1206 // being queried.
1207
1208 // First we register the basic alias analysis that provides the majority of
1209 // per-function local AA logic. This is a stateless, on-demand local set of
1210 // AA techniques.
1211 AA.registerFunctionAnalysis<BasicAA>();
1212
1213 // Next we query fast, specialized alias analyses that wrap IR-embedded
1214 // information about aliasing.
1215 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1216 AA.registerFunctionAnalysis<TypeBasedAA>();
1217
1218 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001219 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1220 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001221 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001222 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001223
1224 return AA;
1225}
1226
Chandler Carruth241bf242016-08-03 07:44:48 +00001227static Optional<int> parseRepeatPassName(StringRef Name) {
1228 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1229 return None;
1230 int Count;
1231 if (Name.getAsInteger(0, Count) || Count <= 0)
1232 return None;
1233 return Count;
1234}
1235
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001236static Optional<int> parseDevirtPassName(StringRef Name) {
1237 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1238 return None;
1239 int Count;
1240 if (Name.getAsInteger(0, Count) || Count <= 0)
1241 return None;
1242 return Count;
1243}
1244
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001245/// Tests whether a pass name starts with a valid prefix for a default pipeline
1246/// alias.
1247static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1248 return Name.startswith("default") || Name.startswith("thinlto") ||
1249 Name.startswith("lto");
1250}
1251
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001252/// Tests whether registered callbacks will accept a given pass name.
1253///
1254/// When parsing a pipeline text, the type of the outermost pipeline may be
1255/// omitted, in which case the type is automatically determined from the first
1256/// pass name in the text. This may be a name that is handled through one of the
1257/// callbacks. We check this through the oridinary parsing callbacks by setting
1258/// up a dummy PassManager in order to not force the client to also handle this
1259/// type of query.
1260template <typename PassManagerT, typename CallbacksT>
1261static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1262 if (!Callbacks.empty()) {
1263 PassManagerT DummyPM;
1264 for (auto &CB : Callbacks)
1265 if (CB(Name, DummyPM, {}))
1266 return true;
1267 }
1268 return false;
1269}
1270
1271template <typename CallbacksT>
1272static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001273 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001274 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001275 return DefaultAliasRegex.match(Name);
1276
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001277 // Explicitly handle pass manager names.
1278 if (Name == "module")
1279 return true;
1280 if (Name == "cgscc")
1281 return true;
1282 if (Name == "function")
1283 return true;
1284
Chandler Carruth241bf242016-08-03 07:44:48 +00001285 // Explicitly handle custom-parsed pass names.
1286 if (parseRepeatPassName(Name))
1287 return true;
1288
Chandler Carruth74a8a222016-06-17 07:15:29 +00001289#define MODULE_PASS(NAME, CREATE_PASS) \
1290 if (Name == NAME) \
1291 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001292#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001293 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001294 return true;
1295#include "PassRegistry.def"
1296
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001297 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001298}
1299
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001300template <typename CallbacksT>
1301static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001302 // Explicitly handle pass manager names.
1303 if (Name == "cgscc")
1304 return true;
1305 if (Name == "function")
1306 return true;
1307
Chandler Carruth241bf242016-08-03 07:44:48 +00001308 // Explicitly handle custom-parsed pass names.
1309 if (parseRepeatPassName(Name))
1310 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001311 if (parseDevirtPassName(Name))
1312 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001313
Chandler Carruth74a8a222016-06-17 07:15:29 +00001314#define CGSCC_PASS(NAME, CREATE_PASS) \
1315 if (Name == NAME) \
1316 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001317#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001318 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001319 return true;
1320#include "PassRegistry.def"
1321
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001322 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001323}
1324
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001325template <typename CallbacksT>
1326static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001327 // Explicitly handle pass manager names.
1328 if (Name == "function")
1329 return true;
1330 if (Name == "loop")
1331 return true;
1332
Chandler Carruth241bf242016-08-03 07:44:48 +00001333 // Explicitly handle custom-parsed pass names.
1334 if (parseRepeatPassName(Name))
1335 return true;
1336
Chandler Carruth74a8a222016-06-17 07:15:29 +00001337#define FUNCTION_PASS(NAME, CREATE_PASS) \
1338 if (Name == NAME) \
1339 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001340#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001341 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001342 return true;
1343#include "PassRegistry.def"
1344
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001345 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001346}
1347
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001348template <typename CallbacksT>
1349static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001350 // Explicitly handle pass manager names.
1351 if (Name == "loop")
1352 return true;
1353
Chandler Carruth241bf242016-08-03 07:44:48 +00001354 // Explicitly handle custom-parsed pass names.
1355 if (parseRepeatPassName(Name))
1356 return true;
1357
Chandler Carruth74a8a222016-06-17 07:15:29 +00001358#define LOOP_PASS(NAME, CREATE_PASS) \
1359 if (Name == NAME) \
1360 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001361#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1362 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1363 return true;
1364#include "PassRegistry.def"
1365
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001366 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001367}
1368
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001369Optional<std::vector<PassBuilder::PipelineElement>>
1370PassBuilder::parsePipelineText(StringRef Text) {
1371 std::vector<PipelineElement> ResultPipeline;
1372
1373 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1374 &ResultPipeline};
1375 for (;;) {
1376 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1377 size_t Pos = Text.find_first_of(",()");
1378 Pipeline.push_back({Text.substr(0, Pos), {}});
1379
1380 // If we have a single terminating name, we're done.
1381 if (Pos == Text.npos)
1382 break;
1383
1384 char Sep = Text[Pos];
1385 Text = Text.substr(Pos + 1);
1386 if (Sep == ',')
1387 // Just a name ending in a comma, continue.
1388 continue;
1389
1390 if (Sep == '(') {
1391 // Push the inner pipeline onto the stack to continue processing.
1392 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1393 continue;
1394 }
1395
1396 assert(Sep == ')' && "Bogus separator!");
1397 // When handling the close parenthesis, we greedily consume them to avoid
1398 // empty strings in the pipeline.
1399 do {
1400 // If we try to pop the outer pipeline we have unbalanced parentheses.
1401 if (PipelineStack.size() == 1)
1402 return None;
1403
1404 PipelineStack.pop_back();
1405 } while (Text.consume_front(")"));
1406
1407 // Check if we've finished parsing.
1408 if (Text.empty())
1409 break;
1410
1411 // Otherwise, the end of an inner pipeline always has to be followed by
1412 // a comma, and then we can continue.
1413 if (!Text.consume_front(","))
1414 return None;
1415 }
1416
1417 if (PipelineStack.size() > 1)
1418 // Unbalanced paretheses.
1419 return None;
1420
1421 assert(PipelineStack.back() == &ResultPipeline &&
1422 "Wrong pipeline at the bottom of the stack!");
1423 return {std::move(ResultPipeline)};
1424}
1425
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001426Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1427 const PipelineElement &E,
1428 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001429 auto &Name = E.Name;
1430 auto &InnerPipeline = E.InnerPipeline;
1431
1432 // First handle complex passes like the pass managers which carry pipelines.
1433 if (!InnerPipeline.empty()) {
1434 if (Name == "module") {
1435 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001436 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1437 VerifyEachPass, DebugLogging))
1438 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001439 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001440 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001441 }
1442 if (Name == "cgscc") {
1443 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001444 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1445 DebugLogging))
1446 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001447 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001448 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001449 }
1450 if (Name == "function") {
1451 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001452 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1453 VerifyEachPass, DebugLogging))
1454 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001455 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001456 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001457 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001458 if (auto Count = parseRepeatPassName(Name)) {
1459 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001460 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1461 VerifyEachPass, DebugLogging))
1462 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001463 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001464 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001465 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001466
1467 for (auto &C : ModulePipelineParsingCallbacks)
1468 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001469 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001470
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001471 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001472 return make_error<StringError>(
1473 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1474 inconvertibleErrorCode());
1475 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001476 }
1477
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001478 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001479 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001480 SmallVector<StringRef, 3> Matches;
1481 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001482 return make_error<StringError>(
1483 formatv("unknown default pipeline alias '{0}'", Name).str(),
1484 inconvertibleErrorCode());
1485
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001486 assert(Matches.size() == 3 && "Must capture two matched strings!");
1487
Jordan Rosef85a95f2016-07-25 18:34:51 +00001488 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001489 .Case("O0", O0)
1490 .Case("O1", O1)
1491 .Case("O2", O2)
1492 .Case("O3", O3)
1493 .Case("Os", Os)
1494 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001495 if (L == O0)
1496 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001497 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001498
1499 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001500 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001501 } else if (Matches[1] == "thinlto-pre-link") {
1502 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1503 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001504 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001505 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001506 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001507 } else {
1508 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001509 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001510 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001511 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001512 }
1513
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001514 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001515#define MODULE_PASS(NAME, CREATE_PASS) \
1516 if (Name == NAME) { \
1517 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001518 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001519 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001520#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1521 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001522 MPM.addPass( \
1523 RequireAnalysisPass< \
1524 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001525 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001526 } \
1527 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001528 MPM.addPass(InvalidateAnalysisPass< \
1529 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001530 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001531 }
1532#include "PassRegistry.def"
1533
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001534 for (auto &C : ModulePipelineParsingCallbacks)
1535 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001536 return Error::success();
1537 return make_error<StringError>(
1538 formatv("unknown module pass '{0}'", Name).str(),
1539 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001540}
1541
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001542Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1543 const PipelineElement &E, bool VerifyEachPass,
1544 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001545 auto &Name = E.Name;
1546 auto &InnerPipeline = E.InnerPipeline;
1547
1548 // First handle complex passes like the pass managers which carry pipelines.
1549 if (!InnerPipeline.empty()) {
1550 if (Name == "cgscc") {
1551 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001552 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1553 VerifyEachPass, DebugLogging))
1554 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001555 // Add the nested pass manager with the appropriate adaptor.
1556 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001557 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001558 }
1559 if (Name == "function") {
1560 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001561 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1562 VerifyEachPass, DebugLogging))
1563 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001564 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001565 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001566 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001567 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001568 if (auto Count = parseRepeatPassName(Name)) {
1569 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001570 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1571 VerifyEachPass, DebugLogging))
1572 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001573 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001574 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001575 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001576 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1577 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001578 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1579 VerifyEachPass, DebugLogging))
1580 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001581 CGPM.addPass(
1582 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001583 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001584 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001585
1586 for (auto &C : CGSCCPipelineParsingCallbacks)
1587 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001588 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001589
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001590 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001591 return make_error<StringError>(
1592 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1593 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001594 }
1595
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001596// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001597#define CGSCC_PASS(NAME, CREATE_PASS) \
1598 if (Name == NAME) { \
1599 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001600 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001601 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001602#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1603 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001604 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001605 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001606 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1607 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001608 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001609 } \
1610 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001611 CGPM.addPass(InvalidateAnalysisPass< \
1612 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001613 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001614 }
1615#include "PassRegistry.def"
1616
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001617 for (auto &C : CGSCCPipelineParsingCallbacks)
1618 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001619 return Error::success();
1620 return make_error<StringError>(
1621 formatv("unknown cgscc pass '{0}'", Name).str(),
1622 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001623}
1624
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001625Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1626 const PipelineElement &E,
1627 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001628 auto &Name = E.Name;
1629 auto &InnerPipeline = E.InnerPipeline;
1630
1631 // First handle complex passes like the pass managers which carry pipelines.
1632 if (!InnerPipeline.empty()) {
1633 if (Name == "function") {
1634 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001635 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1636 VerifyEachPass, DebugLogging))
1637 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001638 // Add the nested pass manager with the appropriate adaptor.
1639 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001640 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001641 }
1642 if (Name == "loop") {
1643 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001644 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1645 DebugLogging))
1646 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001647 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001648 FPM.addPass(
1649 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001650 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001651 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001652 if (auto Count = parseRepeatPassName(Name)) {
1653 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001654 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1655 VerifyEachPass, DebugLogging))
1656 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001657 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001658 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001659 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001660
1661 for (auto &C : FunctionPipelineParsingCallbacks)
1662 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001663 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001664
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001665 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001666 return make_error<StringError>(
1667 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1668 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001669 }
1670
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001671// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001672#define FUNCTION_PASS(NAME, CREATE_PASS) \
1673 if (Name == NAME) { \
1674 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001675 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001676 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001677#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1678 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001679 FPM.addPass( \
1680 RequireAnalysisPass< \
1681 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001682 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001683 } \
1684 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001685 FPM.addPass(InvalidateAnalysisPass< \
1686 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001687 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001688 }
1689#include "PassRegistry.def"
1690
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001691 for (auto &C : FunctionPipelineParsingCallbacks)
1692 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001693 return Error::success();
1694 return make_error<StringError>(
1695 formatv("unknown function pass '{0}'", Name).str(),
1696 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001697}
1698
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001699Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1700 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001701 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001702 auto &InnerPipeline = E.InnerPipeline;
1703
1704 // First handle complex passes like the pass managers which carry pipelines.
1705 if (!InnerPipeline.empty()) {
1706 if (Name == "loop") {
1707 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001708 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1709 VerifyEachPass, DebugLogging))
1710 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001711 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001712 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001713 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001714 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001715 if (auto Count = parseRepeatPassName(Name)) {
1716 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001717 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1718 VerifyEachPass, DebugLogging))
1719 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001720 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001721 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001722 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001723
1724 for (auto &C : LoopPipelineParsingCallbacks)
1725 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001726 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001727
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001728 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001729 return make_error<StringError>(
1730 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1731 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001732 }
1733
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001734// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001735#define LOOP_PASS(NAME, CREATE_PASS) \
1736 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001737 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001738 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001739 }
1740#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1741 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001742 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001743 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1744 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1745 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001746 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001747 } \
1748 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001749 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001750 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001751 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001752 }
1753#include "PassRegistry.def"
1754
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001755 for (auto &C : LoopPipelineParsingCallbacks)
1756 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001757 return Error::success();
1758 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1759 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001760}
1761
Chandler Carruthedf59962016-02-18 09:45:17 +00001762bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001763#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1764 if (Name == NAME) { \
1765 AA.registerModuleAnalysis< \
1766 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1767 return true; \
1768 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001769#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1770 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001771 AA.registerFunctionAnalysis< \
1772 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001773 return true; \
1774 }
1775#include "PassRegistry.def"
1776
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001777 for (auto &C : AAParsingCallbacks)
1778 if (C(Name, AA))
1779 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001780 return false;
1781}
1782
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001783Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001784 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001785 bool VerifyEachPass,
1786 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001787 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001788 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1789 return Err;
1790 // FIXME: No verifier support for Loop passes!
1791 }
1792 return Error::success();
1793}
1794
1795Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1796 ArrayRef<PipelineElement> Pipeline,
1797 bool VerifyEachPass,
1798 bool DebugLogging) {
1799 for (const auto &Element : Pipeline) {
1800 if (auto Err =
1801 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1802 return Err;
1803 if (VerifyEachPass)
1804 FPM.addPass(VerifierPass());
1805 }
1806 return Error::success();
1807}
1808
1809Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1810 ArrayRef<PipelineElement> Pipeline,
1811 bool VerifyEachPass,
1812 bool DebugLogging) {
1813 for (const auto &Element : Pipeline) {
1814 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1815 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001816 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001817 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001818 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001819}
1820
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001821void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1822 FunctionAnalysisManager &FAM,
1823 CGSCCAnalysisManager &CGAM,
1824 ModuleAnalysisManager &MAM) {
1825 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1826 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001827 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1828 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1829 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1830 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1831 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1832}
1833
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001834Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1835 ArrayRef<PipelineElement> Pipeline,
1836 bool VerifyEachPass,
1837 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001838 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001839 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1840 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001841 if (VerifyEachPass)
1842 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001843 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001844 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001845}
1846
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001847// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001848// FIXME: Should this routine accept a TargetMachine or require the caller to
1849// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001850Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1851 StringRef PipelineText,
1852 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001853 auto Pipeline = parsePipelineText(PipelineText);
1854 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001855 return make_error<StringError>(
1856 formatv("invalid pipeline '{0}'", PipelineText).str(),
1857 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001858
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001859 // If the first name isn't at the module layer, wrap the pipeline up
1860 // automatically.
1861 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001862
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001863 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1864 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001865 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001866 } else if (isFunctionPassName(FirstName,
1867 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001868 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001869 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001870 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001871 } else {
1872 for (auto &C : TopLevelPipelineParsingCallbacks)
1873 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001874 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001875
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001876 // Unknown pass or pipeline name!
1877 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1878 return make_error<StringError>(
1879 formatv("unknown {0} name '{1}'",
1880 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1881 .str(),
1882 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001883 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001884 }
1885
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001886 if (auto Err =
1887 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1888 return Err;
1889 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001890}
Chandler Carruthedf59962016-02-18 09:45:17 +00001891
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001892// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001893Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1894 StringRef PipelineText,
1895 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001896 auto Pipeline = parsePipelineText(PipelineText);
1897 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001898 return make_error<StringError>(
1899 formatv("invalid pipeline '{0}'", PipelineText).str(),
1900 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001901
1902 StringRef FirstName = Pipeline->front().Name;
1903 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001904 return make_error<StringError>(
1905 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
1906 PipelineText)
1907 .str(),
1908 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001909
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001910 if (auto Err =
1911 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1912 return Err;
1913 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001914}
1915
1916// Primary pass pipeline description parsing routine for a \c
1917// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001918Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1919 StringRef PipelineText,
1920 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001921 auto Pipeline = parsePipelineText(PipelineText);
1922 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001923 return make_error<StringError>(
1924 formatv("invalid pipeline '{0}'", PipelineText).str(),
1925 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001926
1927 StringRef FirstName = Pipeline->front().Name;
1928 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001929 return make_error<StringError>(
1930 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
1931 PipelineText)
1932 .str(),
1933 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001934
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001935 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1936 DebugLogging))
1937 return Err;
1938 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001939}
1940
1941// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001942Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1943 StringRef PipelineText,
1944 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001945 auto Pipeline = parsePipelineText(PipelineText);
1946 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001947 return make_error<StringError>(
1948 formatv("invalid pipeline '{0}'", PipelineText).str(),
1949 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001950
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001951 if (auto Err =
1952 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1953 return Err;
1954
1955 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001956}
1957
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001958Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00001959 // If the pipeline just consists of the word 'default' just replace the AA
1960 // manager with our default one.
1961 if (PipelineText == "default") {
1962 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001963 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00001964 }
1965
Chandler Carruthedf59962016-02-18 09:45:17 +00001966 while (!PipelineText.empty()) {
1967 StringRef Name;
1968 std::tie(Name, PipelineText) = PipelineText.split(',');
1969 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001970 return make_error<StringError>(
1971 formatv("unknown alias analysis name '{0}'", Name).str(),
1972 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00001973 }
1974
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001975 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00001976}