blob: 21003c0be7e1f6840c8e9d523ba8c3b4c7dfac08 [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"
Hongbin Zheng3f978402016-02-25 17:54:07 +000044#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000045#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000046#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000049#include "llvm/Analysis/ScopedNoAliasAA.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000050#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000051#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000052#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000053#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000054#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000055#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000056#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000057#include "llvm/IR/PassManager.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000058#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000059#include "llvm/Support/Debug.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000060#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000061#include "llvm/Target/TargetMachine.h"
Xinliang David Li64dbb292016-06-05 05:12:23 +000062#include "llvm/Transforms/GCOVProfiler.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000063#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000064#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000065#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000066#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000067#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000068#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000069#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000070#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000071#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000072#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000073#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000074#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000075#include "llvm/Transforms/IPO/GlobalSplit.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000076#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000077#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000078#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000079#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000080#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000081#include "llvm/Transforms/IPO/SCCP.h"
Justin Bogner21e15372015-10-30 23:28:12 +000082#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Davide Italianod737dd22016-06-14 21:44:19 +000083#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000084#include "llvm/Transforms/InstCombine/InstCombine.h"
Xinliang David Lie6b89292016-04-18 17:47:38 +000085#include "llvm/Transforms/InstrProfiling.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000086#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000087#include "llvm/Transforms/PGOInstrumentation.h"
Xinliang David Lid38392e2016-05-27 23:20:16 +000088#include "llvm/Transforms/SampleProfile.h"
Justin Bogner19b67992015-10-30 23:13:18 +000089#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +000090#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +000091#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +000092#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +000093#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +000094#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +000095#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +000096#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +000097#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +000098#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +000099#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000100#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000101#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000102#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000103#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Sean Silva46590d52016-06-14 00:51:09 +0000104#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000105#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000106#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000107#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000108#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000109#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000110#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Dehao Chendcafd5e2016-07-15 16:42:11 +0000111#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000112#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000113#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000114#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000115#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000116#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000117#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000118#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000119#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000120#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000121#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000122#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Sean Silva6347df02016-06-14 02:44:55 +0000123#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000124#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000125#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000126#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000127#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000128#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000129#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000130#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000131#include "llvm/Transforms/Scalar/SROA.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000132#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000133#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000134#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000135#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000136#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000137#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000138#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000139#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000140#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000141#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000142#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000143#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000144#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000145#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000146#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Davide Italiano16284df2016-07-07 21:14:36 +0000147#include "llvm/Transforms/Utils/SimplifyInstructions.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000148#include "llvm/Transforms/Utils/SymbolRewriter.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000149#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000150#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000151
Chandler Carruth66445382014-01-11 08:16:35 +0000152
153using namespace llvm;
154
Chandler Carruth719ffe12017-02-12 05:38:04 +0000155static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
156 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000157static cl::opt<bool>
158 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
159 cl::Hidden, cl::ZeroOrMore,
160 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000161
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000162static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000163 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000164 cl::Hidden, cl::ZeroOrMore,
165 cl::desc("Run NewGVN instead of GVN"));
166
Geoff Berry3cca1da2017-06-10 15:20:03 +0000167static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000168 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
169 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000170
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000171static cl::opt<bool> EnableGVNHoist(
172 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
173 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
174
Davide Italianobe1b6a92017-06-03 23:18:29 +0000175static cl::opt<bool> EnableGVNSink(
176 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
177 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
178
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000179static Regex DefaultAliasRegex(
180 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000181
Chandler Carruthe3f50642016-12-22 06:59:15 +0000182static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
183 switch (Level) {
184 case PassBuilder::O0:
185 case PassBuilder::O1:
186 case PassBuilder::O2:
187 case PassBuilder::O3:
188 return false;
189
190 case PassBuilder::Os:
191 case PassBuilder::Oz:
192 return true;
193 }
194 llvm_unreachable("Invalid optimization level!");
195}
196
Chandler Carruth66445382014-01-11 08:16:35 +0000197namespace {
198
Chandler Carruthd8330982014-01-12 09:34:22 +0000199/// \brief No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000200struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000201 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000202 return PreservedAnalyses::all();
203 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000204 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000205};
206
Chandler Carruth0b576b32015-01-06 02:50:06 +0000207/// \brief No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000208class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
209 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000210 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000211
212public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000213 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000214 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000215 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000216};
217
Chandler Carruth572e3402014-04-21 11:12:00 +0000218/// \brief No-op CGSCC pass which does nothing.
219struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000220 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
221 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000222 return PreservedAnalyses::all();
223 }
224 static StringRef name() { return "NoOpCGSCCPass"; }
225};
226
Chandler Carruth0b576b32015-01-06 02:50:06 +0000227/// \brief No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000228class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
229 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000230 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000231
232public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000233 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000234 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000235 return Result();
236 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000237 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000238};
239
Chandler Carruthd8330982014-01-12 09:34:22 +0000240/// \brief No-op function pass which does nothing.
241struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000242 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000243 return PreservedAnalyses::all();
244 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000245 static StringRef name() { return "NoOpFunctionPass"; }
246};
247
Chandler Carruth0b576b32015-01-06 02:50:06 +0000248/// \brief No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000249class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
250 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000251 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000252
253public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000254 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000255 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000256 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000257};
258
Justin Bognereecc3c82016-02-25 07:23:08 +0000259/// \brief No-op loop pass which does nothing.
260struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000261 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
262 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000263 return PreservedAnalyses::all();
264 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000265 static StringRef name() { return "NoOpLoopPass"; }
266};
267
268/// \brief No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000269class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
270 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000271 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000272
273public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000274 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000275 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
276 return Result();
277 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000278 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000279};
280
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000281AnalysisKey NoOpModuleAnalysis::Key;
282AnalysisKey NoOpCGSCCAnalysis::Key;
283AnalysisKey NoOpFunctionAnalysis::Key;
284AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000285
Chandler Carruth66445382014-01-11 08:16:35 +0000286} // End anonymous namespace.
287
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000288void PassBuilder::invokePeepholeEPCallbacks(
289 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
290 for (auto &C : PeepholeEPCallbacks)
291 C(FPM, Level);
292}
293
Chandler Carruth1ff77242015-03-07 09:02:36 +0000294void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000295#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000296 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000297#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000298
299 for (auto &C : ModuleAnalysisRegistrationCallbacks)
300 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000301}
302
Chandler Carruth1ff77242015-03-07 09:02:36 +0000303void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000304#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000305 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000306#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000307
308 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
309 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000310}
311
Chandler Carruth1ff77242015-03-07 09:02:36 +0000312void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000313#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000314 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000315#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000316
317 for (auto &C : FunctionAnalysisRegistrationCallbacks)
318 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000319}
320
Justin Bognereecc3c82016-02-25 07:23:08 +0000321void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000322#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000323 LAM.registerPass([&] { return CREATE_PASS; });
324#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000325
326 for (auto &C : LoopAnalysisRegistrationCallbacks)
327 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000328}
329
Chandler Carruthe3f50642016-12-22 06:59:15 +0000330FunctionPassManager
331PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000332 ThinLTOPhase Phase,
333 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000334 assert(Level != O0 && "Must request optimizations!");
335 FunctionPassManager FPM(DebugLogging);
336
337 // Form SSA out of local memory accesses after breaking apart aggregates into
338 // scalars.
339 FPM.addPass(SROA());
340
341 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000342 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000343
Davide Italianoc3688312017-06-01 23:08:14 +0000344 // Hoisting of scalars and load expressions.
345 if (EnableGVNHoist)
346 FPM.addPass(GVNHoistPass());
347
Davide Italianobe1b6a92017-06-03 23:18:29 +0000348 // Global value numbering based sinking.
349 if (EnableGVNSink) {
350 FPM.addPass(GVNSinkPass());
351 FPM.addPass(SimplifyCFGPass());
352 }
353
Chandler Carruthe3f50642016-12-22 06:59:15 +0000354 // Speculative execution if the target has divergent branches; otherwise nop.
355 FPM.addPass(SpeculativeExecutionPass());
356
357 // Optimize based on known information about branches, and cleanup afterward.
358 FPM.addPass(JumpThreadingPass());
359 FPM.addPass(CorrelatedValuePropagationPass());
360 FPM.addPass(SimplifyCFGPass());
361 FPM.addPass(InstCombinePass());
362
363 if (!isOptimizingForSize(Level))
364 FPM.addPass(LibCallsShrinkWrapPass());
365
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000366 invokePeepholeEPCallbacks(FPM, Level);
367
Rong Xue1f42452017-10-23 22:21:29 +0000368 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
369 // using the size value profile. Don't perform this when optimizing for size.
370 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
371 !isOptimizingForSize(Level))
372 FPM.addPass(PGOMemOPSizeOpt());
373
Chandler Carruthe3f50642016-12-22 06:59:15 +0000374 FPM.addPass(TailCallElimPass());
375 FPM.addPass(SimplifyCFGPass());
376
377 // Form canonically associated expression trees, and simplify the trees using
378 // basic mathematical properties. For example, this will form (nearly)
379 // minimal multiplication trees.
380 FPM.addPass(ReassociatePass());
381
382 // Add the primary loop simplification pipeline.
383 // FIXME: Currently this is split into two loop pass pipelines because we run
384 // some function passes in between them. These can and should be replaced by
385 // loop pass equivalenst but those aren't ready yet. Specifically,
386 // `SimplifyCFGPass` and `InstCombinePass` are used. We have
387 // `LoopSimplifyCFGPass` which isn't yet powerful enough, and the closest to
388 // the other we have is `LoopInstSimplify`.
389 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
390
391 // Rotate Loop - disable header duplication at -Oz
392 LPM1.addPass(LoopRotatePass(Level != Oz));
393 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000394 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000395 LPM2.addPass(IndVarSimplifyPass());
396 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000397
398 for (auto &C : LateLoopOptimizationsEPCallbacks)
399 C(LPM2, Level);
400
Chandler Carruth79b733b2017-01-26 23:21:17 +0000401 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000402 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000403 // because it changes IR to makes profile annotation in back compile
404 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000405 if (Phase != ThinLTOPhase::PreLink ||
406 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000407 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000408
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000409 for (auto &C : LoopOptimizerEndEPCallbacks)
410 C(LPM2, Level);
411
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000412 // We provide the opt remark emitter pass for LICM to use. We only need to do
413 // this once as it is immutable.
414 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000415 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000416 FPM.addPass(SimplifyCFGPass());
417 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000418 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000419
420 // Eliminate redundancies.
421 if (Level != O1) {
422 // These passes add substantial compile time so skip them at O1.
423 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000424 if (RunNewGVN)
425 FPM.addPass(NewGVNPass());
426 else
427 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000428 }
429
430 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
431 FPM.addPass(MemCpyOptPass());
432
433 // Sparse conditional constant propagation.
434 // FIXME: It isn't clear why we do this *after* loop passes rather than
435 // before...
436 FPM.addPass(SCCPPass());
437
438 // Delete dead bit computations (instcombine runs after to fold away the dead
439 // computations, and then ADCE will run later to exploit any new DCE
440 // opportunities that creates).
441 FPM.addPass(BDCEPass());
442
443 // Run instcombine after redundancy and dead bit elimination to exploit
444 // opportunities opened up by them.
445 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000446 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000447
448 // Re-consider control flow based optimizations after redundancy elimination,
449 // redo DCE, etc.
450 FPM.addPass(JumpThreadingPass());
451 FPM.addPass(CorrelatedValuePropagationPass());
452 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000453 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000454
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000455 for (auto &C : ScalarOptimizerLateEPCallbacks)
456 C(FPM, Level);
457
Chandler Carruthe3f50642016-12-22 06:59:15 +0000458 // Finally, do an expensive DCE pass to catch all the dead code exposed by
459 // the simplifications and basic cleanup after all the simplifications.
460 FPM.addPass(ADCEPass());
461 FPM.addPass(SimplifyCFGPass());
462 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000463 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000464
465 return FPM;
466}
467
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000468void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
469 PassBuilder::OptimizationLevel Level,
470 bool RunProfileGen,
471 std::string ProfileGenFile,
472 std::string ProfileUseFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000473 // Generally running simplification passes and the inliner with an high
474 // threshold results in smaller executables, but there may be cases where
475 // the size grows, so let's be conservative here and skip this simplification
476 // at -Os/Oz.
477 if (!isOptimizingForSize(Level)) {
478 InlineParams IP;
479
480 // In the old pass manager, this is a cl::opt. Should still this be one?
481 IP.DefaultThreshold = 75;
482
483 // FIXME: The hint threshold has the same value used by the regular inliner.
484 // This should probably be lowered after performance testing.
485 // FIXME: this comment is cargo culted from the old pass manager, revisit).
486 IP.HintThreshold = 325;
487
488 CGSCCPassManager CGPipeline(DebugLogging);
489
490 CGPipeline.addPass(InlinerPass(IP));
491
492 FunctionPassManager FPM;
493 FPM.addPass(SROA());
494 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
495 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
496 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000497 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000498
Davide Italiano513dfaa2017-02-13 15:26:22 +0000499 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
500
501 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
502 }
503
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000504 // Delete anything that is now dead to make sure that we don't instrument
505 // dead code. Instrumentation can end up keeping dead code around and
506 // dramatically increase code size.
507 MPM.addPass(GlobalDCEPass());
508
Davide Italiano513dfaa2017-02-13 15:26:22 +0000509 if (RunProfileGen) {
510 MPM.addPass(PGOInstrumentationGen());
511
Xinliang David Lib67530e2017-06-25 00:26:43 +0000512 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000513 FPM.addPass(
514 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000515 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
516
Davide Italiano513dfaa2017-02-13 15:26:22 +0000517 // Add the profile lowering pass.
518 InstrProfOptions Options;
519 if (!ProfileGenFile.empty())
520 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000521 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000522 MPM.addPass(InstrProfiling(Options));
523 }
524
525 if (!ProfileUseFile.empty())
526 MPM.addPass(PGOInstrumentationUse(ProfileUseFile));
527}
528
Easwaran Raman8249fac2017-06-28 13:33:49 +0000529static InlineParams
530getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
531 auto O3 = PassBuilder::O3;
532 unsigned OptLevel = Level > O3 ? 2 : Level;
533 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
534 return getInlineParams(OptLevel, SizeLevel);
535}
536
Chandler Carruthe3f50642016-12-22 06:59:15 +0000537ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000538PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000539 ThinLTOPhase Phase,
540 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000541 ModulePassManager MPM(DebugLogging);
542
Chandler Carruthe3f50642016-12-22 06:59:15 +0000543 // Do basic inference of function attributes from known properties of system
544 // libraries and other oracles.
545 MPM.addPass(InferFunctionAttrsPass());
546
547 // Create an early function pass manager to cleanup the output of the
548 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000549 FunctionPassManager EarlyFPM(DebugLogging);
550 EarlyFPM.addPass(SimplifyCFGPass());
551 EarlyFPM.addPass(SROA());
552 EarlyFPM.addPass(EarlyCSEPass());
553 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000554 if (Level == O3)
555 EarlyFPM.addPass(CallSiteSplittingPass());
556
Dehao Chen08f88312017-08-07 20:23:20 +0000557 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
558 // to convert bitcast to direct calls so that they can be inlined during the
559 // profile annotation prepration step.
560 // More details about SamplePGO design can be found in:
561 // https://research.google.com/pubs/pub45290.html
562 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
563 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
564 Phase == ThinLTOPhase::PostLink)
565 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000566 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000567
Dehao Chen08f88312017-08-07 20:23:20 +0000568 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
569 // Annotate sample profile right after early FPM to ensure freshness of
570 // the debug info.
Dehao Chend26dae02017-10-01 05:24:51 +0000571 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
572 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000573 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
574 // for the profile annotation to be accurate in the ThinLTO backend.
575 if (Phase != ThinLTOPhase::PreLink)
576 // We perform early indirect call promotion here, before globalopt.
577 // This is important for the ThinLTO backend phase because otherwise
578 // imported available_externally functions look unreferenced and are
579 // removed.
580 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
581 true));
582 }
583
Chandler Carruthe3f50642016-12-22 06:59:15 +0000584 // Interprocedural constant propagation now that basic cleanup has occured
585 // and prior to optimizing globals.
586 // FIXME: This position in the pipeline hasn't been carefully considered in
587 // years, it should be re-analyzed.
588 MPM.addPass(IPSCCPPass());
589
Matthew Simpsoncb585582017-10-25 13:40:08 +0000590 // Attach metadata to indirect call sites indicating the set of functions
591 // they may target at run-time. This should follow IPSCCP.
592 MPM.addPass(CalledValuePropagationPass());
593
Chandler Carruthe3f50642016-12-22 06:59:15 +0000594 // Optimize globals to try and fold them into constants.
595 MPM.addPass(GlobalOptPass());
596
597 // Promote any localized globals to SSA registers.
598 // FIXME: Should this instead by a run of SROA?
599 // FIXME: We should probably run instcombine and simplify-cfg afterward to
600 // delete control flows that are dead once globals have been folded to
601 // constants.
602 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
603
604 // Remove any dead arguments exposed by cleanups and constand folding
605 // globals.
606 MPM.addPass(DeadArgumentEliminationPass());
607
608 // Create a small function pass pipeline to cleanup after all the global
609 // optimizations.
610 FunctionPassManager GlobalCleanupPM(DebugLogging);
611 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000612 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
613
Chandler Carruthe3f50642016-12-22 06:59:15 +0000614 GlobalCleanupPM.addPass(SimplifyCFGPass());
615 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
616
Dehao Chen89d32262017-08-02 01:28:31 +0000617 // Add all the requested passes for instrumentation PGO, if requested.
618 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
619 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
620 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
621 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile);
622 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000623 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000624
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000625 // Require the GlobalsAA analysis for the module so we can query it within
626 // the CGSCC pipeline.
627 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000628
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000629 // Require the ProfileSummaryAnalysis for the module so we can query it within
630 // the inliner pass.
631 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
632
Chandler Carruthe3f50642016-12-22 06:59:15 +0000633 // Now begin the main postorder CGSCC pipeline.
634 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
635 // manager and trying to emulate its precise behavior. Much of this doesn't
636 // make a lot of sense and we should revisit the core CGSCC structure.
637 CGSCCPassManager MainCGPipeline(DebugLogging);
638
639 // Note: historically, the PruneEH pass was run first to deduce nounwind and
640 // generally clean up exception handling overhead. It isn't clear this is
641 // valuable as the inliner doesn't currently care whether it is inlining an
642 // invoke or a call.
643
644 // Run the inliner first. The theory is that we are walking bottom-up and so
645 // the callees have already been fully optimized, and we want to inline them
646 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000647 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000648 // because it makes profile annotation in the backend inaccurate.
649 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000650 if (Phase == ThinLTOPhase::PreLink &&
651 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000652 IP.HotCallSiteThreshold = 0;
653 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000654
655 // Now deduce any function attributes based in the current code.
656 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
657
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000658 // When at O3 add argument promotion to the pass pipeline.
659 // FIXME: It isn't at all clear why this should be limited to O3.
660 if (Level == O3)
661 MainCGPipeline.addPass(ArgumentPromotionPass());
662
Chandler Carruthe3f50642016-12-22 06:59:15 +0000663 // Lastly, add the core function simplification pipeline nested inside the
664 // CGSCC walk.
665 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000666 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000667
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000668 for (auto &C : CGSCCOptimizerLateEPCallbacks)
669 C(MainCGPipeline, Level);
670
Chandler Carruth719ffe12017-02-12 05:38:04 +0000671 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
672 // to detect when we devirtualize indirect calls and iterate the SCC passes
673 // in that case to try and catch knock-on inlining or function attrs
674 // opportunities. Then we add it to the module pipeline by walking the SCCs
675 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000676 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000677 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000678 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000679
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000680 return MPM;
681}
682
683ModulePassManager
684PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
685 bool DebugLogging) {
686 ModulePassManager MPM(DebugLogging);
687
688 // Optimize globals now that the module is fully simplified.
689 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000690 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000691
Xinliang David Li126157c2017-05-22 16:41:57 +0000692 // Run partial inlining pass to partially inline functions that have
693 // large bodies.
694 if (RunPartialInlining)
695 MPM.addPass(PartialInlinerPass());
696
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000697 // Remove avail extern fns and globals definitions since we aren't compiling
698 // an object file for later LTO. For LTO we want to preserve these so they
699 // are eligible for inlining at link-time. Note if they are unreferenced they
700 // will be removed by GlobalDCE later, so this only impacts referenced
701 // available externally globals. Eventually they will be suppressed during
702 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
703 // may make globals referenced by available external functions dead and saves
704 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000705 MPM.addPass(EliminateAvailableExternallyPass());
706
707 // Do RPO function attribute inference across the module to forward-propagate
708 // attributes where applicable.
709 // FIXME: Is this really an optimization rather than a canonicalization?
710 MPM.addPass(ReversePostOrderFunctionAttrsPass());
711
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000712 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000713 // useful as the above will have inlined, DCE'ed, and function-attr
714 // propagated everything. We should at this point have a reasonably minimal
715 // and richly annotated call graph. By computing aliasing and mod/ref
716 // information for all local globals here, the late loop passes and notably
717 // the vectorizer will be able to use them to help recognize vectorizable
718 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000719 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000720
721 FunctionPassManager OptimizePM(DebugLogging);
722 OptimizePM.addPass(Float2IntPass());
723 // FIXME: We need to run some loop optimizations to re-rotate loops after
724 // simplify-cfg and others undo their rotation.
725
726 // Optimize the loop execution. These passes operate on entire loop nests
727 // rather than on each loop in an inside-out manner, and so they are actually
728 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000729
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000730 for (auto &C : VectorizerStartEPCallbacks)
731 C(OptimizePM, Level);
732
Chandler Carrutha95ff382017-01-27 00:50:21 +0000733 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000734 OptimizePM.addPass(
735 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000736
737 // Distribute loops to allow partial vectorization. I.e. isolate dependences
738 // into separate loop that would otherwise inhibit vectorization. This is
739 // currently only performed for loops marked with the metadata
740 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000741 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000742
743 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000744 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000745
Chandler Carruthbaabda92017-01-27 01:32:26 +0000746 // Eliminate loads by forwarding stores from the previous iteration to loads
747 // of the current iteration.
748 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000749
750 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000751 OptimizePM.addPass(InstCombinePass());
752
Chandler Carrutha95ff382017-01-27 00:50:21 +0000753 // Now that we've formed fast to execute loop structures, we do further
754 // optimizations. These are run afterward as they might block doing complex
755 // analyses and transforms such as what are needed for loop vectorization.
756
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000757 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
758 // GVN, loop transforms, and others have already run, so it's now better to
759 // convert to more optimized IR using more aggressive simplify CFG options.
760 // The extra sinking transform can create larger basic blocks, so do this
761 // before SLP vectorization.
762 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
763 forwardSwitchCondToPhi(true).
764 convertSwitchToLookupTable(true).
765 needCanonicalLoops(false).
766 sinkCommonInsts(true)));
767
Chandler Carruthe3f50642016-12-22 06:59:15 +0000768 // Optimize parallel scalar instruction chains into SIMD instructions.
769 OptimizePM.addPass(SLPVectorizerPass());
770
Chandler Carruthe3f50642016-12-22 06:59:15 +0000771 OptimizePM.addPass(InstCombinePass());
772
773 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000774 // execution resources of an out-of-order processor. We also then need to
775 // clean up redundancies and loop invariant code.
776 // FIXME: It would be really good to use a loop-integrated instruction
777 // combiner for cleanup here so that the unrolling and LICM can be pipelined
778 // across the loop nests.
Teresa Johnsonecd90132017-08-02 20:35:29 +0000779 OptimizePM.addPass(LoopUnrollPass(Level));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000780 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000781 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000782 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000783
784 // Now that we've vectorized and unrolled loops, we may have more refined
785 // alignment information, try to re-derive it here.
786 OptimizePM.addPass(AlignmentFromAssumptionsPass());
787
Chandler Carrutha95ff382017-01-27 00:50:21 +0000788 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
789 // canonicalization pass that enables other optimizations. As a result,
790 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
791 // result too early.
792 OptimizePM.addPass(LoopSinkPass());
793
794 // And finally clean up LCSSA form before generating code.
795 OptimizePM.addPass(InstSimplifierPass());
796
Sanjay Patel6fd43912017-09-09 13:38:18 +0000797 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
798 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
799 // flattening of blocks.
800 OptimizePM.addPass(DivRemPairsPass());
801
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000802 // LoopSink (and other loop passes since the last simplifyCFG) might have
803 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
804 OptimizePM.addPass(SimplifyCFGPass());
805
Chandler Carruthc34f7892017-11-28 11:32:31 +0000806 // Optimize PHIs by speculating around them when profitable. Note that this
807 // pass needs to be run after any PRE or similar pass as it is essentially
808 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
809 OptimizePM.addPass(SpeculateAroundPHIsPass());
810
Chandler Carrutha95ff382017-01-27 00:50:21 +0000811 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000812 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
813
814 // Now we need to do some global optimization transforms.
815 // FIXME: It would seem like these should come first in the optimization
816 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
817 // ordering here.
818 MPM.addPass(GlobalDCEPass());
819 MPM.addPass(ConstantMergePass());
820
821 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000822}
823
Chandler Carruthe3f50642016-12-22 06:59:15 +0000824ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000825PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
826 bool DebugLogging) {
827 assert(Level != O0 && "Must request optimizations for the default pipeline!");
828
829 ModulePassManager MPM(DebugLogging);
830
831 // Force any function attributes we want the rest of the pipeline to observe.
832 MPM.addPass(ForceFunctionAttrsPass());
833
Dehao Chen08f88312017-08-07 20:23:20 +0000834 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000835 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
836
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000837 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000838 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
839 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000840
841 // Now add the optimization pipeline.
842 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
843
844 return MPM;
845}
846
847ModulePassManager
848PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
849 bool DebugLogging) {
850 assert(Level != O0 && "Must request optimizations for the default pipeline!");
851
852 ModulePassManager MPM(DebugLogging);
853
854 // Force any function attributes we want the rest of the pipeline to observe.
855 MPM.addPass(ForceFunctionAttrsPass());
856
Dehao Chen08f88312017-08-07 20:23:20 +0000857 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000858 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
859
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000860 // If we are planning to perform ThinLTO later, we don't bloat the code with
861 // unrolling/vectorization/... now. Just simplify the module as much as we
862 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000863 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
864 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000865
866 // Run partial inlining pass to partially inline functions that have
867 // large bodies.
868 // FIXME: It isn't clear whether this is really the right place to run this
869 // in ThinLTO. Because there is another canonicalization and simplification
870 // phase that will run after the thin link, running this here ends up with
871 // less information than will be available later and it may grow functions in
872 // ways that aren't beneficial.
873 if (RunPartialInlining)
874 MPM.addPass(PartialInlinerPass());
875
876 // Reduce the size of the IR as much as possible.
877 MPM.addPass(GlobalOptPass());
878
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000879 return MPM;
880}
881
882ModulePassManager
883PassBuilder::buildThinLTODefaultPipeline(OptimizationLevel Level,
884 bool DebugLogging) {
885 // FIXME: The summary index is not hooked in the new pass manager yet.
886 // When it's going to be hooked, enable WholeProgramDevirt and LowerTypeTest
887 // here.
888
889 ModulePassManager MPM(DebugLogging);
890
891 // Force any function attributes we want the rest of the pipeline to observe.
892 MPM.addPass(ForceFunctionAttrsPass());
893
894 // During the ThinLTO backend phase we perform early indirect call promotion
895 // here, before globalopt. Otherwise imported available_externally functions
896 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000897 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
898 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000899 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000900 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
901 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000902
903 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000904 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
905 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000906
907 // Now add the optimization pipeline.
908 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
909
910 return MPM;
911}
912
913ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +0000914PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
915 bool DebugLogging) {
916 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000917 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +0000918 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000919}
920
Chandler Carruthe3f50642016-12-22 06:59:15 +0000921ModulePassManager PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
922 bool DebugLogging) {
923 assert(Level != O0 && "Must request optimizations for the default pipeline!");
924 ModulePassManager MPM(DebugLogging);
925
Davide Italiano089a9122017-01-24 00:57:39 +0000926 // Remove unused virtual tables to improve the quality of code generated by
927 // whole-program devirtualization and bitset lowering.
928 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000929
Davide Italiano089a9122017-01-24 00:57:39 +0000930 // Force any function attributes we want the rest of the pipeline to observe.
931 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000932
Davide Italiano089a9122017-01-24 00:57:39 +0000933 // Do basic inference of function attributes from known properties of system
934 // libraries and other oracles.
935 MPM.addPass(InferFunctionAttrsPass());
936
937 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +0000938 FunctionPassManager EarlyFPM(DebugLogging);
939 EarlyFPM.addPass(CallSiteSplittingPass());
940 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
941
Davide Italiano089a9122017-01-24 00:57:39 +0000942 // Indirect call promotion. This should promote all the targets that are
943 // left by the earlier promotion pass that promotes intra-module targets.
944 // This two-step promotion is to save the compile time. For LTO, it should
945 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +0000946 MPM.addPass(PGOIndirectCallPromotion(
947 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +0000948 // Propagate constants at call sites into the functions they call. This
949 // opens opportunities for globalopt (and inlining) by substituting function
950 // pointers passed as arguments to direct uses of functions.
951 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +0000952
953 // Attach metadata to indirect call sites indicating the set of functions
954 // they may target at run-time. This should follow IPSCCP.
955 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +0000956 }
957
958 // Now deduce any function attributes based in the current code.
959 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
960 PostOrderFunctionAttrsPass()));
961
962 // Do RPO function attribute inference across the module to forward-propagate
963 // attributes where applicable.
964 // FIXME: Is this really an optimization rather than a canonicalization?
965 MPM.addPass(ReversePostOrderFunctionAttrsPass());
966
967 // Use inragne annotations on GEP indices to split globals where beneficial.
968 MPM.addPass(GlobalSplitPass());
969
970 // Run whole program optimization of virtual call when the list of callees
971 // is fixed.
972 MPM.addPass(WholeProgramDevirtPass());
973
974 // Stop here at -O1.
975 if (Level == 1)
976 return MPM;
977
978 // Optimize globals to try and fold them into constants.
979 MPM.addPass(GlobalOptPass());
980
981 // Promote any localized globals to SSA registers.
982 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
983
984 // Linking modules together can lead to duplicate global constant, only
985 // keep one copy of each constant.
986 MPM.addPass(ConstantMergePass());
987
988 // Remove unused arguments from functions.
989 MPM.addPass(DeadArgumentEliminationPass());
990
991 // Reduce the code after globalopt and ipsccp. Both can open up significant
992 // simplification opportunities, and both can propagate functions through
993 // function pointers. When this happens, we often have to resolve varargs
994 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000995 FunctionPassManager PeepholeFPM(DebugLogging);
996 PeepholeFPM.addPass(InstCombinePass());
997 invokePeepholeEPCallbacks(PeepholeFPM, Level);
998
999 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001000
1001 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1002 // generally clean up exception handling overhead. It isn't clear this is
1003 // valuable as the inliner doesn't currently care whether it is inlining an
1004 // invoke or a call.
1005 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001006 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1007 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001008
1009 // Optimize globals again after we ran the inliner.
1010 MPM.addPass(GlobalOptPass());
1011
1012 // Garbage collect dead functions.
1013 // FIXME: Add ArgumentPromotion pass after once it's ported.
1014 MPM.addPass(GlobalDCEPass());
1015
1016 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001017 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001018 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001019 invokePeepholeEPCallbacks(FPM, Level);
1020
Davide Italiano089a9122017-01-24 00:57:39 +00001021 FPM.addPass(JumpThreadingPass());
1022
1023 // Break up allocas
1024 FPM.addPass(SROA());
1025
1026 // Run a few AA driver optimizations here and now to cleanup the code.
1027 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1028
1029 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1030 PostOrderFunctionAttrsPass()));
1031 // FIXME: here we run IP alias analysis in the legacy PM.
1032
1033 FunctionPassManager MainFPM;
1034
1035 // FIXME: once we fix LoopPass Manager, add LICM here.
1036 // FIXME: once we provide support for enabling MLSM, add it here.
1037 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001038 if (RunNewGVN)
1039 MainFPM.addPass(NewGVNPass());
1040 else
1041 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001042
1043 // Remove dead memcpy()'s.
1044 MainFPM.addPass(MemCpyOptPass());
1045
1046 // Nuke dead stores.
1047 MainFPM.addPass(DSEPass());
1048
1049 // FIXME: at this point, we run a bunch of loop passes:
1050 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1051 // loopVectorize. Enable them once the remaining issue with LPM
1052 // are sorted out.
1053
1054 MainFPM.addPass(InstCombinePass());
1055 MainFPM.addPass(SimplifyCFGPass());
1056 MainFPM.addPass(SCCPPass());
1057 MainFPM.addPass(InstCombinePass());
1058 MainFPM.addPass(BDCEPass());
1059
1060 // FIXME: We may want to run SLPVectorizer here.
1061 // After vectorization, assume intrinsics may tell us more
1062 // about pointer alignments.
1063#if 0
1064 MainFPM.add(AlignmentFromAssumptionsPass());
1065#endif
1066
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001067 // FIXME: Conditionally run LoadCombine here, after it's ported
1068 // (in case we still have this pass, given its questionable usefulness).
1069
Davide Italiano089a9122017-01-24 00:57:39 +00001070 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001071 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001072 MainFPM.addPass(JumpThreadingPass());
1073 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1074
1075 // Create a function that performs CFI checks for cross-DSO calls with
1076 // targets in the current module.
1077 MPM.addPass(CrossDSOCFIPass());
1078
1079 // Lower type metadata and the type.test intrinsic. This pass supports
1080 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1081 // to be run at link time if CFI is enabled. This pass does nothing if
1082 // CFI is disabled.
1083 // Enable once we add support for the summary in the new PM.
1084#if 0
Peter Collingbourne857aba42017-02-09 21:45:01 +00001085 MPM.addPass(LowerTypeTestsPass(Summary ? PassSummaryAction::Export :
1086 PassSummaryAction::None,
Davide Italiano089a9122017-01-24 00:57:39 +00001087 Summary));
1088#endif
1089
1090 // Add late LTO optimization passes.
1091 // Delete basic blocks, which optimization passes may have killed.
1092 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1093
1094 // Drop bodies of available eternally objects to improve GlobalDCE.
1095 MPM.addPass(EliminateAvailableExternallyPass());
1096
1097 // Now that we have optimized the program, discard unreachable functions.
1098 MPM.addPass(GlobalDCEPass());
1099
1100 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001101 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001102}
1103
Chandler Carruth060ad612016-12-23 20:38:19 +00001104AAManager PassBuilder::buildDefaultAAPipeline() {
1105 AAManager AA;
1106
1107 // The order in which these are registered determines their priority when
1108 // being queried.
1109
1110 // First we register the basic alias analysis that provides the majority of
1111 // per-function local AA logic. This is a stateless, on-demand local set of
1112 // AA techniques.
1113 AA.registerFunctionAnalysis<BasicAA>();
1114
1115 // Next we query fast, specialized alias analyses that wrap IR-embedded
1116 // information about aliasing.
1117 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1118 AA.registerFunctionAnalysis<TypeBasedAA>();
1119
1120 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001121 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1122 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001123 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001124 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001125
1126 return AA;
1127}
1128
Chandler Carruth241bf242016-08-03 07:44:48 +00001129static Optional<int> parseRepeatPassName(StringRef Name) {
1130 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1131 return None;
1132 int Count;
1133 if (Name.getAsInteger(0, Count) || Count <= 0)
1134 return None;
1135 return Count;
1136}
1137
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001138static Optional<int> parseDevirtPassName(StringRef Name) {
1139 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1140 return None;
1141 int Count;
1142 if (Name.getAsInteger(0, Count) || Count <= 0)
1143 return None;
1144 return Count;
1145}
1146
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001147/// Tests whether a pass name starts with a valid prefix for a default pipeline
1148/// alias.
1149static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1150 return Name.startswith("default") || Name.startswith("thinlto") ||
1151 Name.startswith("lto");
1152}
1153
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001154/// Tests whether registered callbacks will accept a given pass name.
1155///
1156/// When parsing a pipeline text, the type of the outermost pipeline may be
1157/// omitted, in which case the type is automatically determined from the first
1158/// pass name in the text. This may be a name that is handled through one of the
1159/// callbacks. We check this through the oridinary parsing callbacks by setting
1160/// up a dummy PassManager in order to not force the client to also handle this
1161/// type of query.
1162template <typename PassManagerT, typename CallbacksT>
1163static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1164 if (!Callbacks.empty()) {
1165 PassManagerT DummyPM;
1166 for (auto &CB : Callbacks)
1167 if (CB(Name, DummyPM, {}))
1168 return true;
1169 }
1170 return false;
1171}
1172
1173template <typename CallbacksT>
1174static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001175 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001176 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001177 return DefaultAliasRegex.match(Name);
1178
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001179 // Explicitly handle pass manager names.
1180 if (Name == "module")
1181 return true;
1182 if (Name == "cgscc")
1183 return true;
1184 if (Name == "function")
1185 return true;
1186
Chandler Carruth241bf242016-08-03 07:44:48 +00001187 // Explicitly handle custom-parsed pass names.
1188 if (parseRepeatPassName(Name))
1189 return true;
1190
Chandler Carruth74a8a222016-06-17 07:15:29 +00001191#define MODULE_PASS(NAME, CREATE_PASS) \
1192 if (Name == NAME) \
1193 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001194#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001195 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001196 return true;
1197#include "PassRegistry.def"
1198
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001199 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001200}
1201
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001202template <typename CallbacksT>
1203static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001204 // Explicitly handle pass manager names.
1205 if (Name == "cgscc")
1206 return true;
1207 if (Name == "function")
1208 return true;
1209
Chandler Carruth241bf242016-08-03 07:44:48 +00001210 // Explicitly handle custom-parsed pass names.
1211 if (parseRepeatPassName(Name))
1212 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001213 if (parseDevirtPassName(Name))
1214 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001215
Chandler Carruth74a8a222016-06-17 07:15:29 +00001216#define CGSCC_PASS(NAME, CREATE_PASS) \
1217 if (Name == NAME) \
1218 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001219#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001220 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001221 return true;
1222#include "PassRegistry.def"
1223
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001224 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001225}
1226
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001227template <typename CallbacksT>
1228static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001229 // Explicitly handle pass manager names.
1230 if (Name == "function")
1231 return true;
1232 if (Name == "loop")
1233 return true;
1234
Chandler Carruth241bf242016-08-03 07:44:48 +00001235 // Explicitly handle custom-parsed pass names.
1236 if (parseRepeatPassName(Name))
1237 return true;
1238
Chandler Carruth74a8a222016-06-17 07:15:29 +00001239#define FUNCTION_PASS(NAME, CREATE_PASS) \
1240 if (Name == NAME) \
1241 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001242#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001243 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001244 return true;
1245#include "PassRegistry.def"
1246
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001247 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001248}
1249
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001250template <typename CallbacksT>
1251static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001252 // Explicitly handle pass manager names.
1253 if (Name == "loop")
1254 return true;
1255
Chandler Carruth241bf242016-08-03 07:44:48 +00001256 // Explicitly handle custom-parsed pass names.
1257 if (parseRepeatPassName(Name))
1258 return true;
1259
Chandler Carruth74a8a222016-06-17 07:15:29 +00001260#define LOOP_PASS(NAME, CREATE_PASS) \
1261 if (Name == NAME) \
1262 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001263#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1264 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1265 return true;
1266#include "PassRegistry.def"
1267
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001268 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001269}
1270
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001271Optional<std::vector<PassBuilder::PipelineElement>>
1272PassBuilder::parsePipelineText(StringRef Text) {
1273 std::vector<PipelineElement> ResultPipeline;
1274
1275 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1276 &ResultPipeline};
1277 for (;;) {
1278 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1279 size_t Pos = Text.find_first_of(",()");
1280 Pipeline.push_back({Text.substr(0, Pos), {}});
1281
1282 // If we have a single terminating name, we're done.
1283 if (Pos == Text.npos)
1284 break;
1285
1286 char Sep = Text[Pos];
1287 Text = Text.substr(Pos + 1);
1288 if (Sep == ',')
1289 // Just a name ending in a comma, continue.
1290 continue;
1291
1292 if (Sep == '(') {
1293 // Push the inner pipeline onto the stack to continue processing.
1294 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1295 continue;
1296 }
1297
1298 assert(Sep == ')' && "Bogus separator!");
1299 // When handling the close parenthesis, we greedily consume them to avoid
1300 // empty strings in the pipeline.
1301 do {
1302 // If we try to pop the outer pipeline we have unbalanced parentheses.
1303 if (PipelineStack.size() == 1)
1304 return None;
1305
1306 PipelineStack.pop_back();
1307 } while (Text.consume_front(")"));
1308
1309 // Check if we've finished parsing.
1310 if (Text.empty())
1311 break;
1312
1313 // Otherwise, the end of an inner pipeline always has to be followed by
1314 // a comma, and then we can continue.
1315 if (!Text.consume_front(","))
1316 return None;
1317 }
1318
1319 if (PipelineStack.size() > 1)
1320 // Unbalanced paretheses.
1321 return None;
1322
1323 assert(PipelineStack.back() == &ResultPipeline &&
1324 "Wrong pipeline at the bottom of the stack!");
1325 return {std::move(ResultPipeline)};
1326}
1327
1328bool PassBuilder::parseModulePass(ModulePassManager &MPM,
1329 const PipelineElement &E, bool VerifyEachPass,
1330 bool DebugLogging) {
1331 auto &Name = E.Name;
1332 auto &InnerPipeline = E.InnerPipeline;
1333
1334 // First handle complex passes like the pass managers which carry pipelines.
1335 if (!InnerPipeline.empty()) {
1336 if (Name == "module") {
1337 ModulePassManager NestedMPM(DebugLogging);
1338 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1339 DebugLogging))
1340 return false;
1341 MPM.addPass(std::move(NestedMPM));
1342 return true;
1343 }
1344 if (Name == "cgscc") {
1345 CGSCCPassManager CGPM(DebugLogging);
1346 if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1347 DebugLogging))
1348 return false;
Chandler Carruth19913b22017-08-11 05:47:13 +00001349 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001350 return true;
1351 }
1352 if (Name == "function") {
1353 FunctionPassManager FPM(DebugLogging);
1354 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1355 DebugLogging))
1356 return false;
1357 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1358 return true;
1359 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001360 if (auto Count = parseRepeatPassName(Name)) {
1361 ModulePassManager NestedMPM(DebugLogging);
1362 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1363 DebugLogging))
1364 return false;
Chandler Carrutha053a882016-08-04 03:52:53 +00001365 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Chandler Carruth241bf242016-08-03 07:44:48 +00001366 return true;
1367 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001368
1369 for (auto &C : ModulePipelineParsingCallbacks)
1370 if (C(Name, MPM, InnerPipeline))
1371 return true;
1372
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001373 // Normal passes can't have pipelines.
1374 return false;
1375 }
1376
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001377 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001378 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001379 SmallVector<StringRef, 3> Matches;
1380 if (!DefaultAliasRegex.match(Name, &Matches))
1381 return false;
1382 assert(Matches.size() == 3 && "Must capture two matched strings!");
1383
Jordan Rosef85a95f2016-07-25 18:34:51 +00001384 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001385 .Case("O0", O0)
1386 .Case("O1", O1)
1387 .Case("O2", O2)
1388 .Case("O3", O3)
1389 .Case("Os", Os)
1390 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001391 if (L == O0)
1392 // At O0 we do nothing at all!
1393 return true;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001394
1395 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001396 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001397 } else if (Matches[1] == "thinlto-pre-link") {
1398 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1399 } else if (Matches[1] == "thinlto") {
1400 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001401 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001402 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001403 } else {
1404 assert(Matches[1] == "lto" && "Not one of the matched options!");
Chandler Carruthe3f50642016-12-22 06:59:15 +00001405 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001406 }
1407 return true;
1408 }
1409
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001410 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001411#define MODULE_PASS(NAME, CREATE_PASS) \
1412 if (Name == NAME) { \
1413 MPM.addPass(CREATE_PASS); \
1414 return true; \
Chandler Carruth52eef882014-01-12 12:15:39 +00001415 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001416#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1417 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001418 MPM.addPass( \
1419 RequireAnalysisPass< \
1420 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001421 return true; \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001422 } \
1423 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001424 MPM.addPass(InvalidateAnalysisPass< \
1425 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001426 return true; \
Chandler Carruth628503e2015-01-06 02:10:51 +00001427 }
1428#include "PassRegistry.def"
1429
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001430 for (auto &C : ModulePipelineParsingCallbacks)
1431 if (C(Name, MPM, InnerPipeline))
1432 return true;
Chandler Carruth66445382014-01-11 08:16:35 +00001433 return false;
1434}
1435
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001436bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1437 const PipelineElement &E, bool VerifyEachPass,
1438 bool DebugLogging) {
1439 auto &Name = E.Name;
1440 auto &InnerPipeline = E.InnerPipeline;
1441
1442 // First handle complex passes like the pass managers which carry pipelines.
1443 if (!InnerPipeline.empty()) {
1444 if (Name == "cgscc") {
1445 CGSCCPassManager NestedCGPM(DebugLogging);
1446 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1447 DebugLogging))
1448 return false;
1449 // Add the nested pass manager with the appropriate adaptor.
1450 CGPM.addPass(std::move(NestedCGPM));
1451 return true;
1452 }
1453 if (Name == "function") {
1454 FunctionPassManager FPM(DebugLogging);
1455 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1456 DebugLogging))
1457 return false;
1458 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001459 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001460 return true;
1461 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001462 if (auto Count = parseRepeatPassName(Name)) {
1463 CGSCCPassManager NestedCGPM(DebugLogging);
1464 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1465 DebugLogging))
1466 return false;
Chandler Carrutha053a882016-08-04 03:52:53 +00001467 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Chandler Carruth241bf242016-08-03 07:44:48 +00001468 return true;
1469 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001470 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1471 CGSCCPassManager NestedCGPM(DebugLogging);
1472 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1473 DebugLogging))
1474 return false;
Chandler Carruth19913b22017-08-11 05:47:13 +00001475 CGPM.addPass(
1476 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001477 return true;
1478 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001479
1480 for (auto &C : CGSCCPipelineParsingCallbacks)
1481 if (C(Name, CGPM, InnerPipeline))
1482 return true;
1483
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001484 // Normal passes can't have pipelines.
1485 return false;
1486 }
1487
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001488// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001489#define CGSCC_PASS(NAME, CREATE_PASS) \
1490 if (Name == NAME) { \
1491 CGPM.addPass(CREATE_PASS); \
1492 return true; \
1493 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001494#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1495 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001496 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001497 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001498 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1499 CGSCCUpdateResult &>()); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001500 return true; \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001501 } \
1502 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001503 CGPM.addPass(InvalidateAnalysisPass< \
1504 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001505 return true; \
Chandler Carruth628503e2015-01-06 02:10:51 +00001506 }
1507#include "PassRegistry.def"
1508
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001509 for (auto &C : CGSCCPipelineParsingCallbacks)
1510 if (C(Name, CGPM, InnerPipeline))
1511 return true;
Chandler Carruth572e3402014-04-21 11:12:00 +00001512 return false;
1513}
1514
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001515bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1516 const PipelineElement &E,
1517 bool VerifyEachPass, bool DebugLogging) {
1518 auto &Name = E.Name;
1519 auto &InnerPipeline = E.InnerPipeline;
1520
1521 // First handle complex passes like the pass managers which carry pipelines.
1522 if (!InnerPipeline.empty()) {
1523 if (Name == "function") {
1524 FunctionPassManager NestedFPM(DebugLogging);
1525 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1526 DebugLogging))
1527 return false;
1528 // Add the nested pass manager with the appropriate adaptor.
1529 FPM.addPass(std::move(NestedFPM));
1530 return true;
1531 }
1532 if (Name == "loop") {
1533 LoopPassManager LPM(DebugLogging);
1534 if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1535 DebugLogging))
1536 return false;
1537 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001538 FPM.addPass(
1539 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001540 return true;
1541 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001542 if (auto Count = parseRepeatPassName(Name)) {
1543 FunctionPassManager NestedFPM(DebugLogging);
1544 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1545 DebugLogging))
1546 return false;
Chandler Carrutha053a882016-08-04 03:52:53 +00001547 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Chandler Carruth241bf242016-08-03 07:44:48 +00001548 return true;
1549 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001550
1551 for (auto &C : FunctionPipelineParsingCallbacks)
1552 if (C(Name, FPM, InnerPipeline))
1553 return true;
1554
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001555 // Normal passes can't have pipelines.
1556 return false;
1557 }
1558
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001559// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001560#define FUNCTION_PASS(NAME, CREATE_PASS) \
1561 if (Name == NAME) { \
1562 FPM.addPass(CREATE_PASS); \
1563 return true; \
Chandler Carruth52eef882014-01-12 12:15:39 +00001564 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001565#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1566 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001567 FPM.addPass( \
1568 RequireAnalysisPass< \
1569 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001570 return true; \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001571 } \
1572 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001573 FPM.addPass(InvalidateAnalysisPass< \
1574 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001575 return true; \
Chandler Carruth628503e2015-01-06 02:10:51 +00001576 }
1577#include "PassRegistry.def"
1578
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001579 for (auto &C : FunctionPipelineParsingCallbacks)
1580 if (C(Name, FPM, InnerPipeline))
1581 return true;
Chandler Carruthd8330982014-01-12 09:34:22 +00001582 return false;
1583}
1584
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001585bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001586 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001587 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001588 auto &InnerPipeline = E.InnerPipeline;
1589
1590 // First handle complex passes like the pass managers which carry pipelines.
1591 if (!InnerPipeline.empty()) {
1592 if (Name == "loop") {
1593 LoopPassManager NestedLPM(DebugLogging);
1594 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1595 DebugLogging))
1596 return false;
1597 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001598 LPM.addPass(std::move(NestedLPM));
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001599 return true;
1600 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001601 if (auto Count = parseRepeatPassName(Name)) {
1602 LoopPassManager NestedLPM(DebugLogging);
1603 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1604 DebugLogging))
1605 return false;
Chandler Carrutha053a882016-08-04 03:52:53 +00001606 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Chandler Carruth241bf242016-08-03 07:44:48 +00001607 return true;
1608 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001609
1610 for (auto &C : LoopPipelineParsingCallbacks)
1611 if (C(Name, LPM, InnerPipeline))
1612 return true;
1613
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001614 // Normal passes can't have pipelines.
1615 return false;
1616 }
1617
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001618// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001619#define LOOP_PASS(NAME, CREATE_PASS) \
1620 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001621 LPM.addPass(CREATE_PASS); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001622 return true; \
1623 }
1624#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1625 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001626 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001627 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1628 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1629 LPMUpdater &>()); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001630 return true; \
1631 } \
1632 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001633 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001634 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001635 return true; \
1636 }
1637#include "PassRegistry.def"
1638
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001639 for (auto &C : LoopPipelineParsingCallbacks)
1640 if (C(Name, LPM, InnerPipeline))
1641 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001642 return false;
1643}
1644
Chandler Carruthedf59962016-02-18 09:45:17 +00001645bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001646#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1647 if (Name == NAME) { \
1648 AA.registerModuleAnalysis< \
1649 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1650 return true; \
1651 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001652#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1653 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001654 AA.registerFunctionAnalysis< \
1655 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001656 return true; \
1657 }
1658#include "PassRegistry.def"
1659
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001660 for (auto &C : AAParsingCallbacks)
1661 if (C(Name, AA))
1662 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001663 return false;
1664}
1665
Justin Bognereecc3c82016-02-25 07:23:08 +00001666bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001667 ArrayRef<PipelineElement> Pipeline,
Justin Bognereecc3c82016-02-25 07:23:08 +00001668 bool VerifyEachPass,
1669 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001670 for (const auto &Element : Pipeline) {
1671 if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1672 return false;
1673 // FIXME: No verifier support for Loop passes!
Justin Bognereecc3c82016-02-25 07:23:08 +00001674 }
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001675 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001676}
1677
Chandler Carruth1ff77242015-03-07 09:02:36 +00001678bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001679 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001680 bool VerifyEachPass,
1681 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001682 for (const auto &Element : Pipeline) {
1683 if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1684 return false;
1685 if (VerifyEachPass)
1686 FPM.addPass(VerifierPass());
Chandler Carruthd8330982014-01-12 09:34:22 +00001687 }
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001688 return true;
Chandler Carruthd8330982014-01-12 09:34:22 +00001689}
1690
Chandler Carruth1ff77242015-03-07 09:02:36 +00001691bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001692 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001693 bool VerifyEachPass,
1694 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001695 for (const auto &Element : Pipeline) {
1696 if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1697 return false;
1698 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001699 }
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001700 return true;
Chandler Carruth572e3402014-04-21 11:12:00 +00001701}
1702
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001703void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1704 FunctionAnalysisManager &FAM,
1705 CGSCCAnalysisManager &CGAM,
1706 ModuleAnalysisManager &MAM) {
1707 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1708 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001709 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1710 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1711 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1712 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1713 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1714}
1715
Chandler Carruth1ff77242015-03-07 09:02:36 +00001716bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001717 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001718 bool VerifyEachPass,
1719 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001720 for (const auto &Element : Pipeline) {
1721 if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1722 return false;
1723 if (VerifyEachPass)
1724 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001725 }
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001726 return true;
Chandler Carruth66445382014-01-11 08:16:35 +00001727}
1728
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001729// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001730// FIXME: Should this routine accept a TargetMachine or require the caller to
1731// pre-populate the analysis managers with target-specific stuff?
Chandler Carruth1ff77242015-03-07 09:02:36 +00001732bool PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1733 StringRef PipelineText, bool VerifyEachPass,
1734 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001735 auto Pipeline = parsePipelineText(PipelineText);
1736 if (!Pipeline || Pipeline->empty())
1737 return false;
Chandler Carruth66445382014-01-11 08:16:35 +00001738
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001739 // If the first name isn't at the module layer, wrap the pipeline up
1740 // automatically.
1741 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001742
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001743 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1744 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001745 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001746 } else if (isFunctionPassName(FirstName,
1747 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001748 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001749 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001750 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001751 } else {
1752 for (auto &C : TopLevelPipelineParsingCallbacks)
1753 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1754 return true;
1755
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001756 // Unknown pass name!
Chandler Carruth572e3402014-04-21 11:12:00 +00001757 return false;
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001758 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001759 }
1760
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001761 return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging);
Chandler Carruth66445382014-01-11 08:16:35 +00001762}
Chandler Carruthedf59962016-02-18 09:45:17 +00001763
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001764// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
1765bool PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1766 StringRef PipelineText, bool VerifyEachPass,
1767 bool DebugLogging) {
1768 auto Pipeline = parsePipelineText(PipelineText);
1769 if (!Pipeline || Pipeline->empty())
1770 return false;
1771
1772 StringRef FirstName = Pipeline->front().Name;
1773 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
1774 return false;
1775
1776 return parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1777}
1778
1779// Primary pass pipeline description parsing routine for a \c
1780// FunctionPassManager
1781bool PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1782 StringRef PipelineText, bool VerifyEachPass,
1783 bool DebugLogging) {
1784 auto Pipeline = parsePipelineText(PipelineText);
1785 if (!Pipeline || Pipeline->empty())
1786 return false;
1787
1788 StringRef FirstName = Pipeline->front().Name;
1789 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
1790 return false;
1791
1792 return parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1793 DebugLogging);
1794}
1795
1796// Primary pass pipeline description parsing routine for a \c LoopPassManager
1797bool PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1798 StringRef PipelineText, bool VerifyEachPass,
1799 bool DebugLogging) {
1800 auto Pipeline = parsePipelineText(PipelineText);
1801 if (!Pipeline || Pipeline->empty())
1802 return false;
1803
1804 return parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1805}
1806
Chandler Carruthedf59962016-02-18 09:45:17 +00001807bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00001808 // If the pipeline just consists of the word 'default' just replace the AA
1809 // manager with our default one.
1810 if (PipelineText == "default") {
1811 AA = buildDefaultAAPipeline();
1812 return true;
1813 }
1814
Chandler Carruthedf59962016-02-18 09:45:17 +00001815 while (!PipelineText.empty()) {
1816 StringRef Name;
1817 std::tie(Name, PipelineText) = PipelineText.split(',');
1818 if (!parseAAPassName(AA, Name))
1819 return false;
1820 }
1821
1822 return true;
1823}