blob: c344a3165a0f9e3e689e1d5f9c2ab5ec0f804ab8 [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"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000083#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000084#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000085#include "llvm/Transforms/InstCombine/InstCombine.h"
Xinliang David Lie6b89292016-04-18 17:47:38 +000086#include "llvm/Transforms/InstrProfiling.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000087#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000088#include "llvm/Transforms/PGOInstrumentation.h"
Xinliang David Lid38392e2016-05-27 23:20:16 +000089#include "llvm/Transforms/SampleProfile.h"
Justin Bogner19b67992015-10-30 23:13:18 +000090#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +000091#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +000092#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +000093#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +000094#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +000095#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +000096#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +000097#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +000098#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +000099#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000100#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000101#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000102#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000103#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000104#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Sean Silva46590d52016-06-14 00:51:09 +0000105#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000106#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000107#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000108#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000109#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000110#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000111#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Dehao Chendcafd5e2016-07-15 16:42:11 +0000112#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000113#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000114#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000115#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000116#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000117#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000118#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000119#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000120#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000121#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000122#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000123#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Sean Silva6347df02016-06-14 02:44:55 +0000124#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000125#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000126#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000127#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000128#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000129#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000130#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000131#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000132#include "llvm/Transforms/Scalar/SROA.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000133#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000134#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000135#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000136#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000137#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000138#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000139#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000140#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000141#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000142#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000143#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000144#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000145#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000146#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000147#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Davide Italiano16284df2016-07-07 21:14:36 +0000148#include "llvm/Transforms/Utils/SimplifyInstructions.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000149#include "llvm/Transforms/Utils/SymbolRewriter.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000150#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000151#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000152
Chandler Carruth66445382014-01-11 08:16:35 +0000153
154using namespace llvm;
155
Chandler Carruth719ffe12017-02-12 05:38:04 +0000156static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
157 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000158static cl::opt<bool>
159 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
160 cl::Hidden, cl::ZeroOrMore,
161 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000162
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000163static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000164 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000165 cl::Hidden, cl::ZeroOrMore,
166 cl::desc("Run NewGVN instead of GVN"));
167
Geoff Berry3cca1da2017-06-10 15:20:03 +0000168static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000169 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
170 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000171
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000172static cl::opt<bool> EnableGVNHoist(
173 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
174 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
175
Davide Italianobe1b6a92017-06-03 23:18:29 +0000176static cl::opt<bool> EnableGVNSink(
177 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
178 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
179
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000180static cl::opt<bool> EnableSyntheticCounts(
181 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
182 cl::desc("Run synthetic function entry count generation "
183 "pass"));
184
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000185static Regex DefaultAliasRegex(
186 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000187
Chandler Carruthe3f50642016-12-22 06:59:15 +0000188static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
189 switch (Level) {
190 case PassBuilder::O0:
191 case PassBuilder::O1:
192 case PassBuilder::O2:
193 case PassBuilder::O3:
194 return false;
195
196 case PassBuilder::Os:
197 case PassBuilder::Oz:
198 return true;
199 }
200 llvm_unreachable("Invalid optimization level!");
201}
202
Chandler Carruth66445382014-01-11 08:16:35 +0000203namespace {
204
Chandler Carruthd8330982014-01-12 09:34:22 +0000205/// \brief No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000206struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000207 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000208 return PreservedAnalyses::all();
209 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000210 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000211};
212
Chandler Carruth0b576b32015-01-06 02:50:06 +0000213/// \brief No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000214class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
215 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000216 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000217
218public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000219 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000220 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000221 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000222};
223
Chandler Carruth572e3402014-04-21 11:12:00 +0000224/// \brief No-op CGSCC pass which does nothing.
225struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000226 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
227 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000228 return PreservedAnalyses::all();
229 }
230 static StringRef name() { return "NoOpCGSCCPass"; }
231};
232
Chandler Carruth0b576b32015-01-06 02:50:06 +0000233/// \brief No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000234class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
235 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000236 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000237
238public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000239 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000240 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000241 return Result();
242 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000243 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000244};
245
Chandler Carruthd8330982014-01-12 09:34:22 +0000246/// \brief No-op function pass which does nothing.
247struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000248 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000249 return PreservedAnalyses::all();
250 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000251 static StringRef name() { return "NoOpFunctionPass"; }
252};
253
Chandler Carruth0b576b32015-01-06 02:50:06 +0000254/// \brief No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000255class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
256 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000257 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000258
259public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000260 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000261 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000262 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000263};
264
Justin Bognereecc3c82016-02-25 07:23:08 +0000265/// \brief No-op loop pass which does nothing.
266struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000267 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
268 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000269 return PreservedAnalyses::all();
270 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000271 static StringRef name() { return "NoOpLoopPass"; }
272};
273
274/// \brief No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000275class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
276 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000277 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000278
279public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000280 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000281 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
282 return Result();
283 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000284 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000285};
286
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000287AnalysisKey NoOpModuleAnalysis::Key;
288AnalysisKey NoOpCGSCCAnalysis::Key;
289AnalysisKey NoOpFunctionAnalysis::Key;
290AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000291
Chandler Carruth66445382014-01-11 08:16:35 +0000292} // End anonymous namespace.
293
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000294void PassBuilder::invokePeepholeEPCallbacks(
295 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
296 for (auto &C : PeepholeEPCallbacks)
297 C(FPM, Level);
298}
299
Chandler Carruth1ff77242015-03-07 09:02:36 +0000300void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000301#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000302 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000303#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000304
305 for (auto &C : ModuleAnalysisRegistrationCallbacks)
306 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000307}
308
Chandler Carruth1ff77242015-03-07 09:02:36 +0000309void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000310#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000311 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000312#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000313
314 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
315 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000316}
317
Chandler Carruth1ff77242015-03-07 09:02:36 +0000318void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000319#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000320 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000321#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000322
323 for (auto &C : FunctionAnalysisRegistrationCallbacks)
324 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000325}
326
Justin Bognereecc3c82016-02-25 07:23:08 +0000327void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000328#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000329 LAM.registerPass([&] { return CREATE_PASS; });
330#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000331
332 for (auto &C : LoopAnalysisRegistrationCallbacks)
333 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000334}
335
Chandler Carruthe3f50642016-12-22 06:59:15 +0000336FunctionPassManager
337PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000338 ThinLTOPhase Phase,
339 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000340 assert(Level != O0 && "Must request optimizations!");
341 FunctionPassManager FPM(DebugLogging);
342
343 // Form SSA out of local memory accesses after breaking apart aggregates into
344 // scalars.
345 FPM.addPass(SROA());
346
347 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000348 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000349
Davide Italianoc3688312017-06-01 23:08:14 +0000350 // Hoisting of scalars and load expressions.
351 if (EnableGVNHoist)
352 FPM.addPass(GVNHoistPass());
353
Davide Italianobe1b6a92017-06-03 23:18:29 +0000354 // Global value numbering based sinking.
355 if (EnableGVNSink) {
356 FPM.addPass(GVNSinkPass());
357 FPM.addPass(SimplifyCFGPass());
358 }
359
Chandler Carruthe3f50642016-12-22 06:59:15 +0000360 // Speculative execution if the target has divergent branches; otherwise nop.
361 FPM.addPass(SpeculativeExecutionPass());
362
363 // Optimize based on known information about branches, and cleanup afterward.
364 FPM.addPass(JumpThreadingPass());
365 FPM.addPass(CorrelatedValuePropagationPass());
366 FPM.addPass(SimplifyCFGPass());
367 FPM.addPass(InstCombinePass());
368
369 if (!isOptimizingForSize(Level))
370 FPM.addPass(LibCallsShrinkWrapPass());
371
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000372 invokePeepholeEPCallbacks(FPM, Level);
373
Rong Xue1f42452017-10-23 22:21:29 +0000374 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
375 // using the size value profile. Don't perform this when optimizing for size.
376 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
377 !isOptimizingForSize(Level))
378 FPM.addPass(PGOMemOPSizeOpt());
379
Chandler Carruthe3f50642016-12-22 06:59:15 +0000380 FPM.addPass(TailCallElimPass());
381 FPM.addPass(SimplifyCFGPass());
382
383 // Form canonically associated expression trees, and simplify the trees using
384 // basic mathematical properties. For example, this will form (nearly)
385 // minimal multiplication trees.
386 FPM.addPass(ReassociatePass());
387
388 // Add the primary loop simplification pipeline.
389 // FIXME: Currently this is split into two loop pass pipelines because we run
390 // some function passes in between them. These can and should be replaced by
391 // loop pass equivalenst but those aren't ready yet. Specifically,
392 // `SimplifyCFGPass` and `InstCombinePass` are used. We have
393 // `LoopSimplifyCFGPass` which isn't yet powerful enough, and the closest to
394 // the other we have is `LoopInstSimplify`.
395 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
396
397 // Rotate Loop - disable header duplication at -Oz
398 LPM1.addPass(LoopRotatePass(Level != Oz));
399 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000400 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000401 LPM2.addPass(IndVarSimplifyPass());
402 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000403
404 for (auto &C : LateLoopOptimizationsEPCallbacks)
405 C(LPM2, Level);
406
Chandler Carruth79b733b2017-01-26 23:21:17 +0000407 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000408 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000409 // because it changes IR to makes profile annotation in back compile
410 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000411 if (Phase != ThinLTOPhase::PreLink ||
412 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000413 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000414
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000415 for (auto &C : LoopOptimizerEndEPCallbacks)
416 C(LPM2, Level);
417
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000418 // We provide the opt remark emitter pass for LICM to use. We only need to do
419 // this once as it is immutable.
420 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000421 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000422 FPM.addPass(SimplifyCFGPass());
423 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000424 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000425
426 // Eliminate redundancies.
427 if (Level != O1) {
428 // These passes add substantial compile time so skip them at O1.
429 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000430 if (RunNewGVN)
431 FPM.addPass(NewGVNPass());
432 else
433 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000434 }
435
436 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
437 FPM.addPass(MemCpyOptPass());
438
439 // Sparse conditional constant propagation.
440 // FIXME: It isn't clear why we do this *after* loop passes rather than
441 // before...
442 FPM.addPass(SCCPPass());
443
444 // Delete dead bit computations (instcombine runs after to fold away the dead
445 // computations, and then ADCE will run later to exploit any new DCE
446 // opportunities that creates).
447 FPM.addPass(BDCEPass());
448
449 // Run instcombine after redundancy and dead bit elimination to exploit
450 // opportunities opened up by them.
451 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000452 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000453
454 // Re-consider control flow based optimizations after redundancy elimination,
455 // redo DCE, etc.
456 FPM.addPass(JumpThreadingPass());
457 FPM.addPass(CorrelatedValuePropagationPass());
458 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000459 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000460
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000461 for (auto &C : ScalarOptimizerLateEPCallbacks)
462 C(FPM, Level);
463
Chandler Carruthe3f50642016-12-22 06:59:15 +0000464 // Finally, do an expensive DCE pass to catch all the dead code exposed by
465 // the simplifications and basic cleanup after all the simplifications.
466 FPM.addPass(ADCEPass());
467 FPM.addPass(SimplifyCFGPass());
468 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000469 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000470
471 return FPM;
472}
473
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000474void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
475 PassBuilder::OptimizationLevel Level,
476 bool RunProfileGen,
477 std::string ProfileGenFile,
478 std::string ProfileUseFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000479 // Generally running simplification passes and the inliner with an high
480 // threshold results in smaller executables, but there may be cases where
481 // the size grows, so let's be conservative here and skip this simplification
482 // at -Os/Oz.
483 if (!isOptimizingForSize(Level)) {
484 InlineParams IP;
485
486 // In the old pass manager, this is a cl::opt. Should still this be one?
487 IP.DefaultThreshold = 75;
488
489 // FIXME: The hint threshold has the same value used by the regular inliner.
490 // This should probably be lowered after performance testing.
491 // FIXME: this comment is cargo culted from the old pass manager, revisit).
492 IP.HintThreshold = 325;
493
494 CGSCCPassManager CGPipeline(DebugLogging);
495
496 CGPipeline.addPass(InlinerPass(IP));
497
498 FunctionPassManager FPM;
499 FPM.addPass(SROA());
500 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
501 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
502 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000503 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000504
Davide Italiano513dfaa2017-02-13 15:26:22 +0000505 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
506
507 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
508 }
509
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000510 // Delete anything that is now dead to make sure that we don't instrument
511 // dead code. Instrumentation can end up keeping dead code around and
512 // dramatically increase code size.
513 MPM.addPass(GlobalDCEPass());
514
Davide Italiano513dfaa2017-02-13 15:26:22 +0000515 if (RunProfileGen) {
516 MPM.addPass(PGOInstrumentationGen());
517
Xinliang David Lib67530e2017-06-25 00:26:43 +0000518 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000519 FPM.addPass(
520 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000521 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
522
Davide Italiano513dfaa2017-02-13 15:26:22 +0000523 // Add the profile lowering pass.
524 InstrProfOptions Options;
525 if (!ProfileGenFile.empty())
526 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000527 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000528 MPM.addPass(InstrProfiling(Options));
529 }
530
531 if (!ProfileUseFile.empty())
532 MPM.addPass(PGOInstrumentationUse(ProfileUseFile));
533}
534
Easwaran Raman8249fac2017-06-28 13:33:49 +0000535static InlineParams
536getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
537 auto O3 = PassBuilder::O3;
538 unsigned OptLevel = Level > O3 ? 2 : Level;
539 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
540 return getInlineParams(OptLevel, SizeLevel);
541}
542
Chandler Carruthe3f50642016-12-22 06:59:15 +0000543ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000544PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000545 ThinLTOPhase Phase,
546 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000547 ModulePassManager MPM(DebugLogging);
548
Chandler Carruthe3f50642016-12-22 06:59:15 +0000549 // Do basic inference of function attributes from known properties of system
550 // libraries and other oracles.
551 MPM.addPass(InferFunctionAttrsPass());
552
553 // Create an early function pass manager to cleanup the output of the
554 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000555 FunctionPassManager EarlyFPM(DebugLogging);
556 EarlyFPM.addPass(SimplifyCFGPass());
557 EarlyFPM.addPass(SROA());
558 EarlyFPM.addPass(EarlyCSEPass());
559 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000560 if (Level == O3)
561 EarlyFPM.addPass(CallSiteSplittingPass());
562
Dehao Chen08f88312017-08-07 20:23:20 +0000563 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
564 // to convert bitcast to direct calls so that they can be inlined during the
565 // profile annotation prepration step.
566 // More details about SamplePGO design can be found in:
567 // https://research.google.com/pubs/pub45290.html
568 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
569 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
570 Phase == ThinLTOPhase::PostLink)
571 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000572 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000573
Dehao Chen08f88312017-08-07 20:23:20 +0000574 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
575 // Annotate sample profile right after early FPM to ensure freshness of
576 // the debug info.
Dehao Chend26dae02017-10-01 05:24:51 +0000577 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
578 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000579 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
580 // for the profile annotation to be accurate in the ThinLTO backend.
581 if (Phase != ThinLTOPhase::PreLink)
582 // We perform early indirect call promotion here, before globalopt.
583 // This is important for the ThinLTO backend phase because otherwise
584 // imported available_externally functions look unreferenced and are
585 // removed.
586 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
587 true));
588 }
589
Chandler Carruthe3f50642016-12-22 06:59:15 +0000590 // Interprocedural constant propagation now that basic cleanup has occured
591 // and prior to optimizing globals.
592 // FIXME: This position in the pipeline hasn't been carefully considered in
593 // years, it should be re-analyzed.
594 MPM.addPass(IPSCCPPass());
595
Matthew Simpsoncb585582017-10-25 13:40:08 +0000596 // Attach metadata to indirect call sites indicating the set of functions
597 // they may target at run-time. This should follow IPSCCP.
598 MPM.addPass(CalledValuePropagationPass());
599
Chandler Carruthe3f50642016-12-22 06:59:15 +0000600 // Optimize globals to try and fold them into constants.
601 MPM.addPass(GlobalOptPass());
602
603 // Promote any localized globals to SSA registers.
604 // FIXME: Should this instead by a run of SROA?
605 // FIXME: We should probably run instcombine and simplify-cfg afterward to
606 // delete control flows that are dead once globals have been folded to
607 // constants.
608 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
609
610 // Remove any dead arguments exposed by cleanups and constand folding
611 // globals.
612 MPM.addPass(DeadArgumentEliminationPass());
613
614 // Create a small function pass pipeline to cleanup after all the global
615 // optimizations.
616 FunctionPassManager GlobalCleanupPM(DebugLogging);
617 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000618 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
619
Chandler Carruthe3f50642016-12-22 06:59:15 +0000620 GlobalCleanupPM.addPass(SimplifyCFGPass());
621 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
622
Dehao Chen89d32262017-08-02 01:28:31 +0000623 // Add all the requested passes for instrumentation PGO, if requested.
624 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
625 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
626 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
627 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile);
628 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000629 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000630
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000631 // Synthesize function entry counts for non-PGO compilation.
632 if (EnableSyntheticCounts && !PGOOpt)
633 MPM.addPass(SyntheticCountsPropagation());
634
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000635 // Require the GlobalsAA analysis for the module so we can query it within
636 // the CGSCC pipeline.
637 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000638
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000639 // Require the ProfileSummaryAnalysis for the module so we can query it within
640 // the inliner pass.
641 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
642
Chandler Carruthe3f50642016-12-22 06:59:15 +0000643 // Now begin the main postorder CGSCC pipeline.
644 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
645 // manager and trying to emulate its precise behavior. Much of this doesn't
646 // make a lot of sense and we should revisit the core CGSCC structure.
647 CGSCCPassManager MainCGPipeline(DebugLogging);
648
649 // Note: historically, the PruneEH pass was run first to deduce nounwind and
650 // generally clean up exception handling overhead. It isn't clear this is
651 // valuable as the inliner doesn't currently care whether it is inlining an
652 // invoke or a call.
653
654 // Run the inliner first. The theory is that we are walking bottom-up and so
655 // the callees have already been fully optimized, and we want to inline them
656 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000657 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000658 // because it makes profile annotation in the backend inaccurate.
659 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000660 if (Phase == ThinLTOPhase::PreLink &&
661 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000662 IP.HotCallSiteThreshold = 0;
663 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000664
665 // Now deduce any function attributes based in the current code.
666 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
667
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000668 // When at O3 add argument promotion to the pass pipeline.
669 // FIXME: It isn't at all clear why this should be limited to O3.
670 if (Level == O3)
671 MainCGPipeline.addPass(ArgumentPromotionPass());
672
Chandler Carruthe3f50642016-12-22 06:59:15 +0000673 // Lastly, add the core function simplification pipeline nested inside the
674 // CGSCC walk.
675 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000676 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000677
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000678 for (auto &C : CGSCCOptimizerLateEPCallbacks)
679 C(MainCGPipeline, Level);
680
Chandler Carruth719ffe12017-02-12 05:38:04 +0000681 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
682 // to detect when we devirtualize indirect calls and iterate the SCC passes
683 // in that case to try and catch knock-on inlining or function attrs
684 // opportunities. Then we add it to the module pipeline by walking the SCCs
685 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000686 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000687 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000688 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000689
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000690 return MPM;
691}
692
693ModulePassManager
694PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
695 bool DebugLogging) {
696 ModulePassManager MPM(DebugLogging);
697
698 // Optimize globals now that the module is fully simplified.
699 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000700 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000701
Xinliang David Li126157c2017-05-22 16:41:57 +0000702 // Run partial inlining pass to partially inline functions that have
703 // large bodies.
704 if (RunPartialInlining)
705 MPM.addPass(PartialInlinerPass());
706
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000707 // Remove avail extern fns and globals definitions since we aren't compiling
708 // an object file for later LTO. For LTO we want to preserve these so they
709 // are eligible for inlining at link-time. Note if they are unreferenced they
710 // will be removed by GlobalDCE later, so this only impacts referenced
711 // available externally globals. Eventually they will be suppressed during
712 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
713 // may make globals referenced by available external functions dead and saves
714 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000715 MPM.addPass(EliminateAvailableExternallyPass());
716
717 // Do RPO function attribute inference across the module to forward-propagate
718 // attributes where applicable.
719 // FIXME: Is this really an optimization rather than a canonicalization?
720 MPM.addPass(ReversePostOrderFunctionAttrsPass());
721
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000722 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000723 // useful as the above will have inlined, DCE'ed, and function-attr
724 // propagated everything. We should at this point have a reasonably minimal
725 // and richly annotated call graph. By computing aliasing and mod/ref
726 // information for all local globals here, the late loop passes and notably
727 // the vectorizer will be able to use them to help recognize vectorizable
728 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000729 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000730
731 FunctionPassManager OptimizePM(DebugLogging);
732 OptimizePM.addPass(Float2IntPass());
733 // FIXME: We need to run some loop optimizations to re-rotate loops after
734 // simplify-cfg and others undo their rotation.
735
736 // Optimize the loop execution. These passes operate on entire loop nests
737 // rather than on each loop in an inside-out manner, and so they are actually
738 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000739
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000740 for (auto &C : VectorizerStartEPCallbacks)
741 C(OptimizePM, Level);
742
Chandler Carrutha95ff382017-01-27 00:50:21 +0000743 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000744 OptimizePM.addPass(
745 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000746
747 // Distribute loops to allow partial vectorization. I.e. isolate dependences
748 // into separate loop that would otherwise inhibit vectorization. This is
749 // currently only performed for loops marked with the metadata
750 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000751 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000752
753 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000754 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000755
Chandler Carruthbaabda92017-01-27 01:32:26 +0000756 // Eliminate loads by forwarding stores from the previous iteration to loads
757 // of the current iteration.
758 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000759
760 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000761 OptimizePM.addPass(InstCombinePass());
762
Chandler Carrutha95ff382017-01-27 00:50:21 +0000763 // Now that we've formed fast to execute loop structures, we do further
764 // optimizations. These are run afterward as they might block doing complex
765 // analyses and transforms such as what are needed for loop vectorization.
766
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000767 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
768 // GVN, loop transforms, and others have already run, so it's now better to
769 // convert to more optimized IR using more aggressive simplify CFG options.
770 // The extra sinking transform can create larger basic blocks, so do this
771 // before SLP vectorization.
772 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
773 forwardSwitchCondToPhi(true).
774 convertSwitchToLookupTable(true).
775 needCanonicalLoops(false).
776 sinkCommonInsts(true)));
777
Chandler Carruthe3f50642016-12-22 06:59:15 +0000778 // Optimize parallel scalar instruction chains into SIMD instructions.
779 OptimizePM.addPass(SLPVectorizerPass());
780
Chandler Carruthe3f50642016-12-22 06:59:15 +0000781 OptimizePM.addPass(InstCombinePass());
782
783 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000784 // execution resources of an out-of-order processor. We also then need to
785 // clean up redundancies and loop invariant code.
786 // FIXME: It would be really good to use a loop-integrated instruction
787 // combiner for cleanup here so that the unrolling and LICM can be pipelined
788 // across the loop nests.
Teresa Johnsonecd90132017-08-02 20:35:29 +0000789 OptimizePM.addPass(LoopUnrollPass(Level));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000790 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000791 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000792 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000793
794 // Now that we've vectorized and unrolled loops, we may have more refined
795 // alignment information, try to re-derive it here.
796 OptimizePM.addPass(AlignmentFromAssumptionsPass());
797
Chandler Carrutha95ff382017-01-27 00:50:21 +0000798 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
799 // canonicalization pass that enables other optimizations. As a result,
800 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
801 // result too early.
802 OptimizePM.addPass(LoopSinkPass());
803
804 // And finally clean up LCSSA form before generating code.
805 OptimizePM.addPass(InstSimplifierPass());
806
Sanjay Patel6fd43912017-09-09 13:38:18 +0000807 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
808 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
809 // flattening of blocks.
810 OptimizePM.addPass(DivRemPairsPass());
811
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000812 // LoopSink (and other loop passes since the last simplifyCFG) might have
813 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
814 OptimizePM.addPass(SimplifyCFGPass());
815
Chandler Carruthc34f7892017-11-28 11:32:31 +0000816 // Optimize PHIs by speculating around them when profitable. Note that this
817 // pass needs to be run after any PRE or similar pass as it is essentially
818 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
819 OptimizePM.addPass(SpeculateAroundPHIsPass());
820
Chandler Carrutha95ff382017-01-27 00:50:21 +0000821 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000822 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
823
824 // Now we need to do some global optimization transforms.
825 // FIXME: It would seem like these should come first in the optimization
826 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
827 // ordering here.
828 MPM.addPass(GlobalDCEPass());
829 MPM.addPass(ConstantMergePass());
830
831 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000832}
833
Chandler Carruthe3f50642016-12-22 06:59:15 +0000834ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000835PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
836 bool DebugLogging) {
837 assert(Level != O0 && "Must request optimizations for the default pipeline!");
838
839 ModulePassManager MPM(DebugLogging);
840
841 // Force any function attributes we want the rest of the pipeline to observe.
842 MPM.addPass(ForceFunctionAttrsPass());
843
Dehao Chen08f88312017-08-07 20:23:20 +0000844 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000845 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
846
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000847 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000848 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
849 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000850
851 // Now add the optimization pipeline.
852 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
853
854 return MPM;
855}
856
857ModulePassManager
858PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
859 bool DebugLogging) {
860 assert(Level != O0 && "Must request optimizations for the default pipeline!");
861
862 ModulePassManager MPM(DebugLogging);
863
864 // Force any function attributes we want the rest of the pipeline to observe.
865 MPM.addPass(ForceFunctionAttrsPass());
866
Dehao Chen08f88312017-08-07 20:23:20 +0000867 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000868 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
869
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000870 // If we are planning to perform ThinLTO later, we don't bloat the code with
871 // unrolling/vectorization/... now. Just simplify the module as much as we
872 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000873 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
874 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000875
876 // Run partial inlining pass to partially inline functions that have
877 // large bodies.
878 // FIXME: It isn't clear whether this is really the right place to run this
879 // in ThinLTO. Because there is another canonicalization and simplification
880 // phase that will run after the thin link, running this here ends up with
881 // less information than will be available later and it may grow functions in
882 // ways that aren't beneficial.
883 if (RunPartialInlining)
884 MPM.addPass(PartialInlinerPass());
885
886 // Reduce the size of the IR as much as possible.
887 MPM.addPass(GlobalOptPass());
888
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000889 return MPM;
890}
891
892ModulePassManager
893PassBuilder::buildThinLTODefaultPipeline(OptimizationLevel Level,
894 bool DebugLogging) {
895 // FIXME: The summary index is not hooked in the new pass manager yet.
896 // When it's going to be hooked, enable WholeProgramDevirt and LowerTypeTest
897 // here.
898
899 ModulePassManager MPM(DebugLogging);
900
901 // Force any function attributes we want the rest of the pipeline to observe.
902 MPM.addPass(ForceFunctionAttrsPass());
903
904 // During the ThinLTO backend phase we perform early indirect call promotion
905 // here, before globalopt. Otherwise imported available_externally functions
906 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000907 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
908 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000909 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000910 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
911 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000912
913 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000914 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
915 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000916
917 // Now add the optimization pipeline.
918 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
919
920 return MPM;
921}
922
923ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +0000924PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
925 bool DebugLogging) {
926 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000927 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +0000928 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000929}
930
Chandler Carruthe3f50642016-12-22 06:59:15 +0000931ModulePassManager PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
932 bool DebugLogging) {
933 assert(Level != O0 && "Must request optimizations for the default pipeline!");
934 ModulePassManager MPM(DebugLogging);
935
Davide Italiano089a9122017-01-24 00:57:39 +0000936 // Remove unused virtual tables to improve the quality of code generated by
937 // whole-program devirtualization and bitset lowering.
938 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000939
Davide Italiano089a9122017-01-24 00:57:39 +0000940 // Force any function attributes we want the rest of the pipeline to observe.
941 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000942
Davide Italiano089a9122017-01-24 00:57:39 +0000943 // Do basic inference of function attributes from known properties of system
944 // libraries and other oracles.
945 MPM.addPass(InferFunctionAttrsPass());
946
947 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +0000948 FunctionPassManager EarlyFPM(DebugLogging);
949 EarlyFPM.addPass(CallSiteSplittingPass());
950 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
951
Davide Italiano089a9122017-01-24 00:57:39 +0000952 // Indirect call promotion. This should promote all the targets that are
953 // left by the earlier promotion pass that promotes intra-module targets.
954 // This two-step promotion is to save the compile time. For LTO, it should
955 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +0000956 MPM.addPass(PGOIndirectCallPromotion(
957 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +0000958 // Propagate constants at call sites into the functions they call. This
959 // opens opportunities for globalopt (and inlining) by substituting function
960 // pointers passed as arguments to direct uses of functions.
961 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +0000962
963 // Attach metadata to indirect call sites indicating the set of functions
964 // they may target at run-time. This should follow IPSCCP.
965 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +0000966 }
967
968 // Now deduce any function attributes based in the current code.
969 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
970 PostOrderFunctionAttrsPass()));
971
972 // Do RPO function attribute inference across the module to forward-propagate
973 // attributes where applicable.
974 // FIXME: Is this really an optimization rather than a canonicalization?
975 MPM.addPass(ReversePostOrderFunctionAttrsPass());
976
977 // Use inragne annotations on GEP indices to split globals where beneficial.
978 MPM.addPass(GlobalSplitPass());
979
980 // Run whole program optimization of virtual call when the list of callees
981 // is fixed.
982 MPM.addPass(WholeProgramDevirtPass());
983
984 // Stop here at -O1.
985 if (Level == 1)
986 return MPM;
987
988 // Optimize globals to try and fold them into constants.
989 MPM.addPass(GlobalOptPass());
990
991 // Promote any localized globals to SSA registers.
992 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
993
994 // Linking modules together can lead to duplicate global constant, only
995 // keep one copy of each constant.
996 MPM.addPass(ConstantMergePass());
997
998 // Remove unused arguments from functions.
999 MPM.addPass(DeadArgumentEliminationPass());
1000
1001 // Reduce the code after globalopt and ipsccp. Both can open up significant
1002 // simplification opportunities, and both can propagate functions through
1003 // function pointers. When this happens, we often have to resolve varargs
1004 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001005 FunctionPassManager PeepholeFPM(DebugLogging);
1006 PeepholeFPM.addPass(InstCombinePass());
1007 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1008
1009 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001010
1011 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1012 // generally clean up exception handling overhead. It isn't clear this is
1013 // valuable as the inliner doesn't currently care whether it is inlining an
1014 // invoke or a call.
1015 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001016 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1017 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001018
1019 // Optimize globals again after we ran the inliner.
1020 MPM.addPass(GlobalOptPass());
1021
1022 // Garbage collect dead functions.
1023 // FIXME: Add ArgumentPromotion pass after once it's ported.
1024 MPM.addPass(GlobalDCEPass());
1025
1026 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001027 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001028 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001029 invokePeepholeEPCallbacks(FPM, Level);
1030
Davide Italiano089a9122017-01-24 00:57:39 +00001031 FPM.addPass(JumpThreadingPass());
1032
1033 // Break up allocas
1034 FPM.addPass(SROA());
1035
1036 // Run a few AA driver optimizations here and now to cleanup the code.
1037 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1038
1039 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1040 PostOrderFunctionAttrsPass()));
1041 // FIXME: here we run IP alias analysis in the legacy PM.
1042
1043 FunctionPassManager MainFPM;
1044
1045 // FIXME: once we fix LoopPass Manager, add LICM here.
1046 // FIXME: once we provide support for enabling MLSM, add it here.
1047 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001048 if (RunNewGVN)
1049 MainFPM.addPass(NewGVNPass());
1050 else
1051 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001052
1053 // Remove dead memcpy()'s.
1054 MainFPM.addPass(MemCpyOptPass());
1055
1056 // Nuke dead stores.
1057 MainFPM.addPass(DSEPass());
1058
1059 // FIXME: at this point, we run a bunch of loop passes:
1060 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1061 // loopVectorize. Enable them once the remaining issue with LPM
1062 // are sorted out.
1063
1064 MainFPM.addPass(InstCombinePass());
1065 MainFPM.addPass(SimplifyCFGPass());
1066 MainFPM.addPass(SCCPPass());
1067 MainFPM.addPass(InstCombinePass());
1068 MainFPM.addPass(BDCEPass());
1069
1070 // FIXME: We may want to run SLPVectorizer here.
1071 // After vectorization, assume intrinsics may tell us more
1072 // about pointer alignments.
1073#if 0
1074 MainFPM.add(AlignmentFromAssumptionsPass());
1075#endif
1076
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001077 // FIXME: Conditionally run LoadCombine here, after it's ported
1078 // (in case we still have this pass, given its questionable usefulness).
1079
Davide Italiano089a9122017-01-24 00:57:39 +00001080 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001081 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001082 MainFPM.addPass(JumpThreadingPass());
1083 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1084
1085 // Create a function that performs CFI checks for cross-DSO calls with
1086 // targets in the current module.
1087 MPM.addPass(CrossDSOCFIPass());
1088
1089 // Lower type metadata and the type.test intrinsic. This pass supports
1090 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1091 // to be run at link time if CFI is enabled. This pass does nothing if
1092 // CFI is disabled.
1093 // Enable once we add support for the summary in the new PM.
1094#if 0
Peter Collingbourne857aba42017-02-09 21:45:01 +00001095 MPM.addPass(LowerTypeTestsPass(Summary ? PassSummaryAction::Export :
1096 PassSummaryAction::None,
Davide Italiano089a9122017-01-24 00:57:39 +00001097 Summary));
1098#endif
1099
1100 // Add late LTO optimization passes.
1101 // Delete basic blocks, which optimization passes may have killed.
1102 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1103
1104 // Drop bodies of available eternally objects to improve GlobalDCE.
1105 MPM.addPass(EliminateAvailableExternallyPass());
1106
1107 // Now that we have optimized the program, discard unreachable functions.
1108 MPM.addPass(GlobalDCEPass());
1109
1110 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001111 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001112}
1113
Chandler Carruth060ad612016-12-23 20:38:19 +00001114AAManager PassBuilder::buildDefaultAAPipeline() {
1115 AAManager AA;
1116
1117 // The order in which these are registered determines their priority when
1118 // being queried.
1119
1120 // First we register the basic alias analysis that provides the majority of
1121 // per-function local AA logic. This is a stateless, on-demand local set of
1122 // AA techniques.
1123 AA.registerFunctionAnalysis<BasicAA>();
1124
1125 // Next we query fast, specialized alias analyses that wrap IR-embedded
1126 // information about aliasing.
1127 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1128 AA.registerFunctionAnalysis<TypeBasedAA>();
1129
1130 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001131 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1132 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001133 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001134 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001135
1136 return AA;
1137}
1138
Chandler Carruth241bf242016-08-03 07:44:48 +00001139static Optional<int> parseRepeatPassName(StringRef Name) {
1140 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1141 return None;
1142 int Count;
1143 if (Name.getAsInteger(0, Count) || Count <= 0)
1144 return None;
1145 return Count;
1146}
1147
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001148static Optional<int> parseDevirtPassName(StringRef Name) {
1149 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1150 return None;
1151 int Count;
1152 if (Name.getAsInteger(0, Count) || Count <= 0)
1153 return None;
1154 return Count;
1155}
1156
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001157/// Tests whether a pass name starts with a valid prefix for a default pipeline
1158/// alias.
1159static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1160 return Name.startswith("default") || Name.startswith("thinlto") ||
1161 Name.startswith("lto");
1162}
1163
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001164/// Tests whether registered callbacks will accept a given pass name.
1165///
1166/// When parsing a pipeline text, the type of the outermost pipeline may be
1167/// omitted, in which case the type is automatically determined from the first
1168/// pass name in the text. This may be a name that is handled through one of the
1169/// callbacks. We check this through the oridinary parsing callbacks by setting
1170/// up a dummy PassManager in order to not force the client to also handle this
1171/// type of query.
1172template <typename PassManagerT, typename CallbacksT>
1173static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1174 if (!Callbacks.empty()) {
1175 PassManagerT DummyPM;
1176 for (auto &CB : Callbacks)
1177 if (CB(Name, DummyPM, {}))
1178 return true;
1179 }
1180 return false;
1181}
1182
1183template <typename CallbacksT>
1184static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001185 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001186 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001187 return DefaultAliasRegex.match(Name);
1188
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001189 // Explicitly handle pass manager names.
1190 if (Name == "module")
1191 return true;
1192 if (Name == "cgscc")
1193 return true;
1194 if (Name == "function")
1195 return true;
1196
Chandler Carruth241bf242016-08-03 07:44:48 +00001197 // Explicitly handle custom-parsed pass names.
1198 if (parseRepeatPassName(Name))
1199 return true;
1200
Chandler Carruth74a8a222016-06-17 07:15:29 +00001201#define MODULE_PASS(NAME, CREATE_PASS) \
1202 if (Name == NAME) \
1203 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001204#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001205 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001206 return true;
1207#include "PassRegistry.def"
1208
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001209 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001210}
1211
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001212template <typename CallbacksT>
1213static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001214 // Explicitly handle pass manager names.
1215 if (Name == "cgscc")
1216 return true;
1217 if (Name == "function")
1218 return true;
1219
Chandler Carruth241bf242016-08-03 07:44:48 +00001220 // Explicitly handle custom-parsed pass names.
1221 if (parseRepeatPassName(Name))
1222 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001223 if (parseDevirtPassName(Name))
1224 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001225
Chandler Carruth74a8a222016-06-17 07:15:29 +00001226#define CGSCC_PASS(NAME, CREATE_PASS) \
1227 if (Name == NAME) \
1228 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001229#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001230 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001231 return true;
1232#include "PassRegistry.def"
1233
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001234 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001235}
1236
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001237template <typename CallbacksT>
1238static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001239 // Explicitly handle pass manager names.
1240 if (Name == "function")
1241 return true;
1242 if (Name == "loop")
1243 return true;
1244
Chandler Carruth241bf242016-08-03 07:44:48 +00001245 // Explicitly handle custom-parsed pass names.
1246 if (parseRepeatPassName(Name))
1247 return true;
1248
Chandler Carruth74a8a222016-06-17 07:15:29 +00001249#define FUNCTION_PASS(NAME, CREATE_PASS) \
1250 if (Name == NAME) \
1251 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001252#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001253 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001254 return true;
1255#include "PassRegistry.def"
1256
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001257 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001258}
1259
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001260template <typename CallbacksT>
1261static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001262 // Explicitly handle pass manager names.
1263 if (Name == "loop")
1264 return true;
1265
Chandler Carruth241bf242016-08-03 07:44:48 +00001266 // Explicitly handle custom-parsed pass names.
1267 if (parseRepeatPassName(Name))
1268 return true;
1269
Chandler Carruth74a8a222016-06-17 07:15:29 +00001270#define LOOP_PASS(NAME, CREATE_PASS) \
1271 if (Name == NAME) \
1272 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001273#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1274 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1275 return true;
1276#include "PassRegistry.def"
1277
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001278 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001279}
1280
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001281Optional<std::vector<PassBuilder::PipelineElement>>
1282PassBuilder::parsePipelineText(StringRef Text) {
1283 std::vector<PipelineElement> ResultPipeline;
1284
1285 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1286 &ResultPipeline};
1287 for (;;) {
1288 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1289 size_t Pos = Text.find_first_of(",()");
1290 Pipeline.push_back({Text.substr(0, Pos), {}});
1291
1292 // If we have a single terminating name, we're done.
1293 if (Pos == Text.npos)
1294 break;
1295
1296 char Sep = Text[Pos];
1297 Text = Text.substr(Pos + 1);
1298 if (Sep == ',')
1299 // Just a name ending in a comma, continue.
1300 continue;
1301
1302 if (Sep == '(') {
1303 // Push the inner pipeline onto the stack to continue processing.
1304 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1305 continue;
1306 }
1307
1308 assert(Sep == ')' && "Bogus separator!");
1309 // When handling the close parenthesis, we greedily consume them to avoid
1310 // empty strings in the pipeline.
1311 do {
1312 // If we try to pop the outer pipeline we have unbalanced parentheses.
1313 if (PipelineStack.size() == 1)
1314 return None;
1315
1316 PipelineStack.pop_back();
1317 } while (Text.consume_front(")"));
1318
1319 // Check if we've finished parsing.
1320 if (Text.empty())
1321 break;
1322
1323 // Otherwise, the end of an inner pipeline always has to be followed by
1324 // a comma, and then we can continue.
1325 if (!Text.consume_front(","))
1326 return None;
1327 }
1328
1329 if (PipelineStack.size() > 1)
1330 // Unbalanced paretheses.
1331 return None;
1332
1333 assert(PipelineStack.back() == &ResultPipeline &&
1334 "Wrong pipeline at the bottom of the stack!");
1335 return {std::move(ResultPipeline)};
1336}
1337
1338bool PassBuilder::parseModulePass(ModulePassManager &MPM,
1339 const PipelineElement &E, bool VerifyEachPass,
1340 bool DebugLogging) {
1341 auto &Name = E.Name;
1342 auto &InnerPipeline = E.InnerPipeline;
1343
1344 // First handle complex passes like the pass managers which carry pipelines.
1345 if (!InnerPipeline.empty()) {
1346 if (Name == "module") {
1347 ModulePassManager NestedMPM(DebugLogging);
1348 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1349 DebugLogging))
1350 return false;
1351 MPM.addPass(std::move(NestedMPM));
1352 return true;
1353 }
1354 if (Name == "cgscc") {
1355 CGSCCPassManager CGPM(DebugLogging);
1356 if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1357 DebugLogging))
1358 return false;
Chandler Carruth19913b22017-08-11 05:47:13 +00001359 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001360 return true;
1361 }
1362 if (Name == "function") {
1363 FunctionPassManager FPM(DebugLogging);
1364 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1365 DebugLogging))
1366 return false;
1367 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1368 return true;
1369 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001370 if (auto Count = parseRepeatPassName(Name)) {
1371 ModulePassManager NestedMPM(DebugLogging);
1372 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1373 DebugLogging))
1374 return false;
Chandler Carrutha053a882016-08-04 03:52:53 +00001375 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Chandler Carruth241bf242016-08-03 07:44:48 +00001376 return true;
1377 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001378
1379 for (auto &C : ModulePipelineParsingCallbacks)
1380 if (C(Name, MPM, InnerPipeline))
1381 return true;
1382
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001383 // Normal passes can't have pipelines.
1384 return false;
1385 }
1386
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001387 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001388 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001389 SmallVector<StringRef, 3> Matches;
1390 if (!DefaultAliasRegex.match(Name, &Matches))
1391 return false;
1392 assert(Matches.size() == 3 && "Must capture two matched strings!");
1393
Jordan Rosef85a95f2016-07-25 18:34:51 +00001394 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001395 .Case("O0", O0)
1396 .Case("O1", O1)
1397 .Case("O2", O2)
1398 .Case("O3", O3)
1399 .Case("Os", Os)
1400 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001401 if (L == O0)
1402 // At O0 we do nothing at all!
1403 return true;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001404
1405 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001406 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001407 } else if (Matches[1] == "thinlto-pre-link") {
1408 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1409 } else if (Matches[1] == "thinlto") {
1410 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001411 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001412 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001413 } else {
1414 assert(Matches[1] == "lto" && "Not one of the matched options!");
Chandler Carruthe3f50642016-12-22 06:59:15 +00001415 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001416 }
1417 return true;
1418 }
1419
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001420 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001421#define MODULE_PASS(NAME, CREATE_PASS) \
1422 if (Name == NAME) { \
1423 MPM.addPass(CREATE_PASS); \
1424 return true; \
Chandler Carruth52eef882014-01-12 12:15:39 +00001425 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001426#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1427 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001428 MPM.addPass( \
1429 RequireAnalysisPass< \
1430 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001431 return true; \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001432 } \
1433 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001434 MPM.addPass(InvalidateAnalysisPass< \
1435 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001436 return true; \
Chandler Carruth628503e2015-01-06 02:10:51 +00001437 }
1438#include "PassRegistry.def"
1439
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001440 for (auto &C : ModulePipelineParsingCallbacks)
1441 if (C(Name, MPM, InnerPipeline))
1442 return true;
Chandler Carruth66445382014-01-11 08:16:35 +00001443 return false;
1444}
1445
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001446bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1447 const PipelineElement &E, bool VerifyEachPass,
1448 bool DebugLogging) {
1449 auto &Name = E.Name;
1450 auto &InnerPipeline = E.InnerPipeline;
1451
1452 // First handle complex passes like the pass managers which carry pipelines.
1453 if (!InnerPipeline.empty()) {
1454 if (Name == "cgscc") {
1455 CGSCCPassManager NestedCGPM(DebugLogging);
1456 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1457 DebugLogging))
1458 return false;
1459 // Add the nested pass manager with the appropriate adaptor.
1460 CGPM.addPass(std::move(NestedCGPM));
1461 return true;
1462 }
1463 if (Name == "function") {
1464 FunctionPassManager FPM(DebugLogging);
1465 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1466 DebugLogging))
1467 return false;
1468 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001469 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001470 return true;
1471 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001472 if (auto Count = parseRepeatPassName(Name)) {
1473 CGSCCPassManager NestedCGPM(DebugLogging);
1474 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1475 DebugLogging))
1476 return false;
Chandler Carrutha053a882016-08-04 03:52:53 +00001477 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Chandler Carruth241bf242016-08-03 07:44:48 +00001478 return true;
1479 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001480 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1481 CGSCCPassManager NestedCGPM(DebugLogging);
1482 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1483 DebugLogging))
1484 return false;
Chandler Carruth19913b22017-08-11 05:47:13 +00001485 CGPM.addPass(
1486 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001487 return true;
1488 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001489
1490 for (auto &C : CGSCCPipelineParsingCallbacks)
1491 if (C(Name, CGPM, InnerPipeline))
1492 return true;
1493
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001494 // Normal passes can't have pipelines.
1495 return false;
1496 }
1497
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001498// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001499#define CGSCC_PASS(NAME, CREATE_PASS) \
1500 if (Name == NAME) { \
1501 CGPM.addPass(CREATE_PASS); \
1502 return true; \
1503 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001504#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1505 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001506 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001507 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001508 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1509 CGSCCUpdateResult &>()); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001510 return true; \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001511 } \
1512 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001513 CGPM.addPass(InvalidateAnalysisPass< \
1514 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001515 return true; \
Chandler Carruth628503e2015-01-06 02:10:51 +00001516 }
1517#include "PassRegistry.def"
1518
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001519 for (auto &C : CGSCCPipelineParsingCallbacks)
1520 if (C(Name, CGPM, InnerPipeline))
1521 return true;
Chandler Carruth572e3402014-04-21 11:12:00 +00001522 return false;
1523}
1524
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001525bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1526 const PipelineElement &E,
1527 bool VerifyEachPass, bool DebugLogging) {
1528 auto &Name = E.Name;
1529 auto &InnerPipeline = E.InnerPipeline;
1530
1531 // First handle complex passes like the pass managers which carry pipelines.
1532 if (!InnerPipeline.empty()) {
1533 if (Name == "function") {
1534 FunctionPassManager NestedFPM(DebugLogging);
1535 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1536 DebugLogging))
1537 return false;
1538 // Add the nested pass manager with the appropriate adaptor.
1539 FPM.addPass(std::move(NestedFPM));
1540 return true;
1541 }
1542 if (Name == "loop") {
1543 LoopPassManager LPM(DebugLogging);
1544 if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1545 DebugLogging))
1546 return false;
1547 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001548 FPM.addPass(
1549 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001550 return true;
1551 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001552 if (auto Count = parseRepeatPassName(Name)) {
1553 FunctionPassManager NestedFPM(DebugLogging);
1554 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1555 DebugLogging))
1556 return false;
Chandler Carrutha053a882016-08-04 03:52:53 +00001557 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Chandler Carruth241bf242016-08-03 07:44:48 +00001558 return true;
1559 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001560
1561 for (auto &C : FunctionPipelineParsingCallbacks)
1562 if (C(Name, FPM, InnerPipeline))
1563 return true;
1564
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001565 // Normal passes can't have pipelines.
1566 return false;
1567 }
1568
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001569// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001570#define FUNCTION_PASS(NAME, CREATE_PASS) \
1571 if (Name == NAME) { \
1572 FPM.addPass(CREATE_PASS); \
1573 return true; \
Chandler Carruth52eef882014-01-12 12:15:39 +00001574 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001575#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1576 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001577 FPM.addPass( \
1578 RequireAnalysisPass< \
1579 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001580 return true; \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001581 } \
1582 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001583 FPM.addPass(InvalidateAnalysisPass< \
1584 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001585 return true; \
Chandler Carruth628503e2015-01-06 02:10:51 +00001586 }
1587#include "PassRegistry.def"
1588
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001589 for (auto &C : FunctionPipelineParsingCallbacks)
1590 if (C(Name, FPM, InnerPipeline))
1591 return true;
Chandler Carruthd8330982014-01-12 09:34:22 +00001592 return false;
1593}
1594
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001595bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001596 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001597 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001598 auto &InnerPipeline = E.InnerPipeline;
1599
1600 // First handle complex passes like the pass managers which carry pipelines.
1601 if (!InnerPipeline.empty()) {
1602 if (Name == "loop") {
1603 LoopPassManager NestedLPM(DebugLogging);
1604 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1605 DebugLogging))
1606 return false;
1607 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001608 LPM.addPass(std::move(NestedLPM));
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001609 return true;
1610 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001611 if (auto Count = parseRepeatPassName(Name)) {
1612 LoopPassManager NestedLPM(DebugLogging);
1613 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1614 DebugLogging))
1615 return false;
Chandler Carrutha053a882016-08-04 03:52:53 +00001616 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Chandler Carruth241bf242016-08-03 07:44:48 +00001617 return true;
1618 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001619
1620 for (auto &C : LoopPipelineParsingCallbacks)
1621 if (C(Name, LPM, InnerPipeline))
1622 return true;
1623
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001624 // Normal passes can't have pipelines.
1625 return false;
1626 }
1627
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001628// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001629#define LOOP_PASS(NAME, CREATE_PASS) \
1630 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001631 LPM.addPass(CREATE_PASS); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001632 return true; \
1633 }
1634#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1635 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001636 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001637 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1638 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1639 LPMUpdater &>()); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001640 return true; \
1641 } \
1642 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001643 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001644 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001645 return true; \
1646 }
1647#include "PassRegistry.def"
1648
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001649 for (auto &C : LoopPipelineParsingCallbacks)
1650 if (C(Name, LPM, InnerPipeline))
1651 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001652 return false;
1653}
1654
Chandler Carruthedf59962016-02-18 09:45:17 +00001655bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001656#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1657 if (Name == NAME) { \
1658 AA.registerModuleAnalysis< \
1659 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1660 return true; \
1661 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001662#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1663 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001664 AA.registerFunctionAnalysis< \
1665 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001666 return true; \
1667 }
1668#include "PassRegistry.def"
1669
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001670 for (auto &C : AAParsingCallbacks)
1671 if (C(Name, AA))
1672 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001673 return false;
1674}
1675
Justin Bognereecc3c82016-02-25 07:23:08 +00001676bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001677 ArrayRef<PipelineElement> Pipeline,
Justin Bognereecc3c82016-02-25 07:23:08 +00001678 bool VerifyEachPass,
1679 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001680 for (const auto &Element : Pipeline) {
1681 if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1682 return false;
1683 // FIXME: No verifier support for Loop passes!
Justin Bognereecc3c82016-02-25 07:23:08 +00001684 }
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001685 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001686}
1687
Chandler Carruth1ff77242015-03-07 09:02:36 +00001688bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001689 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001690 bool VerifyEachPass,
1691 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001692 for (const auto &Element : Pipeline) {
1693 if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1694 return false;
1695 if (VerifyEachPass)
1696 FPM.addPass(VerifierPass());
Chandler Carruthd8330982014-01-12 09:34:22 +00001697 }
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001698 return true;
Chandler Carruthd8330982014-01-12 09:34:22 +00001699}
1700
Chandler Carruth1ff77242015-03-07 09:02:36 +00001701bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001702 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001703 bool VerifyEachPass,
1704 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001705 for (const auto &Element : Pipeline) {
1706 if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1707 return false;
1708 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001709 }
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001710 return true;
Chandler Carruth572e3402014-04-21 11:12:00 +00001711}
1712
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001713void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1714 FunctionAnalysisManager &FAM,
1715 CGSCCAnalysisManager &CGAM,
1716 ModuleAnalysisManager &MAM) {
1717 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1718 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001719 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1720 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1721 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1722 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1723 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1724}
1725
Chandler Carruth1ff77242015-03-07 09:02:36 +00001726bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001727 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001728 bool VerifyEachPass,
1729 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001730 for (const auto &Element : Pipeline) {
1731 if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1732 return false;
1733 if (VerifyEachPass)
1734 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001735 }
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001736 return true;
Chandler Carruth66445382014-01-11 08:16:35 +00001737}
1738
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001739// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001740// FIXME: Should this routine accept a TargetMachine or require the caller to
1741// pre-populate the analysis managers with target-specific stuff?
Chandler Carruth1ff77242015-03-07 09:02:36 +00001742bool PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1743 StringRef PipelineText, bool VerifyEachPass,
1744 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001745 auto Pipeline = parsePipelineText(PipelineText);
1746 if (!Pipeline || Pipeline->empty())
1747 return false;
Chandler Carruth66445382014-01-11 08:16:35 +00001748
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001749 // If the first name isn't at the module layer, wrap the pipeline up
1750 // automatically.
1751 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001752
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001753 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1754 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001755 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001756 } else if (isFunctionPassName(FirstName,
1757 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001758 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001759 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001760 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001761 } else {
1762 for (auto &C : TopLevelPipelineParsingCallbacks)
1763 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1764 return true;
1765
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001766 // Unknown pass name!
Chandler Carruth572e3402014-04-21 11:12:00 +00001767 return false;
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001768 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001769 }
1770
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001771 return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging);
Chandler Carruth66445382014-01-11 08:16:35 +00001772}
Chandler Carruthedf59962016-02-18 09:45:17 +00001773
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001774// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
1775bool PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1776 StringRef PipelineText, bool VerifyEachPass,
1777 bool DebugLogging) {
1778 auto Pipeline = parsePipelineText(PipelineText);
1779 if (!Pipeline || Pipeline->empty())
1780 return false;
1781
1782 StringRef FirstName = Pipeline->front().Name;
1783 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
1784 return false;
1785
1786 return parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1787}
1788
1789// Primary pass pipeline description parsing routine for a \c
1790// FunctionPassManager
1791bool PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1792 StringRef PipelineText, bool VerifyEachPass,
1793 bool DebugLogging) {
1794 auto Pipeline = parsePipelineText(PipelineText);
1795 if (!Pipeline || Pipeline->empty())
1796 return false;
1797
1798 StringRef FirstName = Pipeline->front().Name;
1799 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
1800 return false;
1801
1802 return parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1803 DebugLogging);
1804}
1805
1806// Primary pass pipeline description parsing routine for a \c LoopPassManager
1807bool PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1808 StringRef PipelineText, bool VerifyEachPass,
1809 bool DebugLogging) {
1810 auto Pipeline = parsePipelineText(PipelineText);
1811 if (!Pipeline || Pipeline->empty())
1812 return false;
1813
1814 return parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1815}
1816
Chandler Carruthedf59962016-02-18 09:45:17 +00001817bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00001818 // If the pipeline just consists of the word 'default' just replace the AA
1819 // manager with our default one.
1820 if (PipelineText == "default") {
1821 AA = buildDefaultAAPipeline();
1822 return true;
1823 }
1824
Chandler Carruthedf59962016-02-18 09:45:17 +00001825 while (!PipelineText.empty()) {
1826 StringRef Name;
1827 std::tie(Name, PipelineText) = PipelineText.split(',');
1828 if (!parseAAPassName(AA, Name))
1829 return false;
1830 }
1831
1832 return true;
1833}