blob: 35ed0ace647e7a7551e5a5150623f1f971d361c2 [file] [log] [blame]
Chandler Carruth1ff77242015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth66445382014-01-11 08:16:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10///
Chandler Carruth1ff77242015-03-07 09:02:36 +000011/// This file provides the implementation of the PassBuilder based on our
12/// static pass registry as well as related functionality. It also provides
13/// helpers to aid in analyzing, debugging, and testing passes and pass
14/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000015///
16//===----------------------------------------------------------------------===//
17
Chandler Carruth1ff77242015-03-07 09:02:36 +000018#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000019#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000020#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000021#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000022#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000023#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000025#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000026#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000027#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
28#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000029#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000030#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000031#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000032#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000033#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000034#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000035#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000036#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000037#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000038#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000039#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000040#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000041#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000042#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000043#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000044#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000045#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000046#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000047#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000048#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000049#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000050#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000051#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000052#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000053#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000054#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000055#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000056#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000057#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000058#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000059#include "llvm/IR/PassManager.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000091#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000092#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000093#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000094#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
95#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +000096#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Justin Bogner19b67992015-10-30 23:13:18 +000097#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +000098#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +000099#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000100#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000101#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000102#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000103#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000104#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000105#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000106#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000107#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000108#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000109#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000110#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000111#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000112#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000113#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000114#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000115#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000116#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000117#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000118#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000119#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000120#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000121#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000122#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000123#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000124#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000125#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000126#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000127#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000128#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000129#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000130#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000131#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000132#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000133#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Sean Silva6347df02016-06-14 02:44:55 +0000134#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000135#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000136#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000137#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000138#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000139#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000140#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000141#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000142#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000143#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000144#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000145#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000146#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000147#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000148#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000149#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000150#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000151#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000152#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000153#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000154#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000155#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000156#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000157#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000158#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000159#include "llvm/Transforms/Utils/SymbolRewriter.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000160#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000161#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000162
Chandler Carruth66445382014-01-11 08:16:35 +0000163using namespace llvm;
164
Chandler Carruth719ffe12017-02-12 05:38:04 +0000165static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
166 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000167static cl::opt<bool>
168 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
169 cl::Hidden, cl::ZeroOrMore,
170 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000171
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000172static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000173 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000174 cl::Hidden, cl::ZeroOrMore,
175 cl::desc("Run NewGVN instead of GVN"));
176
Geoff Berry3cca1da2017-06-10 15:20:03 +0000177static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000178 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
179 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000180
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000181static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000182 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
183 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000184
Davide Italianobe1b6a92017-06-03 23:18:29 +0000185static cl::opt<bool> EnableGVNSink(
186 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
187 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
188
David Green963401d2018-07-01 12:47:30 +0000189static cl::opt<bool> EnableUnrollAndJam(
190 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
191 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
192
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000193static cl::opt<bool> EnableSyntheticCounts(
194 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
195 cl::desc("Run synthetic function entry count generation "
196 "pass"));
197
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000198static Regex DefaultAliasRegex(
199 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000200
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000201static cl::opt<bool>
202 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
203 cl::desc("Enable control height reduction optimization (CHR)"));
204
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000205extern cl::opt<bool> EnableHotColdSplit;
206
Chandler Carruthe3f50642016-12-22 06:59:15 +0000207static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
208 switch (Level) {
209 case PassBuilder::O0:
210 case PassBuilder::O1:
211 case PassBuilder::O2:
212 case PassBuilder::O3:
213 return false;
214
215 case PassBuilder::Os:
216 case PassBuilder::Oz:
217 return true;
218 }
219 llvm_unreachable("Invalid optimization level!");
220}
221
Chandler Carruth66445382014-01-11 08:16:35 +0000222namespace {
223
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000224/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000225struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000226 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000227 return PreservedAnalyses::all();
228 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000229 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000230};
231
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000232/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000233class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
234 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000235 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000236
237public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000238 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000239 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000240 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000241};
242
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000243/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000244struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000245 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
246 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000247 return PreservedAnalyses::all();
248 }
249 static StringRef name() { return "NoOpCGSCCPass"; }
250};
251
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000252/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000253class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
254 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000255 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000256
257public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000258 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000259 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000260 return Result();
261 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000262 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000263};
264
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000265/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000266struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000267 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000268 return PreservedAnalyses::all();
269 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000270 static StringRef name() { return "NoOpFunctionPass"; }
271};
272
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000273/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000274class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
275 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000276 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000277
278public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000279 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000280 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000281 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000282};
283
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000284/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000285struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000286 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
287 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000288 return PreservedAnalyses::all();
289 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000290 static StringRef name() { return "NoOpLoopPass"; }
291};
292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000293/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000294class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
295 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000296 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000297
298public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000299 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000300 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
301 return Result();
302 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000303 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000304};
305
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000306AnalysisKey NoOpModuleAnalysis::Key;
307AnalysisKey NoOpCGSCCAnalysis::Key;
308AnalysisKey NoOpFunctionAnalysis::Key;
309AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000310
Chandler Carruth66445382014-01-11 08:16:35 +0000311} // End anonymous namespace.
312
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000313void PassBuilder::invokePeepholeEPCallbacks(
314 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
315 for (auto &C : PeepholeEPCallbacks)
316 C(FPM, Level);
317}
318
Chandler Carruth1ff77242015-03-07 09:02:36 +0000319void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000320#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000321 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000322#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000323
324 for (auto &C : ModuleAnalysisRegistrationCallbacks)
325 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000326}
327
Chandler Carruth1ff77242015-03-07 09:02:36 +0000328void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000329#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000330 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000331#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000332
333 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
334 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000335}
336
Chandler Carruth1ff77242015-03-07 09:02:36 +0000337void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000338#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000339 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000340#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000341
342 for (auto &C : FunctionAnalysisRegistrationCallbacks)
343 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000344}
345
Justin Bognereecc3c82016-02-25 07:23:08 +0000346void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000347#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000348 LAM.registerPass([&] { return CREATE_PASS; });
349#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000350
351 for (auto &C : LoopAnalysisRegistrationCallbacks)
352 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000353}
354
Chandler Carruthe3f50642016-12-22 06:59:15 +0000355FunctionPassManager
356PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000357 ThinLTOPhase Phase,
358 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000359 assert(Level != O0 && "Must request optimizations!");
360 FunctionPassManager FPM(DebugLogging);
361
362 // Form SSA out of local memory accesses after breaking apart aggregates into
363 // scalars.
364 FPM.addPass(SROA());
365
366 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000367 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000368
Davide Italianoc3688312017-06-01 23:08:14 +0000369 // Hoisting of scalars and load expressions.
370 if (EnableGVNHoist)
371 FPM.addPass(GVNHoistPass());
372
Davide Italianobe1b6a92017-06-03 23:18:29 +0000373 // Global value numbering based sinking.
374 if (EnableGVNSink) {
375 FPM.addPass(GVNSinkPass());
376 FPM.addPass(SimplifyCFGPass());
377 }
378
Chandler Carruthe3f50642016-12-22 06:59:15 +0000379 // Speculative execution if the target has divergent branches; otherwise nop.
380 FPM.addPass(SpeculativeExecutionPass());
381
382 // Optimize based on known information about branches, and cleanup afterward.
383 FPM.addPass(JumpThreadingPass());
384 FPM.addPass(CorrelatedValuePropagationPass());
385 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000386 if (Level == O3)
387 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000388 FPM.addPass(InstCombinePass());
389
390 if (!isOptimizingForSize(Level))
391 FPM.addPass(LibCallsShrinkWrapPass());
392
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000393 invokePeepholeEPCallbacks(FPM, Level);
394
Rong Xue1f42452017-10-23 22:21:29 +0000395 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
396 // using the size value profile. Don't perform this when optimizing for size.
397 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
398 !isOptimizingForSize(Level))
399 FPM.addPass(PGOMemOPSizeOpt());
400
Chandler Carruthe3f50642016-12-22 06:59:15 +0000401 FPM.addPass(TailCallElimPass());
402 FPM.addPass(SimplifyCFGPass());
403
404 // Form canonically associated expression trees, and simplify the trees using
405 // basic mathematical properties. For example, this will form (nearly)
406 // minimal multiplication trees.
407 FPM.addPass(ReassociatePass());
408
409 // Add the primary loop simplification pipeline.
410 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000411 // some function passes in between them. These can and should be removed
412 // and/or replaced by scheduling the loop pass equivalents in the correct
413 // positions. But those equivalent passes aren't powerful enough yet.
414 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
415 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
416 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
417 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000418 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
419
Chandler Carruth71fd2702018-05-30 02:46:45 +0000420 // Simplify the loop body. We do this initially to clean up after other loop
421 // passes run, either when iterating on a loop or on inner loops with
422 // implications on the outer loop.
423 LPM1.addPass(LoopInstSimplifyPass());
424 LPM1.addPass(LoopSimplifyCFGPass());
425
Chandler Carruthe3f50642016-12-22 06:59:15 +0000426 // Rotate Loop - disable header duplication at -Oz
427 LPM1.addPass(LoopRotatePass(Level != Oz));
428 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000429 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000430 LPM2.addPass(IndVarSimplifyPass());
431 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000432
433 for (auto &C : LateLoopOptimizationsEPCallbacks)
434 C(LPM2, Level);
435
Chandler Carruth79b733b2017-01-26 23:21:17 +0000436 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000437 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000438 // because it changes IR to makes profile annotation in back compile
439 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000440 if (Phase != ThinLTOPhase::PreLink ||
441 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000442 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000443
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000444 for (auto &C : LoopOptimizerEndEPCallbacks)
445 C(LPM2, Level);
446
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000447 // We provide the opt remark emitter pass for LICM to use. We only need to do
448 // this once as it is immutable.
449 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000450 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000451 FPM.addPass(SimplifyCFGPass());
452 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000453 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000454
455 // Eliminate redundancies.
456 if (Level != O1) {
457 // These passes add substantial compile time so skip them at O1.
458 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000459 if (RunNewGVN)
460 FPM.addPass(NewGVNPass());
461 else
462 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000463 }
464
465 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
466 FPM.addPass(MemCpyOptPass());
467
468 // Sparse conditional constant propagation.
469 // FIXME: It isn't clear why we do this *after* loop passes rather than
470 // before...
471 FPM.addPass(SCCPPass());
472
473 // Delete dead bit computations (instcombine runs after to fold away the dead
474 // computations, and then ADCE will run later to exploit any new DCE
475 // opportunities that creates).
476 FPM.addPass(BDCEPass());
477
478 // Run instcombine after redundancy and dead bit elimination to exploit
479 // opportunities opened up by them.
480 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000481 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000482
483 // Re-consider control flow based optimizations after redundancy elimination,
484 // redo DCE, etc.
485 FPM.addPass(JumpThreadingPass());
486 FPM.addPass(CorrelatedValuePropagationPass());
487 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000488 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000489
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000490 for (auto &C : ScalarOptimizerLateEPCallbacks)
491 C(FPM, Level);
492
Chandler Carruthe3f50642016-12-22 06:59:15 +0000493 // Finally, do an expensive DCE pass to catch all the dead code exposed by
494 // the simplifications and basic cleanup after all the simplifications.
495 FPM.addPass(ADCEPass());
496 FPM.addPass(SimplifyCFGPass());
497 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000498 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000499
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000500 if (EnableCHR && Level == O3 && PGOOpt &&
501 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
502 FPM.addPass(ControlHeightReductionPass());
503
Chandler Carruthe3f50642016-12-22 06:59:15 +0000504 return FPM;
505}
506
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000507void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
508 PassBuilder::OptimizationLevel Level,
509 bool RunProfileGen,
510 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000511 std::string ProfileUseFile,
512 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000513 // Generally running simplification passes and the inliner with an high
514 // threshold results in smaller executables, but there may be cases where
515 // the size grows, so let's be conservative here and skip this simplification
516 // at -Os/Oz.
517 if (!isOptimizingForSize(Level)) {
518 InlineParams IP;
519
520 // In the old pass manager, this is a cl::opt. Should still this be one?
521 IP.DefaultThreshold = 75;
522
523 // FIXME: The hint threshold has the same value used by the regular inliner.
524 // This should probably be lowered after performance testing.
525 // FIXME: this comment is cargo culted from the old pass manager, revisit).
526 IP.HintThreshold = 325;
527
528 CGSCCPassManager CGPipeline(DebugLogging);
529
530 CGPipeline.addPass(InlinerPass(IP));
531
532 FunctionPassManager FPM;
533 FPM.addPass(SROA());
534 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
535 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
536 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000537 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000538
Davide Italiano513dfaa2017-02-13 15:26:22 +0000539 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
540
541 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
542 }
543
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000544 // Delete anything that is now dead to make sure that we don't instrument
545 // dead code. Instrumentation can end up keeping dead code around and
546 // dramatically increase code size.
547 MPM.addPass(GlobalDCEPass());
548
Davide Italiano513dfaa2017-02-13 15:26:22 +0000549 if (RunProfileGen) {
550 MPM.addPass(PGOInstrumentationGen());
551
Xinliang David Lib67530e2017-06-25 00:26:43 +0000552 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000553 FPM.addPass(
554 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000555 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
556
Davide Italiano513dfaa2017-02-13 15:26:22 +0000557 // Add the profile lowering pass.
558 InstrProfOptions Options;
559 if (!ProfileGenFile.empty())
560 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000561 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000562 MPM.addPass(InstrProfiling(Options));
563 }
564
565 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000566 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000567}
568
Easwaran Raman8249fac2017-06-28 13:33:49 +0000569static InlineParams
570getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
571 auto O3 = PassBuilder::O3;
572 unsigned OptLevel = Level > O3 ? 2 : Level;
573 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
574 return getInlineParams(OptLevel, SizeLevel);
575}
576
Chandler Carruthe3f50642016-12-22 06:59:15 +0000577ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000578PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000579 ThinLTOPhase Phase,
580 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000581 ModulePassManager MPM(DebugLogging);
582
Chandler Carruthe3f50642016-12-22 06:59:15 +0000583 // Do basic inference of function attributes from known properties of system
584 // libraries and other oracles.
585 MPM.addPass(InferFunctionAttrsPass());
586
587 // Create an early function pass manager to cleanup the output of the
588 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000589 FunctionPassManager EarlyFPM(DebugLogging);
590 EarlyFPM.addPass(SimplifyCFGPass());
591 EarlyFPM.addPass(SROA());
592 EarlyFPM.addPass(EarlyCSEPass());
593 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000594 if (Level == O3)
595 EarlyFPM.addPass(CallSiteSplittingPass());
596
Dehao Chen08f88312017-08-07 20:23:20 +0000597 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
598 // to convert bitcast to direct calls so that they can be inlined during the
599 // profile annotation prepration step.
600 // More details about SamplePGO design can be found in:
601 // https://research.google.com/pubs/pub45290.html
602 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
603 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
604 Phase == ThinLTOPhase::PostLink)
605 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000606 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000607
Dehao Chen08f88312017-08-07 20:23:20 +0000608 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
609 // Annotate sample profile right after early FPM to ensure freshness of
610 // the debug info.
Dehao Chend26dae02017-10-01 05:24:51 +0000611 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000612 PGOOpt->ProfileRemappingFile,
Dehao Chend26dae02017-10-01 05:24:51 +0000613 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000614 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
615 // for the profile annotation to be accurate in the ThinLTO backend.
616 if (Phase != ThinLTOPhase::PreLink)
617 // We perform early indirect call promotion here, before globalopt.
618 // This is important for the ThinLTO backend phase because otherwise
619 // imported available_externally functions look unreferenced and are
620 // removed.
621 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
622 true));
623 }
624
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000625 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000626 // and prior to optimizing globals.
627 // FIXME: This position in the pipeline hasn't been carefully considered in
628 // years, it should be re-analyzed.
629 MPM.addPass(IPSCCPPass());
630
Matthew Simpsoncb585582017-10-25 13:40:08 +0000631 // Attach metadata to indirect call sites indicating the set of functions
632 // they may target at run-time. This should follow IPSCCP.
633 MPM.addPass(CalledValuePropagationPass());
634
Chandler Carruthe3f50642016-12-22 06:59:15 +0000635 // Optimize globals to try and fold them into constants.
636 MPM.addPass(GlobalOptPass());
637
638 // Promote any localized globals to SSA registers.
639 // FIXME: Should this instead by a run of SROA?
640 // FIXME: We should probably run instcombine and simplify-cfg afterward to
641 // delete control flows that are dead once globals have been folded to
642 // constants.
643 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
644
645 // Remove any dead arguments exposed by cleanups and constand folding
646 // globals.
647 MPM.addPass(DeadArgumentEliminationPass());
648
649 // Create a small function pass pipeline to cleanup after all the global
650 // optimizations.
651 FunctionPassManager GlobalCleanupPM(DebugLogging);
652 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000653 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
654
Chandler Carruthe3f50642016-12-22 06:59:15 +0000655 GlobalCleanupPM.addPass(SimplifyCFGPass());
656 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
657
Dehao Chen89d32262017-08-02 01:28:31 +0000658 // Add all the requested passes for instrumentation PGO, if requested.
659 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
660 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
661 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000662 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
663 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000664 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000665 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000666
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000667 // Synthesize function entry counts for non-PGO compilation.
668 if (EnableSyntheticCounts && !PGOOpt)
669 MPM.addPass(SyntheticCountsPropagation());
670
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000671 // Require the GlobalsAA analysis for the module so we can query it within
672 // the CGSCC pipeline.
673 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000674
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000675 // Require the ProfileSummaryAnalysis for the module so we can query it within
676 // the inliner pass.
677 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
678
Chandler Carruthe3f50642016-12-22 06:59:15 +0000679 // Now begin the main postorder CGSCC pipeline.
680 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
681 // manager and trying to emulate its precise behavior. Much of this doesn't
682 // make a lot of sense and we should revisit the core CGSCC structure.
683 CGSCCPassManager MainCGPipeline(DebugLogging);
684
685 // Note: historically, the PruneEH pass was run first to deduce nounwind and
686 // generally clean up exception handling overhead. It isn't clear this is
687 // valuable as the inliner doesn't currently care whether it is inlining an
688 // invoke or a call.
689
690 // Run the inliner first. The theory is that we are walking bottom-up and so
691 // the callees have already been fully optimized, and we want to inline them
692 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000693 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000694 // because it makes profile annotation in the backend inaccurate.
695 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000696 if (Phase == ThinLTOPhase::PreLink &&
697 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000698 IP.HotCallSiteThreshold = 0;
699 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000700
701 // Now deduce any function attributes based in the current code.
702 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
703
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000704 // When at O3 add argument promotion to the pass pipeline.
705 // FIXME: It isn't at all clear why this should be limited to O3.
706 if (Level == O3)
707 MainCGPipeline.addPass(ArgumentPromotionPass());
708
Chandler Carruthe3f50642016-12-22 06:59:15 +0000709 // Lastly, add the core function simplification pipeline nested inside the
710 // CGSCC walk.
711 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000712 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000713
Teresa Johnsond7253352018-10-23 22:57:40 +0000714 // We only want to do hot cold splitting once for ThinLTO, during the
715 // post-link ThinLTO.
716 if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink)
Aditya Kumard9e2e382018-10-21 18:11:56 +0000717 MPM.addPass(HotColdSplittingPass());
718
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000719 for (auto &C : CGSCCOptimizerLateEPCallbacks)
720 C(MainCGPipeline, Level);
721
Chandler Carruth719ffe12017-02-12 05:38:04 +0000722 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
723 // to detect when we devirtualize indirect calls and iterate the SCC passes
724 // in that case to try and catch knock-on inlining or function attrs
725 // opportunities. Then we add it to the module pipeline by walking the SCCs
726 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000727 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000728 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000729 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000730
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000731 return MPM;
732}
733
734ModulePassManager
735PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
736 bool DebugLogging) {
737 ModulePassManager MPM(DebugLogging);
738
739 // Optimize globals now that the module is fully simplified.
740 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000741 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000742
Xinliang David Li126157c2017-05-22 16:41:57 +0000743 // Run partial inlining pass to partially inline functions that have
744 // large bodies.
745 if (RunPartialInlining)
746 MPM.addPass(PartialInlinerPass());
747
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000748 // Remove avail extern fns and globals definitions since we aren't compiling
749 // an object file for later LTO. For LTO we want to preserve these so they
750 // are eligible for inlining at link-time. Note if they are unreferenced they
751 // will be removed by GlobalDCE later, so this only impacts referenced
752 // available externally globals. Eventually they will be suppressed during
753 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
754 // may make globals referenced by available external functions dead and saves
755 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000756 MPM.addPass(EliminateAvailableExternallyPass());
757
758 // Do RPO function attribute inference across the module to forward-propagate
759 // attributes where applicable.
760 // FIXME: Is this really an optimization rather than a canonicalization?
761 MPM.addPass(ReversePostOrderFunctionAttrsPass());
762
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000763 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000764 // useful as the above will have inlined, DCE'ed, and function-attr
765 // propagated everything. We should at this point have a reasonably minimal
766 // and richly annotated call graph. By computing aliasing and mod/ref
767 // information for all local globals here, the late loop passes and notably
768 // the vectorizer will be able to use them to help recognize vectorizable
769 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000770 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000771
772 FunctionPassManager OptimizePM(DebugLogging);
773 OptimizePM.addPass(Float2IntPass());
774 // FIXME: We need to run some loop optimizations to re-rotate loops after
775 // simplify-cfg and others undo their rotation.
776
777 // Optimize the loop execution. These passes operate on entire loop nests
778 // rather than on each loop in an inside-out manner, and so they are actually
779 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000780
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000781 for (auto &C : VectorizerStartEPCallbacks)
782 C(OptimizePM, Level);
783
Chandler Carrutha95ff382017-01-27 00:50:21 +0000784 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000785 OptimizePM.addPass(
786 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000787
788 // Distribute loops to allow partial vectorization. I.e. isolate dependences
789 // into separate loop that would otherwise inhibit vectorization. This is
790 // currently only performed for loops marked with the metadata
791 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000792 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000793
794 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000795 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000796
Chandler Carruthbaabda92017-01-27 01:32:26 +0000797 // Eliminate loads by forwarding stores from the previous iteration to loads
798 // of the current iteration.
799 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000800
801 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000802 OptimizePM.addPass(InstCombinePass());
803
Chandler Carrutha95ff382017-01-27 00:50:21 +0000804 // Now that we've formed fast to execute loop structures, we do further
805 // optimizations. These are run afterward as they might block doing complex
806 // analyses and transforms such as what are needed for loop vectorization.
807
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000808 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
809 // GVN, loop transforms, and others have already run, so it's now better to
810 // convert to more optimized IR using more aggressive simplify CFG options.
811 // The extra sinking transform can create larger basic blocks, so do this
812 // before SLP vectorization.
813 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
814 forwardSwitchCondToPhi(true).
815 convertSwitchToLookupTable(true).
816 needCanonicalLoops(false).
817 sinkCommonInsts(true)));
818
Chandler Carruthe3f50642016-12-22 06:59:15 +0000819 // Optimize parallel scalar instruction chains into SIMD instructions.
820 OptimizePM.addPass(SLPVectorizerPass());
821
Chandler Carruthe3f50642016-12-22 06:59:15 +0000822 OptimizePM.addPass(InstCombinePass());
823
824 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000825 // execution resources of an out-of-order processor. We also then need to
826 // clean up redundancies and loop invariant code.
827 // FIXME: It would be really good to use a loop-integrated instruction
828 // combiner for cleanup here so that the unrolling and LICM can be pipelined
829 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000830 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
831 if (EnableUnrollAndJam) {
832 OptimizePM.addPass(
833 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
834 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000835 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000836 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000837 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000838 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000839
840 // Now that we've vectorized and unrolled loops, we may have more refined
841 // alignment information, try to re-derive it here.
842 OptimizePM.addPass(AlignmentFromAssumptionsPass());
843
Chandler Carrutha95ff382017-01-27 00:50:21 +0000844 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
845 // canonicalization pass that enables other optimizations. As a result,
846 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
847 // result too early.
848 OptimizePM.addPass(LoopSinkPass());
849
850 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000851 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000852
Sanjay Patel6fd43912017-09-09 13:38:18 +0000853 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
854 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
855 // flattening of blocks.
856 OptimizePM.addPass(DivRemPairsPass());
857
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000858 // LoopSink (and other loop passes since the last simplifyCFG) might have
859 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
860 OptimizePM.addPass(SimplifyCFGPass());
861
Chandler Carruthc34f7892017-11-28 11:32:31 +0000862 // Optimize PHIs by speculating around them when profitable. Note that this
863 // pass needs to be run after any PRE or similar pass as it is essentially
864 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
865 OptimizePM.addPass(SpeculateAroundPHIsPass());
866
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000867 for (auto &C : OptimizerLastEPCallbacks)
868 C(OptimizePM, Level);
869
Chandler Carrutha95ff382017-01-27 00:50:21 +0000870 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000871 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
872
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000873 MPM.addPass(CGProfilePass());
874
Chandler Carruthe3f50642016-12-22 06:59:15 +0000875 // Now we need to do some global optimization transforms.
876 // FIXME: It would seem like these should come first in the optimization
877 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
878 // ordering here.
879 MPM.addPass(GlobalDCEPass());
880 MPM.addPass(ConstantMergePass());
881
882 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000883}
884
Chandler Carruthe3f50642016-12-22 06:59:15 +0000885ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000886PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
887 bool DebugLogging) {
888 assert(Level != O0 && "Must request optimizations for the default pipeline!");
889
890 ModulePassManager MPM(DebugLogging);
891
892 // Force any function attributes we want the rest of the pipeline to observe.
893 MPM.addPass(ForceFunctionAttrsPass());
894
David Blaikie0c64f5a2018-01-23 01:25:20 +0000895 // Apply module pipeline start EP callback.
896 for (auto &C : PipelineStartEPCallbacks)
897 C(MPM);
898
Dehao Chen08f88312017-08-07 20:23:20 +0000899 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000900 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
901
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000902 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000903 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
904 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000905
906 // Now add the optimization pipeline.
907 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
908
909 return MPM;
910}
911
912ModulePassManager
913PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
914 bool DebugLogging) {
915 assert(Level != O0 && "Must request optimizations for the default pipeline!");
916
917 ModulePassManager MPM(DebugLogging);
918
919 // Force any function attributes we want the rest of the pipeline to observe.
920 MPM.addPass(ForceFunctionAttrsPass());
921
Dehao Chen08f88312017-08-07 20:23:20 +0000922 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000923 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
924
David Blaikie0c64f5a2018-01-23 01:25:20 +0000925 // Apply module pipeline start EP callback.
926 for (auto &C : PipelineStartEPCallbacks)
927 C(MPM);
928
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000929 // If we are planning to perform ThinLTO later, we don't bloat the code with
930 // unrolling/vectorization/... now. Just simplify the module as much as we
931 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000932 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
933 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000934
935 // Run partial inlining pass to partially inline functions that have
936 // large bodies.
937 // FIXME: It isn't clear whether this is really the right place to run this
938 // in ThinLTO. Because there is another canonicalization and simplification
939 // phase that will run after the thin link, running this here ends up with
940 // less information than will be available later and it may grow functions in
941 // ways that aren't beneficial.
942 if (RunPartialInlining)
943 MPM.addPass(PartialInlinerPass());
944
945 // Reduce the size of the IR as much as possible.
946 MPM.addPass(GlobalOptPass());
947
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000948 return MPM;
949}
950
Teresa Johnson28023db2018-07-19 14:51:32 +0000951ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
952 OptimizationLevel Level, bool DebugLogging,
953 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000954 ModulePassManager MPM(DebugLogging);
955
Teresa Johnson28023db2018-07-19 14:51:32 +0000956 if (ImportSummary) {
957 // These passes import type identifier resolutions for whole-program
958 // devirtualization and CFI. They must run early because other passes may
959 // disturb the specific instruction patterns that these passes look for,
960 // creating dependencies on resolutions that may not appear in the summary.
961 //
962 // For example, GVN may transform the pattern assume(type.test) appearing in
963 // two basic blocks into assume(phi(type.test, type.test)), which would
964 // transform a dependency on a WPD resolution into a dependency on a type
965 // identifier resolution for CFI.
966 //
967 // Also, WPD has access to more precise information than ICP and can
968 // devirtualize more effectively, so it should operate on the IR first.
969 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
970 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
971 }
972
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000973 // Force any function attributes we want the rest of the pipeline to observe.
974 MPM.addPass(ForceFunctionAttrsPass());
975
976 // During the ThinLTO backend phase we perform early indirect call promotion
977 // here, before globalopt. Otherwise imported available_externally functions
978 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000979 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
980 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000981 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000982 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
983 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000984
985 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000986 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
987 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000988
989 // Now add the optimization pipeline.
990 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
991
992 return MPM;
993}
994
995ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +0000996PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
997 bool DebugLogging) {
998 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000999 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +00001000 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001001}
1002
Teresa Johnson28023db2018-07-19 14:51:32 +00001003ModulePassManager
1004PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1005 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001006 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1007 ModulePassManager MPM(DebugLogging);
1008
Xin Tong642c8d32018-11-15 18:06:42 +00001009 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1010 // Load sample profile before running the LTO optimization pipeline.
1011 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1012 PGOOpt->ProfileRemappingFile,
1013 false /* ThinLTOPhase::PreLink */));
1014 }
1015
Davide Italiano089a9122017-01-24 00:57:39 +00001016 // Remove unused virtual tables to improve the quality of code generated by
1017 // whole-program devirtualization and bitset lowering.
1018 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001019
Davide Italiano089a9122017-01-24 00:57:39 +00001020 // Force any function attributes we want the rest of the pipeline to observe.
1021 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001022
Davide Italiano089a9122017-01-24 00:57:39 +00001023 // Do basic inference of function attributes from known properties of system
1024 // libraries and other oracles.
1025 MPM.addPass(InferFunctionAttrsPass());
1026
1027 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001028 FunctionPassManager EarlyFPM(DebugLogging);
1029 EarlyFPM.addPass(CallSiteSplittingPass());
1030 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1031
Davide Italiano089a9122017-01-24 00:57:39 +00001032 // Indirect call promotion. This should promote all the targets that are
1033 // left by the earlier promotion pass that promotes intra-module targets.
1034 // This two-step promotion is to save the compile time. For LTO, it should
1035 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001036 MPM.addPass(PGOIndirectCallPromotion(
1037 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001038 // Propagate constants at call sites into the functions they call. This
1039 // opens opportunities for globalopt (and inlining) by substituting function
1040 // pointers passed as arguments to direct uses of functions.
1041 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001042
1043 // Attach metadata to indirect call sites indicating the set of functions
1044 // they may target at run-time. This should follow IPSCCP.
1045 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001046 }
1047
1048 // Now deduce any function attributes based in the current code.
1049 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1050 PostOrderFunctionAttrsPass()));
1051
1052 // Do RPO function attribute inference across the module to forward-propagate
1053 // attributes where applicable.
1054 // FIXME: Is this really an optimization rather than a canonicalization?
1055 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1056
1057 // Use inragne annotations on GEP indices to split globals where beneficial.
1058 MPM.addPass(GlobalSplitPass());
1059
1060 // Run whole program optimization of virtual call when the list of callees
1061 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001062 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001063
1064 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001065 if (Level == 1) {
1066 // The LowerTypeTestsPass needs to run to lower type metadata and the
1067 // type.test intrinsics. The pass does nothing if CFI is disabled.
1068 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001069 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001070 }
Davide Italiano089a9122017-01-24 00:57:39 +00001071
1072 // Optimize globals to try and fold them into constants.
1073 MPM.addPass(GlobalOptPass());
1074
1075 // Promote any localized globals to SSA registers.
1076 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1077
1078 // Linking modules together can lead to duplicate global constant, only
1079 // keep one copy of each constant.
1080 MPM.addPass(ConstantMergePass());
1081
1082 // Remove unused arguments from functions.
1083 MPM.addPass(DeadArgumentEliminationPass());
1084
1085 // Reduce the code after globalopt and ipsccp. Both can open up significant
1086 // simplification opportunities, and both can propagate functions through
1087 // function pointers. When this happens, we often have to resolve varargs
1088 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001089 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001090 if (Level == O3)
1091 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001092 PeepholeFPM.addPass(InstCombinePass());
1093 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1094
1095 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001096
1097 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1098 // generally clean up exception handling overhead. It isn't clear this is
1099 // valuable as the inliner doesn't currently care whether it is inlining an
1100 // invoke or a call.
1101 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001102 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1103 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001104
1105 // Optimize globals again after we ran the inliner.
1106 MPM.addPass(GlobalOptPass());
1107
1108 // Garbage collect dead functions.
1109 // FIXME: Add ArgumentPromotion pass after once it's ported.
1110 MPM.addPass(GlobalDCEPass());
1111
1112 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001113 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001114 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001115 invokePeepholeEPCallbacks(FPM, Level);
1116
Davide Italiano089a9122017-01-24 00:57:39 +00001117 FPM.addPass(JumpThreadingPass());
1118
1119 // Break up allocas
1120 FPM.addPass(SROA());
1121
1122 // Run a few AA driver optimizations here and now to cleanup the code.
1123 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1124
1125 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1126 PostOrderFunctionAttrsPass()));
1127 // FIXME: here we run IP alias analysis in the legacy PM.
1128
1129 FunctionPassManager MainFPM;
1130
1131 // FIXME: once we fix LoopPass Manager, add LICM here.
1132 // FIXME: once we provide support for enabling MLSM, add it here.
1133 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001134 if (RunNewGVN)
1135 MainFPM.addPass(NewGVNPass());
1136 else
1137 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001138
1139 // Remove dead memcpy()'s.
1140 MainFPM.addPass(MemCpyOptPass());
1141
1142 // Nuke dead stores.
1143 MainFPM.addPass(DSEPass());
1144
1145 // FIXME: at this point, we run a bunch of loop passes:
1146 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1147 // loopVectorize. Enable them once the remaining issue with LPM
1148 // are sorted out.
1149
1150 MainFPM.addPass(InstCombinePass());
1151 MainFPM.addPass(SimplifyCFGPass());
1152 MainFPM.addPass(SCCPPass());
1153 MainFPM.addPass(InstCombinePass());
1154 MainFPM.addPass(BDCEPass());
1155
1156 // FIXME: We may want to run SLPVectorizer here.
1157 // After vectorization, assume intrinsics may tell us more
1158 // about pointer alignments.
1159#if 0
1160 MainFPM.add(AlignmentFromAssumptionsPass());
1161#endif
1162
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001163 // FIXME: Conditionally run LoadCombine here, after it's ported
1164 // (in case we still have this pass, given its questionable usefulness).
1165
Davide Italiano089a9122017-01-24 00:57:39 +00001166 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001167 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001168 MainFPM.addPass(JumpThreadingPass());
1169 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1170
1171 // Create a function that performs CFI checks for cross-DSO calls with
1172 // targets in the current module.
1173 MPM.addPass(CrossDSOCFIPass());
1174
1175 // Lower type metadata and the type.test intrinsic. This pass supports
1176 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1177 // to be run at link time if CFI is enabled. This pass does nothing if
1178 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001179 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001180
1181 // Add late LTO optimization passes.
1182 // Delete basic blocks, which optimization passes may have killed.
1183 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1184
1185 // Drop bodies of available eternally objects to improve GlobalDCE.
1186 MPM.addPass(EliminateAvailableExternallyPass());
1187
1188 // Now that we have optimized the program, discard unreachable functions.
1189 MPM.addPass(GlobalDCEPass());
1190
1191 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001192 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001193}
1194
Chandler Carruth060ad612016-12-23 20:38:19 +00001195AAManager PassBuilder::buildDefaultAAPipeline() {
1196 AAManager AA;
1197
1198 // The order in which these are registered determines their priority when
1199 // being queried.
1200
1201 // First we register the basic alias analysis that provides the majority of
1202 // per-function local AA logic. This is a stateless, on-demand local set of
1203 // AA techniques.
1204 AA.registerFunctionAnalysis<BasicAA>();
1205
1206 // Next we query fast, specialized alias analyses that wrap IR-embedded
1207 // information about aliasing.
1208 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1209 AA.registerFunctionAnalysis<TypeBasedAA>();
1210
1211 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001212 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1213 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001214 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001215 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001216
1217 return AA;
1218}
1219
Chandler Carruth241bf242016-08-03 07:44:48 +00001220static Optional<int> parseRepeatPassName(StringRef Name) {
1221 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1222 return None;
1223 int Count;
1224 if (Name.getAsInteger(0, Count) || Count <= 0)
1225 return None;
1226 return Count;
1227}
1228
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001229static Optional<int> parseDevirtPassName(StringRef Name) {
1230 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1231 return None;
1232 int Count;
1233 if (Name.getAsInteger(0, Count) || Count <= 0)
1234 return None;
1235 return Count;
1236}
1237
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001238/// Tests whether a pass name starts with a valid prefix for a default pipeline
1239/// alias.
1240static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1241 return Name.startswith("default") || Name.startswith("thinlto") ||
1242 Name.startswith("lto");
1243}
1244
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001245/// Tests whether registered callbacks will accept a given pass name.
1246///
1247/// When parsing a pipeline text, the type of the outermost pipeline may be
1248/// omitted, in which case the type is automatically determined from the first
1249/// pass name in the text. This may be a name that is handled through one of the
1250/// callbacks. We check this through the oridinary parsing callbacks by setting
1251/// up a dummy PassManager in order to not force the client to also handle this
1252/// type of query.
1253template <typename PassManagerT, typename CallbacksT>
1254static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1255 if (!Callbacks.empty()) {
1256 PassManagerT DummyPM;
1257 for (auto &CB : Callbacks)
1258 if (CB(Name, DummyPM, {}))
1259 return true;
1260 }
1261 return false;
1262}
1263
1264template <typename CallbacksT>
1265static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001266 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001267 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001268 return DefaultAliasRegex.match(Name);
1269
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001270 // Explicitly handle pass manager names.
1271 if (Name == "module")
1272 return true;
1273 if (Name == "cgscc")
1274 return true;
1275 if (Name == "function")
1276 return true;
1277
Chandler Carruth241bf242016-08-03 07:44:48 +00001278 // Explicitly handle custom-parsed pass names.
1279 if (parseRepeatPassName(Name))
1280 return true;
1281
Chandler Carruth74a8a222016-06-17 07:15:29 +00001282#define MODULE_PASS(NAME, CREATE_PASS) \
1283 if (Name == NAME) \
1284 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001285#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001286 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001287 return true;
1288#include "PassRegistry.def"
1289
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001290 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001291}
1292
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001293template <typename CallbacksT>
1294static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001295 // Explicitly handle pass manager names.
1296 if (Name == "cgscc")
1297 return true;
1298 if (Name == "function")
1299 return true;
1300
Chandler Carruth241bf242016-08-03 07:44:48 +00001301 // Explicitly handle custom-parsed pass names.
1302 if (parseRepeatPassName(Name))
1303 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001304 if (parseDevirtPassName(Name))
1305 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001306
Chandler Carruth74a8a222016-06-17 07:15:29 +00001307#define CGSCC_PASS(NAME, CREATE_PASS) \
1308 if (Name == NAME) \
1309 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001310#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001311 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001312 return true;
1313#include "PassRegistry.def"
1314
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001315 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001316}
1317
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001318template <typename CallbacksT>
1319static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001320 // Explicitly handle pass manager names.
1321 if (Name == "function")
1322 return true;
1323 if (Name == "loop")
1324 return true;
1325
Chandler Carruth241bf242016-08-03 07:44:48 +00001326 // Explicitly handle custom-parsed pass names.
1327 if (parseRepeatPassName(Name))
1328 return true;
1329
Chandler Carruth74a8a222016-06-17 07:15:29 +00001330#define FUNCTION_PASS(NAME, CREATE_PASS) \
1331 if (Name == NAME) \
1332 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001333#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001334 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001335 return true;
1336#include "PassRegistry.def"
1337
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001338 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001339}
1340
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001341template <typename CallbacksT>
1342static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001343 // Explicitly handle pass manager names.
1344 if (Name == "loop")
1345 return true;
1346
Chandler Carruth241bf242016-08-03 07:44:48 +00001347 // Explicitly handle custom-parsed pass names.
1348 if (parseRepeatPassName(Name))
1349 return true;
1350
Chandler Carruth74a8a222016-06-17 07:15:29 +00001351#define LOOP_PASS(NAME, CREATE_PASS) \
1352 if (Name == NAME) \
1353 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001354#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1355 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1356 return true;
1357#include "PassRegistry.def"
1358
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001359 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001360}
1361
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001362Optional<std::vector<PassBuilder::PipelineElement>>
1363PassBuilder::parsePipelineText(StringRef Text) {
1364 std::vector<PipelineElement> ResultPipeline;
1365
1366 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1367 &ResultPipeline};
1368 for (;;) {
1369 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1370 size_t Pos = Text.find_first_of(",()");
1371 Pipeline.push_back({Text.substr(0, Pos), {}});
1372
1373 // If we have a single terminating name, we're done.
1374 if (Pos == Text.npos)
1375 break;
1376
1377 char Sep = Text[Pos];
1378 Text = Text.substr(Pos + 1);
1379 if (Sep == ',')
1380 // Just a name ending in a comma, continue.
1381 continue;
1382
1383 if (Sep == '(') {
1384 // Push the inner pipeline onto the stack to continue processing.
1385 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1386 continue;
1387 }
1388
1389 assert(Sep == ')' && "Bogus separator!");
1390 // When handling the close parenthesis, we greedily consume them to avoid
1391 // empty strings in the pipeline.
1392 do {
1393 // If we try to pop the outer pipeline we have unbalanced parentheses.
1394 if (PipelineStack.size() == 1)
1395 return None;
1396
1397 PipelineStack.pop_back();
1398 } while (Text.consume_front(")"));
1399
1400 // Check if we've finished parsing.
1401 if (Text.empty())
1402 break;
1403
1404 // Otherwise, the end of an inner pipeline always has to be followed by
1405 // a comma, and then we can continue.
1406 if (!Text.consume_front(","))
1407 return None;
1408 }
1409
1410 if (PipelineStack.size() > 1)
1411 // Unbalanced paretheses.
1412 return None;
1413
1414 assert(PipelineStack.back() == &ResultPipeline &&
1415 "Wrong pipeline at the bottom of the stack!");
1416 return {std::move(ResultPipeline)};
1417}
1418
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001419Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1420 const PipelineElement &E,
1421 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001422 auto &Name = E.Name;
1423 auto &InnerPipeline = E.InnerPipeline;
1424
1425 // First handle complex passes like the pass managers which carry pipelines.
1426 if (!InnerPipeline.empty()) {
1427 if (Name == "module") {
1428 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001429 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1430 VerifyEachPass, DebugLogging))
1431 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001432 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001433 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001434 }
1435 if (Name == "cgscc") {
1436 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001437 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1438 DebugLogging))
1439 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001440 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001441 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001442 }
1443 if (Name == "function") {
1444 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001445 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1446 VerifyEachPass, DebugLogging))
1447 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001448 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001449 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001450 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001451 if (auto Count = parseRepeatPassName(Name)) {
1452 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001453 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1454 VerifyEachPass, DebugLogging))
1455 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001456 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001457 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001458 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001459
1460 for (auto &C : ModulePipelineParsingCallbacks)
1461 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001462 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001463
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001464 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001465 return make_error<StringError>(
1466 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1467 inconvertibleErrorCode());
1468 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001469 }
1470
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001471 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001472 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001473 SmallVector<StringRef, 3> Matches;
1474 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001475 return make_error<StringError>(
1476 formatv("unknown default pipeline alias '{0}'", Name).str(),
1477 inconvertibleErrorCode());
1478
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001479 assert(Matches.size() == 3 && "Must capture two matched strings!");
1480
Jordan Rosef85a95f2016-07-25 18:34:51 +00001481 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001482 .Case("O0", O0)
1483 .Case("O1", O1)
1484 .Case("O2", O2)
1485 .Case("O3", O3)
1486 .Case("Os", Os)
1487 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001488 if (L == O0)
1489 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001490 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001491
1492 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001493 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001494 } else if (Matches[1] == "thinlto-pre-link") {
1495 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1496 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001497 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001498 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001499 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001500 } else {
1501 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001502 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001503 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001504 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001505 }
1506
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001507 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001508#define MODULE_PASS(NAME, CREATE_PASS) \
1509 if (Name == NAME) { \
1510 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001511 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001512 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001513#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1514 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001515 MPM.addPass( \
1516 RequireAnalysisPass< \
1517 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001518 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001519 } \
1520 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001521 MPM.addPass(InvalidateAnalysisPass< \
1522 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001523 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001524 }
1525#include "PassRegistry.def"
1526
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001527 for (auto &C : ModulePipelineParsingCallbacks)
1528 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001529 return Error::success();
1530 return make_error<StringError>(
1531 formatv("unknown module pass '{0}'", Name).str(),
1532 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001533}
1534
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001535Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1536 const PipelineElement &E, bool VerifyEachPass,
1537 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001538 auto &Name = E.Name;
1539 auto &InnerPipeline = E.InnerPipeline;
1540
1541 // First handle complex passes like the pass managers which carry pipelines.
1542 if (!InnerPipeline.empty()) {
1543 if (Name == "cgscc") {
1544 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001545 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1546 VerifyEachPass, DebugLogging))
1547 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001548 // Add the nested pass manager with the appropriate adaptor.
1549 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001550 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001551 }
1552 if (Name == "function") {
1553 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001554 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1555 VerifyEachPass, DebugLogging))
1556 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001557 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001558 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001559 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001560 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001561 if (auto Count = parseRepeatPassName(Name)) {
1562 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001563 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1564 VerifyEachPass, DebugLogging))
1565 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001566 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001567 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001568 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001569 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1570 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001571 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1572 VerifyEachPass, DebugLogging))
1573 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001574 CGPM.addPass(
1575 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001576 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001577 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001578
1579 for (auto &C : CGSCCPipelineParsingCallbacks)
1580 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001581 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001582
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001583 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001584 return make_error<StringError>(
1585 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1586 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001587 }
1588
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001589// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001590#define CGSCC_PASS(NAME, CREATE_PASS) \
1591 if (Name == NAME) { \
1592 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001593 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001594 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001595#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1596 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001597 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001598 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001599 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1600 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001601 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001602 } \
1603 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001604 CGPM.addPass(InvalidateAnalysisPass< \
1605 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001606 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001607 }
1608#include "PassRegistry.def"
1609
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001610 for (auto &C : CGSCCPipelineParsingCallbacks)
1611 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001612 return Error::success();
1613 return make_error<StringError>(
1614 formatv("unknown cgscc pass '{0}'", Name).str(),
1615 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001616}
1617
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001618Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1619 const PipelineElement &E,
1620 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001621 auto &Name = E.Name;
1622 auto &InnerPipeline = E.InnerPipeline;
1623
1624 // First handle complex passes like the pass managers which carry pipelines.
1625 if (!InnerPipeline.empty()) {
1626 if (Name == "function") {
1627 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001628 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1629 VerifyEachPass, DebugLogging))
1630 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001631 // Add the nested pass manager with the appropriate adaptor.
1632 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001633 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001634 }
1635 if (Name == "loop") {
1636 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001637 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1638 DebugLogging))
1639 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001640 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001641 FPM.addPass(
1642 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001643 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001644 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001645 if (auto Count = parseRepeatPassName(Name)) {
1646 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001647 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1648 VerifyEachPass, DebugLogging))
1649 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001650 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001651 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001652 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001653
1654 for (auto &C : FunctionPipelineParsingCallbacks)
1655 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001656 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001657
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001658 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001659 return make_error<StringError>(
1660 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1661 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001662 }
1663
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001664// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001665#define FUNCTION_PASS(NAME, CREATE_PASS) \
1666 if (Name == NAME) { \
1667 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001668 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001669 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001670#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1671 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001672 FPM.addPass( \
1673 RequireAnalysisPass< \
1674 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001675 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001676 } \
1677 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001678 FPM.addPass(InvalidateAnalysisPass< \
1679 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001680 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001681 }
1682#include "PassRegistry.def"
1683
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001684 for (auto &C : FunctionPipelineParsingCallbacks)
1685 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001686 return Error::success();
1687 return make_error<StringError>(
1688 formatv("unknown function pass '{0}'", Name).str(),
1689 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001690}
1691
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001692Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1693 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001694 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001695 auto &InnerPipeline = E.InnerPipeline;
1696
1697 // First handle complex passes like the pass managers which carry pipelines.
1698 if (!InnerPipeline.empty()) {
1699 if (Name == "loop") {
1700 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001701 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1702 VerifyEachPass, DebugLogging))
1703 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001704 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001705 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001706 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001707 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001708 if (auto Count = parseRepeatPassName(Name)) {
1709 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001710 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1711 VerifyEachPass, DebugLogging))
1712 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001713 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001714 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001715 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001716
1717 for (auto &C : LoopPipelineParsingCallbacks)
1718 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001719 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001720
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001721 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001722 return make_error<StringError>(
1723 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1724 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001725 }
1726
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001727// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001728#define LOOP_PASS(NAME, CREATE_PASS) \
1729 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001730 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001731 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001732 }
1733#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1734 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001735 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001736 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1737 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1738 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001739 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001740 } \
1741 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001742 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001743 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001744 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001745 }
1746#include "PassRegistry.def"
1747
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001748 for (auto &C : LoopPipelineParsingCallbacks)
1749 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001750 return Error::success();
1751 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1752 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001753}
1754
Chandler Carruthedf59962016-02-18 09:45:17 +00001755bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001756#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1757 if (Name == NAME) { \
1758 AA.registerModuleAnalysis< \
1759 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1760 return true; \
1761 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001762#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1763 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001764 AA.registerFunctionAnalysis< \
1765 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001766 return true; \
1767 }
1768#include "PassRegistry.def"
1769
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001770 for (auto &C : AAParsingCallbacks)
1771 if (C(Name, AA))
1772 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001773 return false;
1774}
1775
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001776Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001777 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001778 bool VerifyEachPass,
1779 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001780 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001781 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1782 return Err;
1783 // FIXME: No verifier support for Loop passes!
1784 }
1785 return Error::success();
1786}
1787
1788Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1789 ArrayRef<PipelineElement> Pipeline,
1790 bool VerifyEachPass,
1791 bool DebugLogging) {
1792 for (const auto &Element : Pipeline) {
1793 if (auto Err =
1794 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1795 return Err;
1796 if (VerifyEachPass)
1797 FPM.addPass(VerifierPass());
1798 }
1799 return Error::success();
1800}
1801
1802Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1803 ArrayRef<PipelineElement> Pipeline,
1804 bool VerifyEachPass,
1805 bool DebugLogging) {
1806 for (const auto &Element : Pipeline) {
1807 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1808 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001809 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001810 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001811 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001812}
1813
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001814void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1815 FunctionAnalysisManager &FAM,
1816 CGSCCAnalysisManager &CGAM,
1817 ModuleAnalysisManager &MAM) {
1818 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1819 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001820 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1821 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1822 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1823 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1824 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1825}
1826
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001827Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1828 ArrayRef<PipelineElement> Pipeline,
1829 bool VerifyEachPass,
1830 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001831 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001832 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1833 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001834 if (VerifyEachPass)
1835 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001836 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001837 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001838}
1839
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001840// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001841// FIXME: Should this routine accept a TargetMachine or require the caller to
1842// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001843Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1844 StringRef PipelineText,
1845 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001846 auto Pipeline = parsePipelineText(PipelineText);
1847 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001848 return make_error<StringError>(
1849 formatv("invalid pipeline '{0}'", PipelineText).str(),
1850 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001851
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001852 // If the first name isn't at the module layer, wrap the pipeline up
1853 // automatically.
1854 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001855
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001856 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1857 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001858 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001859 } else if (isFunctionPassName(FirstName,
1860 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001861 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001862 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001863 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001864 } else {
1865 for (auto &C : TopLevelPipelineParsingCallbacks)
1866 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001867 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001868
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001869 // Unknown pass or pipeline name!
1870 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1871 return make_error<StringError>(
1872 formatv("unknown {0} name '{1}'",
1873 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1874 .str(),
1875 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001876 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001877 }
1878
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001879 if (auto Err =
1880 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1881 return Err;
1882 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001883}
Chandler Carruthedf59962016-02-18 09:45:17 +00001884
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001885// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001886Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1887 StringRef PipelineText,
1888 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001889 auto Pipeline = parsePipelineText(PipelineText);
1890 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001891 return make_error<StringError>(
1892 formatv("invalid pipeline '{0}'", PipelineText).str(),
1893 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001894
1895 StringRef FirstName = Pipeline->front().Name;
1896 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001897 return make_error<StringError>(
1898 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
1899 PipelineText)
1900 .str(),
1901 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001902
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001903 if (auto Err =
1904 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1905 return Err;
1906 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001907}
1908
1909// Primary pass pipeline description parsing routine for a \c
1910// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001911Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1912 StringRef PipelineText,
1913 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001914 auto Pipeline = parsePipelineText(PipelineText);
1915 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001916 return make_error<StringError>(
1917 formatv("invalid pipeline '{0}'", PipelineText).str(),
1918 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001919
1920 StringRef FirstName = Pipeline->front().Name;
1921 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001922 return make_error<StringError>(
1923 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
1924 PipelineText)
1925 .str(),
1926 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001927
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001928 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1929 DebugLogging))
1930 return Err;
1931 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001932}
1933
1934// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001935Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1936 StringRef PipelineText,
1937 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001938 auto Pipeline = parsePipelineText(PipelineText);
1939 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001940 return make_error<StringError>(
1941 formatv("invalid pipeline '{0}'", PipelineText).str(),
1942 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001943
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001944 if (auto Err =
1945 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1946 return Err;
1947
1948 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001949}
1950
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001951Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00001952 // If the pipeline just consists of the word 'default' just replace the AA
1953 // manager with our default one.
1954 if (PipelineText == "default") {
1955 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001956 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00001957 }
1958
Chandler Carruthedf59962016-02-18 09:45:17 +00001959 while (!PipelineText.empty()) {
1960 StringRef Name;
1961 std::tie(Name, PipelineText) = PipelineText.split(',');
1962 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001963 return make_error<StringError>(
1964 formatv("unknown alias analysis name '{0}'", Name).str(),
1965 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00001966 }
1967
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001968 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00001969}