blob: 9b03d2b1192b842231e3c215bde62feb9065ef8b [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"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000134#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000135#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000136#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000137#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000138#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000139#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000140#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000141#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000142#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000143#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000144#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000145#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000146#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000147#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000148#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000149#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000150#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000151#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000152#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000153#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000154#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000155#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000156#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000157#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000158#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000159#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000160#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000161#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000162#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000163#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000164
Chandler Carruth66445382014-01-11 08:16:35 +0000165using namespace llvm;
166
Chandler Carruth719ffe12017-02-12 05:38:04 +0000167static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
168 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000169static cl::opt<bool>
170 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
171 cl::Hidden, cl::ZeroOrMore,
172 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000173
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000174static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000175 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000176 cl::Hidden, cl::ZeroOrMore,
177 cl::desc("Run NewGVN instead of GVN"));
178
Geoff Berry3cca1da2017-06-10 15:20:03 +0000179static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000180 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
181 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000182
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000183static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000184 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
185 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000186
Davide Italianobe1b6a92017-06-03 23:18:29 +0000187static cl::opt<bool> EnableGVNSink(
188 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
189 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
190
David Green963401d2018-07-01 12:47:30 +0000191static cl::opt<bool> EnableUnrollAndJam(
192 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
193 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
194
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000195static cl::opt<bool> EnableSyntheticCounts(
196 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
197 cl::desc("Run synthetic function entry count generation "
198 "pass"));
199
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000200static Regex DefaultAliasRegex(
201 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000202
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000203static cl::opt<bool>
204 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
205 cl::desc("Enable control height reduction optimization (CHR)"));
206
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000207extern cl::opt<bool> EnableHotColdSplit;
208
Chandler Carruthe3f50642016-12-22 06:59:15 +0000209static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
210 switch (Level) {
211 case PassBuilder::O0:
212 case PassBuilder::O1:
213 case PassBuilder::O2:
214 case PassBuilder::O3:
215 return false;
216
217 case PassBuilder::Os:
218 case PassBuilder::Oz:
219 return true;
220 }
221 llvm_unreachable("Invalid optimization level!");
222}
223
Chandler Carruth66445382014-01-11 08:16:35 +0000224namespace {
225
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000226/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000227struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000228 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000229 return PreservedAnalyses::all();
230 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000231 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000232};
233
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000234/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000235class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
236 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000237 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000238
239public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000240 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000241 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000242 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000243};
244
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000245/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000246struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000247 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
248 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000249 return PreservedAnalyses::all();
250 }
251 static StringRef name() { return "NoOpCGSCCPass"; }
252};
253
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000254/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000255class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
256 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000257 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000258
259public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000260 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000261 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000262 return Result();
263 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000264 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000265};
266
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000267/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000268struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000269 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000270 return PreservedAnalyses::all();
271 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000272 static StringRef name() { return "NoOpFunctionPass"; }
273};
274
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000275/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000276class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
277 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000278 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000279
280public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000281 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000282 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000283 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000284};
285
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000286/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000287struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000288 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
289 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000290 return PreservedAnalyses::all();
291 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000292 static StringRef name() { return "NoOpLoopPass"; }
293};
294
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000295/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000296class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
297 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000298 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000299
300public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000301 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000302 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
303 return Result();
304 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000305 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000306};
307
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000308AnalysisKey NoOpModuleAnalysis::Key;
309AnalysisKey NoOpCGSCCAnalysis::Key;
310AnalysisKey NoOpFunctionAnalysis::Key;
311AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000312
Chandler Carruth66445382014-01-11 08:16:35 +0000313} // End anonymous namespace.
314
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000315void PassBuilder::invokePeepholeEPCallbacks(
316 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
317 for (auto &C : PeepholeEPCallbacks)
318 C(FPM, Level);
319}
320
Chandler Carruth1ff77242015-03-07 09:02:36 +0000321void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000322#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000323 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000324#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000325
326 for (auto &C : ModuleAnalysisRegistrationCallbacks)
327 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000328}
329
Chandler Carruth1ff77242015-03-07 09:02:36 +0000330void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000331#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000332 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000333#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000334
335 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
336 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000337}
338
Chandler Carruth1ff77242015-03-07 09:02:36 +0000339void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000340#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000341 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000342#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000343
344 for (auto &C : FunctionAnalysisRegistrationCallbacks)
345 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000346}
347
Justin Bognereecc3c82016-02-25 07:23:08 +0000348void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000349#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000350 LAM.registerPass([&] { return CREATE_PASS; });
351#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000352
353 for (auto &C : LoopAnalysisRegistrationCallbacks)
354 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000355}
356
Chandler Carruthe3f50642016-12-22 06:59:15 +0000357FunctionPassManager
358PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000359 ThinLTOPhase Phase,
360 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000361 assert(Level != O0 && "Must request optimizations!");
362 FunctionPassManager FPM(DebugLogging);
363
364 // Form SSA out of local memory accesses after breaking apart aggregates into
365 // scalars.
366 FPM.addPass(SROA());
367
368 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000369 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000370
Davide Italianoc3688312017-06-01 23:08:14 +0000371 // Hoisting of scalars and load expressions.
372 if (EnableGVNHoist)
373 FPM.addPass(GVNHoistPass());
374
Davide Italianobe1b6a92017-06-03 23:18:29 +0000375 // Global value numbering based sinking.
376 if (EnableGVNSink) {
377 FPM.addPass(GVNSinkPass());
378 FPM.addPass(SimplifyCFGPass());
379 }
380
Chandler Carruthe3f50642016-12-22 06:59:15 +0000381 // Speculative execution if the target has divergent branches; otherwise nop.
382 FPM.addPass(SpeculativeExecutionPass());
383
384 // Optimize based on known information about branches, and cleanup afterward.
385 FPM.addPass(JumpThreadingPass());
386 FPM.addPass(CorrelatedValuePropagationPass());
387 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000388 if (Level == O3)
389 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000390 FPM.addPass(InstCombinePass());
391
392 if (!isOptimizingForSize(Level))
393 FPM.addPass(LibCallsShrinkWrapPass());
394
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000395 invokePeepholeEPCallbacks(FPM, Level);
396
Rong Xue1f42452017-10-23 22:21:29 +0000397 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
398 // using the size value profile. Don't perform this when optimizing for size.
399 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
400 !isOptimizingForSize(Level))
401 FPM.addPass(PGOMemOPSizeOpt());
402
Chandler Carruthe3f50642016-12-22 06:59:15 +0000403 FPM.addPass(TailCallElimPass());
404 FPM.addPass(SimplifyCFGPass());
405
406 // Form canonically associated expression trees, and simplify the trees using
407 // basic mathematical properties. For example, this will form (nearly)
408 // minimal multiplication trees.
409 FPM.addPass(ReassociatePass());
410
411 // Add the primary loop simplification pipeline.
412 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000413 // some function passes in between them. These can and should be removed
414 // and/or replaced by scheduling the loop pass equivalents in the correct
415 // positions. But those equivalent passes aren't powerful enough yet.
416 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
417 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
418 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
419 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000420 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
421
Chandler Carruth71fd2702018-05-30 02:46:45 +0000422 // Simplify the loop body. We do this initially to clean up after other loop
423 // passes run, either when iterating on a loop or on inner loops with
424 // implications on the outer loop.
425 LPM1.addPass(LoopInstSimplifyPass());
426 LPM1.addPass(LoopSimplifyCFGPass());
427
Chandler Carruthe3f50642016-12-22 06:59:15 +0000428 // Rotate Loop - disable header duplication at -Oz
429 LPM1.addPass(LoopRotatePass(Level != Oz));
430 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000431 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000432 LPM2.addPass(IndVarSimplifyPass());
433 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000434
435 for (auto &C : LateLoopOptimizationsEPCallbacks)
436 C(LPM2, Level);
437
Chandler Carruth79b733b2017-01-26 23:21:17 +0000438 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000439 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000440 // because it changes IR to makes profile annotation in back compile
441 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000442 if (Phase != ThinLTOPhase::PreLink ||
443 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000444 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000445
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000446 for (auto &C : LoopOptimizerEndEPCallbacks)
447 C(LPM2, Level);
448
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000449 // We provide the opt remark emitter pass for LICM to use. We only need to do
450 // this once as it is immutable.
451 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000452 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000453 FPM.addPass(SimplifyCFGPass());
454 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000455 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000456
457 // Eliminate redundancies.
458 if (Level != O1) {
459 // These passes add substantial compile time so skip them at O1.
460 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000461 if (RunNewGVN)
462 FPM.addPass(NewGVNPass());
463 else
464 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000465 }
466
467 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
468 FPM.addPass(MemCpyOptPass());
469
470 // Sparse conditional constant propagation.
471 // FIXME: It isn't clear why we do this *after* loop passes rather than
472 // before...
473 FPM.addPass(SCCPPass());
474
475 // Delete dead bit computations (instcombine runs after to fold away the dead
476 // computations, and then ADCE will run later to exploit any new DCE
477 // opportunities that creates).
478 FPM.addPass(BDCEPass());
479
480 // Run instcombine after redundancy and dead bit elimination to exploit
481 // opportunities opened up by them.
482 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000483 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000484
485 // Re-consider control flow based optimizations after redundancy elimination,
486 // redo DCE, etc.
487 FPM.addPass(JumpThreadingPass());
488 FPM.addPass(CorrelatedValuePropagationPass());
489 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000490 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000491
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000492 for (auto &C : ScalarOptimizerLateEPCallbacks)
493 C(FPM, Level);
494
Chandler Carruthe3f50642016-12-22 06:59:15 +0000495 // Finally, do an expensive DCE pass to catch all the dead code exposed by
496 // the simplifications and basic cleanup after all the simplifications.
497 FPM.addPass(ADCEPass());
498 FPM.addPass(SimplifyCFGPass());
499 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000500 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000501
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000502 if (EnableCHR && Level == O3 && PGOOpt &&
503 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
504 FPM.addPass(ControlHeightReductionPass());
505
Chandler Carruthe3f50642016-12-22 06:59:15 +0000506 return FPM;
507}
508
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000509void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
510 PassBuilder::OptimizationLevel Level,
511 bool RunProfileGen,
512 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000513 std::string ProfileUseFile,
514 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000515 // Generally running simplification passes and the inliner with an high
516 // threshold results in smaller executables, but there may be cases where
517 // the size grows, so let's be conservative here and skip this simplification
518 // at -Os/Oz.
519 if (!isOptimizingForSize(Level)) {
520 InlineParams IP;
521
522 // In the old pass manager, this is a cl::opt. Should still this be one?
523 IP.DefaultThreshold = 75;
524
525 // FIXME: The hint threshold has the same value used by the regular inliner.
526 // This should probably be lowered after performance testing.
527 // FIXME: this comment is cargo culted from the old pass manager, revisit).
528 IP.HintThreshold = 325;
529
530 CGSCCPassManager CGPipeline(DebugLogging);
531
532 CGPipeline.addPass(InlinerPass(IP));
533
534 FunctionPassManager FPM;
535 FPM.addPass(SROA());
536 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
537 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
538 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000539 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000540
Davide Italiano513dfaa2017-02-13 15:26:22 +0000541 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
542
543 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
544 }
545
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000546 // Delete anything that is now dead to make sure that we don't instrument
547 // dead code. Instrumentation can end up keeping dead code around and
548 // dramatically increase code size.
549 MPM.addPass(GlobalDCEPass());
550
Davide Italiano513dfaa2017-02-13 15:26:22 +0000551 if (RunProfileGen) {
552 MPM.addPass(PGOInstrumentationGen());
553
Xinliang David Lib67530e2017-06-25 00:26:43 +0000554 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000555 FPM.addPass(
556 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000557 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
558
Davide Italiano513dfaa2017-02-13 15:26:22 +0000559 // Add the profile lowering pass.
560 InstrProfOptions Options;
561 if (!ProfileGenFile.empty())
562 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000563 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000564 MPM.addPass(InstrProfiling(Options));
565 }
566
567 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000568 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000569}
570
Easwaran Raman8249fac2017-06-28 13:33:49 +0000571static InlineParams
572getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
573 auto O3 = PassBuilder::O3;
574 unsigned OptLevel = Level > O3 ? 2 : Level;
575 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
576 return getInlineParams(OptLevel, SizeLevel);
577}
578
Chandler Carruthe3f50642016-12-22 06:59:15 +0000579ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000580PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000581 ThinLTOPhase Phase,
582 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000583 ModulePassManager MPM(DebugLogging);
584
Chandler Carruthe3f50642016-12-22 06:59:15 +0000585 // Do basic inference of function attributes from known properties of system
586 // libraries and other oracles.
587 MPM.addPass(InferFunctionAttrsPass());
588
589 // Create an early function pass manager to cleanup the output of the
590 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000591 FunctionPassManager EarlyFPM(DebugLogging);
592 EarlyFPM.addPass(SimplifyCFGPass());
593 EarlyFPM.addPass(SROA());
594 EarlyFPM.addPass(EarlyCSEPass());
595 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000596 if (Level == O3)
597 EarlyFPM.addPass(CallSiteSplittingPass());
598
Dehao Chen08f88312017-08-07 20:23:20 +0000599 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
600 // to convert bitcast to direct calls so that they can be inlined during the
601 // profile annotation prepration step.
602 // More details about SamplePGO design can be found in:
603 // https://research.google.com/pubs/pub45290.html
604 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
605 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
606 Phase == ThinLTOPhase::PostLink)
607 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000608 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000609
Dehao Chen08f88312017-08-07 20:23:20 +0000610 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
611 // Annotate sample profile right after early FPM to ensure freshness of
612 // the debug info.
Dehao Chend26dae02017-10-01 05:24:51 +0000613 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000614 PGOOpt->ProfileRemappingFile,
Dehao Chend26dae02017-10-01 05:24:51 +0000615 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000616 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
617 // for the profile annotation to be accurate in the ThinLTO backend.
618 if (Phase != ThinLTOPhase::PreLink)
619 // We perform early indirect call promotion here, before globalopt.
620 // This is important for the ThinLTO backend phase because otherwise
621 // imported available_externally functions look unreferenced and are
622 // removed.
623 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
624 true));
625 }
626
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000627 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000628 // and prior to optimizing globals.
629 // FIXME: This position in the pipeline hasn't been carefully considered in
630 // years, it should be re-analyzed.
631 MPM.addPass(IPSCCPPass());
632
Matthew Simpsoncb585582017-10-25 13:40:08 +0000633 // Attach metadata to indirect call sites indicating the set of functions
634 // they may target at run-time. This should follow IPSCCP.
635 MPM.addPass(CalledValuePropagationPass());
636
Chandler Carruthe3f50642016-12-22 06:59:15 +0000637 // Optimize globals to try and fold them into constants.
638 MPM.addPass(GlobalOptPass());
639
640 // Promote any localized globals to SSA registers.
641 // FIXME: Should this instead by a run of SROA?
642 // FIXME: We should probably run instcombine and simplify-cfg afterward to
643 // delete control flows that are dead once globals have been folded to
644 // constants.
645 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
646
647 // Remove any dead arguments exposed by cleanups and constand folding
648 // globals.
649 MPM.addPass(DeadArgumentEliminationPass());
650
651 // Create a small function pass pipeline to cleanup after all the global
652 // optimizations.
653 FunctionPassManager GlobalCleanupPM(DebugLogging);
654 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000655 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
656
Chandler Carruthe3f50642016-12-22 06:59:15 +0000657 GlobalCleanupPM.addPass(SimplifyCFGPass());
658 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
659
Dehao Chen89d32262017-08-02 01:28:31 +0000660 // Add all the requested passes for instrumentation PGO, if requested.
661 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
662 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
663 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000664 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
665 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000666 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000667 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000668
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000669 // Synthesize function entry counts for non-PGO compilation.
670 if (EnableSyntheticCounts && !PGOOpt)
671 MPM.addPass(SyntheticCountsPropagation());
672
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000673 // Require the GlobalsAA analysis for the module so we can query it within
674 // the CGSCC pipeline.
675 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000676
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000677 // Require the ProfileSummaryAnalysis for the module so we can query it within
678 // the inliner pass.
679 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
680
Chandler Carruthe3f50642016-12-22 06:59:15 +0000681 // Now begin the main postorder CGSCC pipeline.
682 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
683 // manager and trying to emulate its precise behavior. Much of this doesn't
684 // make a lot of sense and we should revisit the core CGSCC structure.
685 CGSCCPassManager MainCGPipeline(DebugLogging);
686
687 // Note: historically, the PruneEH pass was run first to deduce nounwind and
688 // generally clean up exception handling overhead. It isn't clear this is
689 // valuable as the inliner doesn't currently care whether it is inlining an
690 // invoke or a call.
691
692 // Run the inliner first. The theory is that we are walking bottom-up and so
693 // the callees have already been fully optimized, and we want to inline them
694 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000695 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000696 // because it makes profile annotation in the backend inaccurate.
697 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000698 if (Phase == ThinLTOPhase::PreLink &&
699 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000700 IP.HotCallSiteThreshold = 0;
701 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000702
703 // Now deduce any function attributes based in the current code.
704 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
705
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000706 // When at O3 add argument promotion to the pass pipeline.
707 // FIXME: It isn't at all clear why this should be limited to O3.
708 if (Level == O3)
709 MainCGPipeline.addPass(ArgumentPromotionPass());
710
Chandler Carruthe3f50642016-12-22 06:59:15 +0000711 // Lastly, add the core function simplification pipeline nested inside the
712 // CGSCC walk.
713 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000714 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000715
Teresa Johnsond7253352018-10-23 22:57:40 +0000716 // We only want to do hot cold splitting once for ThinLTO, during the
717 // post-link ThinLTO.
718 if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink)
Aditya Kumard9e2e382018-10-21 18:11:56 +0000719 MPM.addPass(HotColdSplittingPass());
720
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000721 for (auto &C : CGSCCOptimizerLateEPCallbacks)
722 C(MainCGPipeline, Level);
723
Chandler Carruth719ffe12017-02-12 05:38:04 +0000724 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
725 // to detect when we devirtualize indirect calls and iterate the SCC passes
726 // in that case to try and catch knock-on inlining or function attrs
727 // opportunities. Then we add it to the module pipeline by walking the SCCs
728 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000729 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000730 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000731 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000732
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000733 return MPM;
734}
735
736ModulePassManager
737PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
738 bool DebugLogging) {
739 ModulePassManager MPM(DebugLogging);
740
741 // Optimize globals now that the module is fully simplified.
742 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000743 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000744
Xinliang David Li126157c2017-05-22 16:41:57 +0000745 // Run partial inlining pass to partially inline functions that have
746 // large bodies.
747 if (RunPartialInlining)
748 MPM.addPass(PartialInlinerPass());
749
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000750 // Remove avail extern fns and globals definitions since we aren't compiling
751 // an object file for later LTO. For LTO we want to preserve these so they
752 // are eligible for inlining at link-time. Note if they are unreferenced they
753 // will be removed by GlobalDCE later, so this only impacts referenced
754 // available externally globals. Eventually they will be suppressed during
755 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
756 // may make globals referenced by available external functions dead and saves
757 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000758 MPM.addPass(EliminateAvailableExternallyPass());
759
760 // Do RPO function attribute inference across the module to forward-propagate
761 // attributes where applicable.
762 // FIXME: Is this really an optimization rather than a canonicalization?
763 MPM.addPass(ReversePostOrderFunctionAttrsPass());
764
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000765 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000766 // useful as the above will have inlined, DCE'ed, and function-attr
767 // propagated everything. We should at this point have a reasonably minimal
768 // and richly annotated call graph. By computing aliasing and mod/ref
769 // information for all local globals here, the late loop passes and notably
770 // the vectorizer will be able to use them to help recognize vectorizable
771 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000772 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000773
774 FunctionPassManager OptimizePM(DebugLogging);
775 OptimizePM.addPass(Float2IntPass());
776 // FIXME: We need to run some loop optimizations to re-rotate loops after
777 // simplify-cfg and others undo their rotation.
778
779 // Optimize the loop execution. These passes operate on entire loop nests
780 // rather than on each loop in an inside-out manner, and so they are actually
781 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000782
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000783 for (auto &C : VectorizerStartEPCallbacks)
784 C(OptimizePM, Level);
785
Chandler Carrutha95ff382017-01-27 00:50:21 +0000786 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000787 OptimizePM.addPass(
788 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000789
790 // Distribute loops to allow partial vectorization. I.e. isolate dependences
791 // into separate loop that would otherwise inhibit vectorization. This is
792 // currently only performed for loops marked with the metadata
793 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000794 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000795
796 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000797 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000798
Chandler Carruthbaabda92017-01-27 01:32:26 +0000799 // Eliminate loads by forwarding stores from the previous iteration to loads
800 // of the current iteration.
801 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000802
803 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000804 OptimizePM.addPass(InstCombinePass());
805
Chandler Carrutha95ff382017-01-27 00:50:21 +0000806 // Now that we've formed fast to execute loop structures, we do further
807 // optimizations. These are run afterward as they might block doing complex
808 // analyses and transforms such as what are needed for loop vectorization.
809
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000810 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
811 // GVN, loop transforms, and others have already run, so it's now better to
812 // convert to more optimized IR using more aggressive simplify CFG options.
813 // The extra sinking transform can create larger basic blocks, so do this
814 // before SLP vectorization.
815 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
816 forwardSwitchCondToPhi(true).
817 convertSwitchToLookupTable(true).
818 needCanonicalLoops(false).
819 sinkCommonInsts(true)));
820
Chandler Carruthe3f50642016-12-22 06:59:15 +0000821 // Optimize parallel scalar instruction chains into SIMD instructions.
822 OptimizePM.addPass(SLPVectorizerPass());
823
Chandler Carruthe3f50642016-12-22 06:59:15 +0000824 OptimizePM.addPass(InstCombinePass());
825
826 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000827 // execution resources of an out-of-order processor. We also then need to
828 // clean up redundancies and loop invariant code.
829 // FIXME: It would be really good to use a loop-integrated instruction
830 // combiner for cleanup here so that the unrolling and LICM can be pipelined
831 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000832 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
833 if (EnableUnrollAndJam) {
834 OptimizePM.addPass(
835 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
836 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000837 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000838 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000839 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000840 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000841
842 // Now that we've vectorized and unrolled loops, we may have more refined
843 // alignment information, try to re-derive it here.
844 OptimizePM.addPass(AlignmentFromAssumptionsPass());
845
Chandler Carrutha95ff382017-01-27 00:50:21 +0000846 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
847 // canonicalization pass that enables other optimizations. As a result,
848 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
849 // result too early.
850 OptimizePM.addPass(LoopSinkPass());
851
852 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000853 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000854
Sanjay Patel6fd43912017-09-09 13:38:18 +0000855 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
856 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
857 // flattening of blocks.
858 OptimizePM.addPass(DivRemPairsPass());
859
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000860 // LoopSink (and other loop passes since the last simplifyCFG) might have
861 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
862 OptimizePM.addPass(SimplifyCFGPass());
863
Chandler Carruthc34f7892017-11-28 11:32:31 +0000864 // Optimize PHIs by speculating around them when profitable. Note that this
865 // pass needs to be run after any PRE or similar pass as it is essentially
866 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
867 OptimizePM.addPass(SpeculateAroundPHIsPass());
868
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000869 for (auto &C : OptimizerLastEPCallbacks)
870 C(OptimizePM, Level);
871
Chandler Carrutha95ff382017-01-27 00:50:21 +0000872 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000873 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
874
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000875 MPM.addPass(CGProfilePass());
876
Chandler Carruthe3f50642016-12-22 06:59:15 +0000877 // Now we need to do some global optimization transforms.
878 // FIXME: It would seem like these should come first in the optimization
879 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
880 // ordering here.
881 MPM.addPass(GlobalDCEPass());
882 MPM.addPass(ConstantMergePass());
883
884 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000885}
886
Chandler Carruthe3f50642016-12-22 06:59:15 +0000887ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000888PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
889 bool DebugLogging) {
890 assert(Level != O0 && "Must request optimizations for the default pipeline!");
891
892 ModulePassManager MPM(DebugLogging);
893
894 // Force any function attributes we want the rest of the pipeline to observe.
895 MPM.addPass(ForceFunctionAttrsPass());
896
David Blaikie0c64f5a2018-01-23 01:25:20 +0000897 // Apply module pipeline start EP callback.
898 for (auto &C : PipelineStartEPCallbacks)
899 C(MPM);
900
Dehao Chen08f88312017-08-07 20:23:20 +0000901 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000902 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
903
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000904 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000905 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
906 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000907
908 // Now add the optimization pipeline.
909 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
910
911 return MPM;
912}
913
914ModulePassManager
915PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
916 bool DebugLogging) {
917 assert(Level != O0 && "Must request optimizations for the default pipeline!");
918
919 ModulePassManager MPM(DebugLogging);
920
921 // Force any function attributes we want the rest of the pipeline to observe.
922 MPM.addPass(ForceFunctionAttrsPass());
923
Dehao Chen08f88312017-08-07 20:23:20 +0000924 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000925 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
926
David Blaikie0c64f5a2018-01-23 01:25:20 +0000927 // Apply module pipeline start EP callback.
928 for (auto &C : PipelineStartEPCallbacks)
929 C(MPM);
930
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000931 // If we are planning to perform ThinLTO later, we don't bloat the code with
932 // unrolling/vectorization/... now. Just simplify the module as much as we
933 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000934 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
935 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000936
937 // Run partial inlining pass to partially inline functions that have
938 // large bodies.
939 // FIXME: It isn't clear whether this is really the right place to run this
940 // in ThinLTO. Because there is another canonicalization and simplification
941 // phase that will run after the thin link, running this here ends up with
942 // less information than will be available later and it may grow functions in
943 // ways that aren't beneficial.
944 if (RunPartialInlining)
945 MPM.addPass(PartialInlinerPass());
946
947 // Reduce the size of the IR as much as possible.
948 MPM.addPass(GlobalOptPass());
949
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000950 return MPM;
951}
952
Teresa Johnson28023db2018-07-19 14:51:32 +0000953ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
954 OptimizationLevel Level, bool DebugLogging,
955 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000956 ModulePassManager MPM(DebugLogging);
957
Teresa Johnson28023db2018-07-19 14:51:32 +0000958 if (ImportSummary) {
959 // These passes import type identifier resolutions for whole-program
960 // devirtualization and CFI. They must run early because other passes may
961 // disturb the specific instruction patterns that these passes look for,
962 // creating dependencies on resolutions that may not appear in the summary.
963 //
964 // For example, GVN may transform the pattern assume(type.test) appearing in
965 // two basic blocks into assume(phi(type.test, type.test)), which would
966 // transform a dependency on a WPD resolution into a dependency on a type
967 // identifier resolution for CFI.
968 //
969 // Also, WPD has access to more precise information than ICP and can
970 // devirtualize more effectively, so it should operate on the IR first.
971 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
972 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
973 }
974
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000975 // Force any function attributes we want the rest of the pipeline to observe.
976 MPM.addPass(ForceFunctionAttrsPass());
977
978 // During the ThinLTO backend phase we perform early indirect call promotion
979 // here, before globalopt. Otherwise imported available_externally functions
980 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000981 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
982 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000983 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000984 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
985 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000986
987 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000988 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
989 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000990
991 // Now add the optimization pipeline.
992 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
993
994 return MPM;
995}
996
997ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +0000998PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
999 bool DebugLogging) {
1000 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001001 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +00001002 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001003}
1004
Teresa Johnson28023db2018-07-19 14:51:32 +00001005ModulePassManager
1006PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1007 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001008 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1009 ModulePassManager MPM(DebugLogging);
1010
Xin Tong642c8d32018-11-15 18:06:42 +00001011 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1012 // Load sample profile before running the LTO optimization pipeline.
1013 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1014 PGOOpt->ProfileRemappingFile,
1015 false /* ThinLTOPhase::PreLink */));
1016 }
1017
Davide Italiano089a9122017-01-24 00:57:39 +00001018 // Remove unused virtual tables to improve the quality of code generated by
1019 // whole-program devirtualization and bitset lowering.
1020 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001021
Davide Italiano089a9122017-01-24 00:57:39 +00001022 // Force any function attributes we want the rest of the pipeline to observe.
1023 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001024
Davide Italiano089a9122017-01-24 00:57:39 +00001025 // Do basic inference of function attributes from known properties of system
1026 // libraries and other oracles.
1027 MPM.addPass(InferFunctionAttrsPass());
1028
1029 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001030 FunctionPassManager EarlyFPM(DebugLogging);
1031 EarlyFPM.addPass(CallSiteSplittingPass());
1032 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1033
Davide Italiano089a9122017-01-24 00:57:39 +00001034 // Indirect call promotion. This should promote all the targets that are
1035 // left by the earlier promotion pass that promotes intra-module targets.
1036 // This two-step promotion is to save the compile time. For LTO, it should
1037 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001038 MPM.addPass(PGOIndirectCallPromotion(
1039 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001040 // Propagate constants at call sites into the functions they call. This
1041 // opens opportunities for globalopt (and inlining) by substituting function
1042 // pointers passed as arguments to direct uses of functions.
1043 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001044
1045 // Attach metadata to indirect call sites indicating the set of functions
1046 // they may target at run-time. This should follow IPSCCP.
1047 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001048 }
1049
1050 // Now deduce any function attributes based in the current code.
1051 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1052 PostOrderFunctionAttrsPass()));
1053
1054 // Do RPO function attribute inference across the module to forward-propagate
1055 // attributes where applicable.
1056 // FIXME: Is this really an optimization rather than a canonicalization?
1057 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1058
1059 // Use inragne annotations on GEP indices to split globals where beneficial.
1060 MPM.addPass(GlobalSplitPass());
1061
1062 // Run whole program optimization of virtual call when the list of callees
1063 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001064 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001065
1066 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001067 if (Level == 1) {
1068 // The LowerTypeTestsPass needs to run to lower type metadata and the
1069 // type.test intrinsics. The pass does nothing if CFI is disabled.
1070 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001071 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001072 }
Davide Italiano089a9122017-01-24 00:57:39 +00001073
1074 // Optimize globals to try and fold them into constants.
1075 MPM.addPass(GlobalOptPass());
1076
1077 // Promote any localized globals to SSA registers.
1078 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1079
1080 // Linking modules together can lead to duplicate global constant, only
1081 // keep one copy of each constant.
1082 MPM.addPass(ConstantMergePass());
1083
1084 // Remove unused arguments from functions.
1085 MPM.addPass(DeadArgumentEliminationPass());
1086
1087 // Reduce the code after globalopt and ipsccp. Both can open up significant
1088 // simplification opportunities, and both can propagate functions through
1089 // function pointers. When this happens, we often have to resolve varargs
1090 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001091 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001092 if (Level == O3)
1093 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001094 PeepholeFPM.addPass(InstCombinePass());
1095 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1096
1097 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001098
1099 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1100 // generally clean up exception handling overhead. It isn't clear this is
1101 // valuable as the inliner doesn't currently care whether it is inlining an
1102 // invoke or a call.
1103 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001104 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1105 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001106
1107 // Optimize globals again after we ran the inliner.
1108 MPM.addPass(GlobalOptPass());
1109
1110 // Garbage collect dead functions.
1111 // FIXME: Add ArgumentPromotion pass after once it's ported.
1112 MPM.addPass(GlobalDCEPass());
1113
1114 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001115 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001116 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001117 invokePeepholeEPCallbacks(FPM, Level);
1118
Davide Italiano089a9122017-01-24 00:57:39 +00001119 FPM.addPass(JumpThreadingPass());
1120
1121 // Break up allocas
1122 FPM.addPass(SROA());
1123
1124 // Run a few AA driver optimizations here and now to cleanup the code.
1125 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1126
1127 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1128 PostOrderFunctionAttrsPass()));
1129 // FIXME: here we run IP alias analysis in the legacy PM.
1130
1131 FunctionPassManager MainFPM;
1132
1133 // FIXME: once we fix LoopPass Manager, add LICM here.
1134 // FIXME: once we provide support for enabling MLSM, add it here.
1135 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001136 if (RunNewGVN)
1137 MainFPM.addPass(NewGVNPass());
1138 else
1139 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001140
1141 // Remove dead memcpy()'s.
1142 MainFPM.addPass(MemCpyOptPass());
1143
1144 // Nuke dead stores.
1145 MainFPM.addPass(DSEPass());
1146
1147 // FIXME: at this point, we run a bunch of loop passes:
1148 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1149 // loopVectorize. Enable them once the remaining issue with LPM
1150 // are sorted out.
1151
1152 MainFPM.addPass(InstCombinePass());
1153 MainFPM.addPass(SimplifyCFGPass());
1154 MainFPM.addPass(SCCPPass());
1155 MainFPM.addPass(InstCombinePass());
1156 MainFPM.addPass(BDCEPass());
1157
1158 // FIXME: We may want to run SLPVectorizer here.
1159 // After vectorization, assume intrinsics may tell us more
1160 // about pointer alignments.
1161#if 0
1162 MainFPM.add(AlignmentFromAssumptionsPass());
1163#endif
1164
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001165 // FIXME: Conditionally run LoadCombine here, after it's ported
1166 // (in case we still have this pass, given its questionable usefulness).
1167
Davide Italiano089a9122017-01-24 00:57:39 +00001168 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001169 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001170 MainFPM.addPass(JumpThreadingPass());
1171 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1172
1173 // Create a function that performs CFI checks for cross-DSO calls with
1174 // targets in the current module.
1175 MPM.addPass(CrossDSOCFIPass());
1176
1177 // Lower type metadata and the type.test intrinsic. This pass supports
1178 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1179 // to be run at link time if CFI is enabled. This pass does nothing if
1180 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001181 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001182
1183 // Add late LTO optimization passes.
1184 // Delete basic blocks, which optimization passes may have killed.
1185 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1186
1187 // Drop bodies of available eternally objects to improve GlobalDCE.
1188 MPM.addPass(EliminateAvailableExternallyPass());
1189
1190 // Now that we have optimized the program, discard unreachable functions.
1191 MPM.addPass(GlobalDCEPass());
1192
1193 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001194 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001195}
1196
Chandler Carruth060ad612016-12-23 20:38:19 +00001197AAManager PassBuilder::buildDefaultAAPipeline() {
1198 AAManager AA;
1199
1200 // The order in which these are registered determines their priority when
1201 // being queried.
1202
1203 // First we register the basic alias analysis that provides the majority of
1204 // per-function local AA logic. This is a stateless, on-demand local set of
1205 // AA techniques.
1206 AA.registerFunctionAnalysis<BasicAA>();
1207
1208 // Next we query fast, specialized alias analyses that wrap IR-embedded
1209 // information about aliasing.
1210 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1211 AA.registerFunctionAnalysis<TypeBasedAA>();
1212
1213 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001214 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1215 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001216 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001217 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001218
1219 return AA;
1220}
1221
Chandler Carruth241bf242016-08-03 07:44:48 +00001222static Optional<int> parseRepeatPassName(StringRef Name) {
1223 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1224 return None;
1225 int Count;
1226 if (Name.getAsInteger(0, Count) || Count <= 0)
1227 return None;
1228 return Count;
1229}
1230
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001231static Optional<int> parseDevirtPassName(StringRef Name) {
1232 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1233 return None;
1234 int Count;
1235 if (Name.getAsInteger(0, Count) || Count <= 0)
1236 return None;
1237 return Count;
1238}
1239
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001240/// Tests whether a pass name starts with a valid prefix for a default pipeline
1241/// alias.
1242static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1243 return Name.startswith("default") || Name.startswith("thinlto") ||
1244 Name.startswith("lto");
1245}
1246
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001247/// Tests whether registered callbacks will accept a given pass name.
1248///
1249/// When parsing a pipeline text, the type of the outermost pipeline may be
1250/// omitted, in which case the type is automatically determined from the first
1251/// pass name in the text. This may be a name that is handled through one of the
1252/// callbacks. We check this through the oridinary parsing callbacks by setting
1253/// up a dummy PassManager in order to not force the client to also handle this
1254/// type of query.
1255template <typename PassManagerT, typename CallbacksT>
1256static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1257 if (!Callbacks.empty()) {
1258 PassManagerT DummyPM;
1259 for (auto &CB : Callbacks)
1260 if (CB(Name, DummyPM, {}))
1261 return true;
1262 }
1263 return false;
1264}
1265
1266template <typename CallbacksT>
1267static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001268 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001269 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001270 return DefaultAliasRegex.match(Name);
1271
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001272 // Explicitly handle pass manager names.
1273 if (Name == "module")
1274 return true;
1275 if (Name == "cgscc")
1276 return true;
1277 if (Name == "function")
1278 return true;
1279
Chandler Carruth241bf242016-08-03 07:44:48 +00001280 // Explicitly handle custom-parsed pass names.
1281 if (parseRepeatPassName(Name))
1282 return true;
1283
Chandler Carruth74a8a222016-06-17 07:15:29 +00001284#define MODULE_PASS(NAME, CREATE_PASS) \
1285 if (Name == NAME) \
1286 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001287#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001288 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001289 return true;
1290#include "PassRegistry.def"
1291
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001292 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001293}
1294
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001295template <typename CallbacksT>
1296static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001297 // Explicitly handle pass manager names.
1298 if (Name == "cgscc")
1299 return true;
1300 if (Name == "function")
1301 return true;
1302
Chandler Carruth241bf242016-08-03 07:44:48 +00001303 // Explicitly handle custom-parsed pass names.
1304 if (parseRepeatPassName(Name))
1305 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001306 if (parseDevirtPassName(Name))
1307 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001308
Chandler Carruth74a8a222016-06-17 07:15:29 +00001309#define CGSCC_PASS(NAME, CREATE_PASS) \
1310 if (Name == NAME) \
1311 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001312#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001313 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001314 return true;
1315#include "PassRegistry.def"
1316
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001317 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001318}
1319
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001320template <typename CallbacksT>
1321static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001322 // Explicitly handle pass manager names.
1323 if (Name == "function")
1324 return true;
1325 if (Name == "loop")
1326 return true;
1327
Chandler Carruth241bf242016-08-03 07:44:48 +00001328 // Explicitly handle custom-parsed pass names.
1329 if (parseRepeatPassName(Name))
1330 return true;
1331
Chandler Carruth74a8a222016-06-17 07:15:29 +00001332#define FUNCTION_PASS(NAME, CREATE_PASS) \
1333 if (Name == NAME) \
1334 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001335#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001336 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001337 return true;
1338#include "PassRegistry.def"
1339
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001340 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001341}
1342
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001343template <typename CallbacksT>
1344static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001345 // Explicitly handle pass manager names.
1346 if (Name == "loop")
1347 return true;
1348
Chandler Carruth241bf242016-08-03 07:44:48 +00001349 // Explicitly handle custom-parsed pass names.
1350 if (parseRepeatPassName(Name))
1351 return true;
1352
Chandler Carruth74a8a222016-06-17 07:15:29 +00001353#define LOOP_PASS(NAME, CREATE_PASS) \
1354 if (Name == NAME) \
1355 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001356#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1357 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1358 return true;
1359#include "PassRegistry.def"
1360
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001361 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001362}
1363
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001364Optional<std::vector<PassBuilder::PipelineElement>>
1365PassBuilder::parsePipelineText(StringRef Text) {
1366 std::vector<PipelineElement> ResultPipeline;
1367
1368 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1369 &ResultPipeline};
1370 for (;;) {
1371 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1372 size_t Pos = Text.find_first_of(",()");
1373 Pipeline.push_back({Text.substr(0, Pos), {}});
1374
1375 // If we have a single terminating name, we're done.
1376 if (Pos == Text.npos)
1377 break;
1378
1379 char Sep = Text[Pos];
1380 Text = Text.substr(Pos + 1);
1381 if (Sep == ',')
1382 // Just a name ending in a comma, continue.
1383 continue;
1384
1385 if (Sep == '(') {
1386 // Push the inner pipeline onto the stack to continue processing.
1387 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1388 continue;
1389 }
1390
1391 assert(Sep == ')' && "Bogus separator!");
1392 // When handling the close parenthesis, we greedily consume them to avoid
1393 // empty strings in the pipeline.
1394 do {
1395 // If we try to pop the outer pipeline we have unbalanced parentheses.
1396 if (PipelineStack.size() == 1)
1397 return None;
1398
1399 PipelineStack.pop_back();
1400 } while (Text.consume_front(")"));
1401
1402 // Check if we've finished parsing.
1403 if (Text.empty())
1404 break;
1405
1406 // Otherwise, the end of an inner pipeline always has to be followed by
1407 // a comma, and then we can continue.
1408 if (!Text.consume_front(","))
1409 return None;
1410 }
1411
1412 if (PipelineStack.size() > 1)
1413 // Unbalanced paretheses.
1414 return None;
1415
1416 assert(PipelineStack.back() == &ResultPipeline &&
1417 "Wrong pipeline at the bottom of the stack!");
1418 return {std::move(ResultPipeline)};
1419}
1420
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001421Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1422 const PipelineElement &E,
1423 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001424 auto &Name = E.Name;
1425 auto &InnerPipeline = E.InnerPipeline;
1426
1427 // First handle complex passes like the pass managers which carry pipelines.
1428 if (!InnerPipeline.empty()) {
1429 if (Name == "module") {
1430 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001431 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1432 VerifyEachPass, DebugLogging))
1433 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001434 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001435 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001436 }
1437 if (Name == "cgscc") {
1438 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001439 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1440 DebugLogging))
1441 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001442 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001443 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001444 }
1445 if (Name == "function") {
1446 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001447 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1448 VerifyEachPass, DebugLogging))
1449 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001450 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001451 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001452 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001453 if (auto Count = parseRepeatPassName(Name)) {
1454 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001455 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1456 VerifyEachPass, DebugLogging))
1457 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001458 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001459 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001460 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001461
1462 for (auto &C : ModulePipelineParsingCallbacks)
1463 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001464 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001465
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001466 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001467 return make_error<StringError>(
1468 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1469 inconvertibleErrorCode());
1470 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001471 }
1472
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001473 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001474 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001475 SmallVector<StringRef, 3> Matches;
1476 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001477 return make_error<StringError>(
1478 formatv("unknown default pipeline alias '{0}'", Name).str(),
1479 inconvertibleErrorCode());
1480
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001481 assert(Matches.size() == 3 && "Must capture two matched strings!");
1482
Jordan Rosef85a95f2016-07-25 18:34:51 +00001483 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001484 .Case("O0", O0)
1485 .Case("O1", O1)
1486 .Case("O2", O2)
1487 .Case("O3", O3)
1488 .Case("Os", Os)
1489 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001490 if (L == O0)
1491 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001492 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001493
1494 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001495 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001496 } else if (Matches[1] == "thinlto-pre-link") {
1497 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1498 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001499 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001500 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001501 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001502 } else {
1503 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001504 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001505 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001506 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001507 }
1508
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001509 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001510#define MODULE_PASS(NAME, CREATE_PASS) \
1511 if (Name == NAME) { \
1512 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001513 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001514 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001515#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1516 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001517 MPM.addPass( \
1518 RequireAnalysisPass< \
1519 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001520 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001521 } \
1522 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001523 MPM.addPass(InvalidateAnalysisPass< \
1524 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001525 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001526 }
1527#include "PassRegistry.def"
1528
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001529 for (auto &C : ModulePipelineParsingCallbacks)
1530 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001531 return Error::success();
1532 return make_error<StringError>(
1533 formatv("unknown module pass '{0}'", Name).str(),
1534 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001535}
1536
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001537Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1538 const PipelineElement &E, bool VerifyEachPass,
1539 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001540 auto &Name = E.Name;
1541 auto &InnerPipeline = E.InnerPipeline;
1542
1543 // First handle complex passes like the pass managers which carry pipelines.
1544 if (!InnerPipeline.empty()) {
1545 if (Name == "cgscc") {
1546 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001547 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1548 VerifyEachPass, DebugLogging))
1549 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001550 // Add the nested pass manager with the appropriate adaptor.
1551 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001552 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001553 }
1554 if (Name == "function") {
1555 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001556 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1557 VerifyEachPass, DebugLogging))
1558 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001559 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001560 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001561 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001562 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001563 if (auto Count = parseRepeatPassName(Name)) {
1564 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001565 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1566 VerifyEachPass, DebugLogging))
1567 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001568 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001569 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001570 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001571 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1572 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001573 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1574 VerifyEachPass, DebugLogging))
1575 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001576 CGPM.addPass(
1577 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001578 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001579 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001580
1581 for (auto &C : CGSCCPipelineParsingCallbacks)
1582 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001583 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001584
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001585 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001586 return make_error<StringError>(
1587 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1588 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001589 }
1590
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001591// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001592#define CGSCC_PASS(NAME, CREATE_PASS) \
1593 if (Name == NAME) { \
1594 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001595 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001596 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001597#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1598 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001599 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001600 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001601 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1602 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001603 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001604 } \
1605 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001606 CGPM.addPass(InvalidateAnalysisPass< \
1607 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001608 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001609 }
1610#include "PassRegistry.def"
1611
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001612 for (auto &C : CGSCCPipelineParsingCallbacks)
1613 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001614 return Error::success();
1615 return make_error<StringError>(
1616 formatv("unknown cgscc pass '{0}'", Name).str(),
1617 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001618}
1619
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001620Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1621 const PipelineElement &E,
1622 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001623 auto &Name = E.Name;
1624 auto &InnerPipeline = E.InnerPipeline;
1625
1626 // First handle complex passes like the pass managers which carry pipelines.
1627 if (!InnerPipeline.empty()) {
1628 if (Name == "function") {
1629 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001630 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1631 VerifyEachPass, DebugLogging))
1632 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001633 // Add the nested pass manager with the appropriate adaptor.
1634 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001635 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001636 }
1637 if (Name == "loop") {
1638 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001639 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1640 DebugLogging))
1641 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001642 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001643 FPM.addPass(
1644 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001645 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001646 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001647 if (auto Count = parseRepeatPassName(Name)) {
1648 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001649 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1650 VerifyEachPass, DebugLogging))
1651 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001652 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001653 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001654 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001655
1656 for (auto &C : FunctionPipelineParsingCallbacks)
1657 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001658 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001659
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001660 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001661 return make_error<StringError>(
1662 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1663 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001664 }
1665
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001666// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001667#define FUNCTION_PASS(NAME, CREATE_PASS) \
1668 if (Name == NAME) { \
1669 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001670 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001671 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001672#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1673 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001674 FPM.addPass( \
1675 RequireAnalysisPass< \
1676 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001677 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001678 } \
1679 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001680 FPM.addPass(InvalidateAnalysisPass< \
1681 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001682 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001683 }
1684#include "PassRegistry.def"
1685
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001686 for (auto &C : FunctionPipelineParsingCallbacks)
1687 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001688 return Error::success();
1689 return make_error<StringError>(
1690 formatv("unknown function pass '{0}'", Name).str(),
1691 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001692}
1693
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001694Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1695 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001696 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001697 auto &InnerPipeline = E.InnerPipeline;
1698
1699 // First handle complex passes like the pass managers which carry pipelines.
1700 if (!InnerPipeline.empty()) {
1701 if (Name == "loop") {
1702 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001703 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1704 VerifyEachPass, DebugLogging))
1705 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001706 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001707 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001708 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001709 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001710 if (auto Count = parseRepeatPassName(Name)) {
1711 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001712 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1713 VerifyEachPass, DebugLogging))
1714 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001715 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001716 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001717 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001718
1719 for (auto &C : LoopPipelineParsingCallbacks)
1720 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001721 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001722
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001723 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001724 return make_error<StringError>(
1725 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1726 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001727 }
1728
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001729// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001730#define LOOP_PASS(NAME, CREATE_PASS) \
1731 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001732 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001733 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001734 }
1735#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1736 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001737 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001738 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1739 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1740 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001741 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001742 } \
1743 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001744 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001745 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001746 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001747 }
1748#include "PassRegistry.def"
1749
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001750 for (auto &C : LoopPipelineParsingCallbacks)
1751 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001752 return Error::success();
1753 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1754 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001755}
1756
Chandler Carruthedf59962016-02-18 09:45:17 +00001757bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001758#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1759 if (Name == NAME) { \
1760 AA.registerModuleAnalysis< \
1761 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1762 return true; \
1763 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001764#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1765 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001766 AA.registerFunctionAnalysis< \
1767 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001768 return true; \
1769 }
1770#include "PassRegistry.def"
1771
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001772 for (auto &C : AAParsingCallbacks)
1773 if (C(Name, AA))
1774 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001775 return false;
1776}
1777
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001778Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001779 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001780 bool VerifyEachPass,
1781 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001782 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001783 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1784 return Err;
1785 // FIXME: No verifier support for Loop passes!
1786 }
1787 return Error::success();
1788}
1789
1790Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1791 ArrayRef<PipelineElement> Pipeline,
1792 bool VerifyEachPass,
1793 bool DebugLogging) {
1794 for (const auto &Element : Pipeline) {
1795 if (auto Err =
1796 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1797 return Err;
1798 if (VerifyEachPass)
1799 FPM.addPass(VerifierPass());
1800 }
1801 return Error::success();
1802}
1803
1804Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1805 ArrayRef<PipelineElement> Pipeline,
1806 bool VerifyEachPass,
1807 bool DebugLogging) {
1808 for (const auto &Element : Pipeline) {
1809 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1810 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001811 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001812 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001813 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001814}
1815
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001816void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1817 FunctionAnalysisManager &FAM,
1818 CGSCCAnalysisManager &CGAM,
1819 ModuleAnalysisManager &MAM) {
1820 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1821 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001822 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1823 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1824 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1825 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1826 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1827}
1828
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001829Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1830 ArrayRef<PipelineElement> Pipeline,
1831 bool VerifyEachPass,
1832 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001833 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001834 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1835 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001836 if (VerifyEachPass)
1837 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001838 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001839 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001840}
1841
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001842// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001843// FIXME: Should this routine accept a TargetMachine or require the caller to
1844// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001845Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1846 StringRef PipelineText,
1847 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001848 auto Pipeline = parsePipelineText(PipelineText);
1849 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001850 return make_error<StringError>(
1851 formatv("invalid pipeline '{0}'", PipelineText).str(),
1852 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001853
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001854 // If the first name isn't at the module layer, wrap the pipeline up
1855 // automatically.
1856 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001857
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001858 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1859 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001860 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001861 } else if (isFunctionPassName(FirstName,
1862 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001863 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001864 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001865 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001866 } else {
1867 for (auto &C : TopLevelPipelineParsingCallbacks)
1868 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001869 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001870
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001871 // Unknown pass or pipeline name!
1872 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1873 return make_error<StringError>(
1874 formatv("unknown {0} name '{1}'",
1875 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1876 .str(),
1877 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001878 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001879 }
1880
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001881 if (auto Err =
1882 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1883 return Err;
1884 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001885}
Chandler Carruthedf59962016-02-18 09:45:17 +00001886
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001887// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001888Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1889 StringRef PipelineText,
1890 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001891 auto Pipeline = parsePipelineText(PipelineText);
1892 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001893 return make_error<StringError>(
1894 formatv("invalid pipeline '{0}'", PipelineText).str(),
1895 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001896
1897 StringRef FirstName = Pipeline->front().Name;
1898 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001899 return make_error<StringError>(
1900 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
1901 PipelineText)
1902 .str(),
1903 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001904
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001905 if (auto Err =
1906 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1907 return Err;
1908 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001909}
1910
1911// Primary pass pipeline description parsing routine for a \c
1912// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001913Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1914 StringRef PipelineText,
1915 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001916 auto Pipeline = parsePipelineText(PipelineText);
1917 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001918 return make_error<StringError>(
1919 formatv("invalid pipeline '{0}'", PipelineText).str(),
1920 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001921
1922 StringRef FirstName = Pipeline->front().Name;
1923 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001924 return make_error<StringError>(
1925 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
1926 PipelineText)
1927 .str(),
1928 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001929
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001930 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1931 DebugLogging))
1932 return Err;
1933 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001934}
1935
1936// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001937Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1938 StringRef PipelineText,
1939 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001940 auto Pipeline = parsePipelineText(PipelineText);
1941 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001942 return make_error<StringError>(
1943 formatv("invalid pipeline '{0}'", PipelineText).str(),
1944 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001945
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001946 if (auto Err =
1947 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1948 return Err;
1949
1950 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001951}
1952
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001953Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00001954 // If the pipeline just consists of the word 'default' just replace the AA
1955 // manager with our default one.
1956 if (PipelineText == "default") {
1957 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001958 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00001959 }
1960
Chandler Carruthedf59962016-02-18 09:45:17 +00001961 while (!PipelineText.empty()) {
1962 StringRef Name;
1963 std::tie(Name, PipelineText) = PipelineText.split(',');
1964 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001965 return make_error<StringError>(
1966 formatv("unknown alias analysis name '{0}'", Name).str(),
1967 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00001968 }
1969
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001970 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00001971}