blob: e4d15277899beee2ff997dd73e11d9307ca148f1 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth66445382014-01-11 08:16:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9///
Chandler Carruth1ff77242015-03-07 09:02:36 +000010/// This file provides the implementation of the PassBuilder based on our
11/// static pass registry as well as related functionality. It also provides
12/// helpers to aid in analyzing, debugging, and testing passes and pass
13/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000014///
15//===----------------------------------------------------------------------===//
16
Chandler Carruth1ff77242015-03-07 09:02:36 +000017#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000018#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000019#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000020#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000021#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000022#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000024#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000025#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000026#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000028#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000029#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000030#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000031#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000032#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000033#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000034#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000035#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000036#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000037#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000038#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000039#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000040#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000041#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000042#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000043#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000044#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000045#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000046#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000049#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000050#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000051#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000052#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000053#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000054#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000055#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000057#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000058#include "llvm/IR/PassManager.h"
Fedor Sergeeva2ed4482019-03-31 10:15:39 +000059#include "llvm/IR/SafepointIRVerifier.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000091#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000092#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000093#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000094#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000095#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000096#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Leonard Chan0cdd3b12019-05-14 21:17:21 +000097#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Manman Ren18295122019-02-28 20:13:38 +000098#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000099#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +0000100#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000101#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000102#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000103#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000104#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000105#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000106#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000107#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000108#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000109#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000110#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000111#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000112#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000113#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000114#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000115#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000116#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000117#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000118#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000119#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000120#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000121#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000122#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000123#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000124#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000125#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000126#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000127#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000128#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000129#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000130#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000131#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000132#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000133#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000134#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000135#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000136#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000137#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000138#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000139#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000140#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000141#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000142#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000143#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000144#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000145#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000146#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000147#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000148#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000149#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000150#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000151#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000152#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000153#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000154#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000155#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000156#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000157#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000158#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000159#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000160#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000161#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000162#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000163#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000164#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000165#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000166#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000167#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000168#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000169#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000170#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000171#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000172#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000173#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000174
Chandler Carruth66445382014-01-11 08:16:35 +0000175using namespace llvm;
176
Chandler Carruth719ffe12017-02-12 05:38:04 +0000177static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
178 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000179static cl::opt<bool>
180 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
181 cl::Hidden, cl::ZeroOrMore,
182 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000183
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000184static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000185 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000186 cl::Hidden, cl::ZeroOrMore,
187 cl::desc("Run NewGVN instead of GVN"));
188
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000189static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000190 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
191 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000192
Davide Italianobe1b6a92017-06-03 23:18:29 +0000193static cl::opt<bool> EnableGVNSink(
194 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
195 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
196
David Green963401d2018-07-01 12:47:30 +0000197static cl::opt<bool> EnableUnrollAndJam(
198 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
199 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
200
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000201static cl::opt<bool> EnableSyntheticCounts(
202 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
203 cl::desc("Run synthetic function entry count generation "
204 "pass"));
205
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000206static Regex DefaultAliasRegex(
207 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000208
Eric Christophereff3b6f2019-04-18 06:17:40 +0000209// This option is used in simplifying testing SampleFDO optimizations for
210// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000211static cl::opt<bool>
212 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
213 cl::desc("Enable control height reduction optimization (CHR)"));
214
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000215PipelineTuningOptions::PipelineTuningOptions() {
216 LoopInterleaving = EnableLoopInterleaving;
217 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea458c7332019-05-08 17:58:35 +0000218 SLPVectorization = RunSLPVectorization;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000219 LicmMssaOptCap = SetLicmMssaOptCap;
220 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000221}
222
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000223extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000224extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000225
Wei Mi3bcccdf2019-01-17 20:48:34 +0000226extern cl::opt<bool> FlattenedProfileUsed;
227
Chandler Carruthe3f50642016-12-22 06:59:15 +0000228static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
229 switch (Level) {
230 case PassBuilder::O0:
231 case PassBuilder::O1:
232 case PassBuilder::O2:
233 case PassBuilder::O3:
234 return false;
235
236 case PassBuilder::Os:
237 case PassBuilder::Oz:
238 return true;
239 }
240 llvm_unreachable("Invalid optimization level!");
241}
242
Chandler Carruth66445382014-01-11 08:16:35 +0000243namespace {
244
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000245/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000246struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000247 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000248 return PreservedAnalyses::all();
249 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000250 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000251};
252
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000253/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000254class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
255 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000256 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000257
258public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000259 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000260 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000261 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000262};
263
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000264/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000265struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000266 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
267 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000268 return PreservedAnalyses::all();
269 }
270 static StringRef name() { return "NoOpCGSCCPass"; }
271};
272
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000273/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000274class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
275 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000276 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000277
278public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000279 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000280 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000281 return Result();
282 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000283 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000284};
285
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000286/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000287struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000288 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000289 return PreservedAnalyses::all();
290 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000291 static StringRef name() { return "NoOpFunctionPass"; }
292};
293
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000294/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000295class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
296 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000297 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000298
299public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000300 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000301 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000302 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000303};
304
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000305/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000306struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000307 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
308 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000309 return PreservedAnalyses::all();
310 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000311 static StringRef name() { return "NoOpLoopPass"; }
312};
313
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000314/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000315class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
316 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000317 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000318
319public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000320 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000321 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
322 return Result();
323 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000324 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000325};
326
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000327AnalysisKey NoOpModuleAnalysis::Key;
328AnalysisKey NoOpCGSCCAnalysis::Key;
329AnalysisKey NoOpFunctionAnalysis::Key;
330AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000331
Chandler Carruth66445382014-01-11 08:16:35 +0000332} // End anonymous namespace.
333
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000334void PassBuilder::invokePeepholeEPCallbacks(
335 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
336 for (auto &C : PeepholeEPCallbacks)
337 C(FPM, Level);
338}
339
Chandler Carruth1ff77242015-03-07 09:02:36 +0000340void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000341#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000342 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000343#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000344
345 for (auto &C : ModuleAnalysisRegistrationCallbacks)
346 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000347}
348
Chandler Carruth1ff77242015-03-07 09:02:36 +0000349void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000350#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000351 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000352#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000353
354 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
355 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000356}
357
Chandler Carruth1ff77242015-03-07 09:02:36 +0000358void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000359#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000360 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000361#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000362
363 for (auto &C : FunctionAnalysisRegistrationCallbacks)
364 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000365}
366
Justin Bognereecc3c82016-02-25 07:23:08 +0000367void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000368#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000369 LAM.registerPass([&] { return CREATE_PASS; });
370#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000371
372 for (auto &C : LoopAnalysisRegistrationCallbacks)
373 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000374}
375
Chandler Carruthe3f50642016-12-22 06:59:15 +0000376FunctionPassManager
377PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000378 ThinLTOPhase Phase,
379 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000380 assert(Level != O0 && "Must request optimizations!");
381 FunctionPassManager FPM(DebugLogging);
382
383 // Form SSA out of local memory accesses after breaking apart aggregates into
384 // scalars.
385 FPM.addPass(SROA());
386
387 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000388 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000389
Davide Italianoc3688312017-06-01 23:08:14 +0000390 // Hoisting of scalars and load expressions.
391 if (EnableGVNHoist)
392 FPM.addPass(GVNHoistPass());
393
Davide Italianobe1b6a92017-06-03 23:18:29 +0000394 // Global value numbering based sinking.
395 if (EnableGVNSink) {
396 FPM.addPass(GVNSinkPass());
397 FPM.addPass(SimplifyCFGPass());
398 }
399
Chandler Carruthe3f50642016-12-22 06:59:15 +0000400 // Speculative execution if the target has divergent branches; otherwise nop.
401 FPM.addPass(SpeculativeExecutionPass());
402
403 // Optimize based on known information about branches, and cleanup afterward.
404 FPM.addPass(JumpThreadingPass());
405 FPM.addPass(CorrelatedValuePropagationPass());
406 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000407 if (Level == O3)
408 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000409 FPM.addPass(InstCombinePass());
410
411 if (!isOptimizingForSize(Level))
412 FPM.addPass(LibCallsShrinkWrapPass());
413
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000414 invokePeepholeEPCallbacks(FPM, Level);
415
Rong Xue1f42452017-10-23 22:21:29 +0000416 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
417 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000418 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000419 !isOptimizingForSize(Level))
420 FPM.addPass(PGOMemOPSizeOpt());
421
Chandler Carruthe3f50642016-12-22 06:59:15 +0000422 FPM.addPass(TailCallElimPass());
423 FPM.addPass(SimplifyCFGPass());
424
425 // Form canonically associated expression trees, and simplify the trees using
426 // basic mathematical properties. For example, this will form (nearly)
427 // minimal multiplication trees.
428 FPM.addPass(ReassociatePass());
429
430 // Add the primary loop simplification pipeline.
431 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000432 // some function passes in between them. These can and should be removed
433 // and/or replaced by scheduling the loop pass equivalents in the correct
434 // positions. But those equivalent passes aren't powerful enough yet.
435 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
436 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
437 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
438 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000439 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
440
Chandler Carruth71fd2702018-05-30 02:46:45 +0000441 // Simplify the loop body. We do this initially to clean up after other loop
442 // passes run, either when iterating on a loop or on inner loops with
443 // implications on the outer loop.
444 LPM1.addPass(LoopInstSimplifyPass());
445 LPM1.addPass(LoopSimplifyCFGPass());
446
Chandler Carruthe3f50642016-12-22 06:59:15 +0000447 // Rotate Loop - disable header duplication at -Oz
448 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000449 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000450 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000451 LPM2.addPass(IndVarSimplifyPass());
452 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000453
454 for (auto &C : LateLoopOptimizationsEPCallbacks)
455 C(LPM2, Level);
456
Chandler Carruth79b733b2017-01-26 23:21:17 +0000457 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000458 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000459 // because it changes IR to makes profile annotation in back compile
460 // inaccurate.
Rong Xudb29a3a2019-03-04 20:21:27 +0000461 if (Phase != ThinLTOPhase::PreLink || !PGOOpt ||
462 PGOOpt->Action != PGOOptions::SampleUse)
Teresa Johnsonecd90132017-08-02 20:35:29 +0000463 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000464
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000465 for (auto &C : LoopOptimizerEndEPCallbacks)
466 C(LPM2, Level);
467
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000468 // We provide the opt remark emitter pass for LICM to use. We only need to do
469 // this once as it is immutable.
470 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000471 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000472 FPM.addPass(SimplifyCFGPass());
473 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000474 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000475
476 // Eliminate redundancies.
477 if (Level != O1) {
478 // These passes add substantial compile time so skip them at O1.
479 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000480 if (RunNewGVN)
481 FPM.addPass(NewGVNPass());
482 else
483 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000484 }
485
486 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
487 FPM.addPass(MemCpyOptPass());
488
489 // Sparse conditional constant propagation.
490 // FIXME: It isn't clear why we do this *after* loop passes rather than
491 // before...
492 FPM.addPass(SCCPPass());
493
494 // Delete dead bit computations (instcombine runs after to fold away the dead
495 // computations, and then ADCE will run later to exploit any new DCE
496 // opportunities that creates).
497 FPM.addPass(BDCEPass());
498
499 // Run instcombine after redundancy and dead bit elimination to exploit
500 // opportunities opened up by them.
501 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000502 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000503
504 // Re-consider control flow based optimizations after redundancy elimination,
505 // redo DCE, etc.
506 FPM.addPass(JumpThreadingPass());
507 FPM.addPass(CorrelatedValuePropagationPass());
508 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000509 FPM.addPass(createFunctionToLoopPassAdaptor(
510 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
511 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000512
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000513 for (auto &C : ScalarOptimizerLateEPCallbacks)
514 C(FPM, Level);
515
Chandler Carruthe3f50642016-12-22 06:59:15 +0000516 // Finally, do an expensive DCE pass to catch all the dead code exposed by
517 // the simplifications and basic cleanup after all the simplifications.
518 FPM.addPass(ADCEPass());
519 FPM.addPass(SimplifyCFGPass());
520 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000521 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000522
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000523 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000524 (PGOOpt->Action == PGOOptions::IRUse ||
525 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000526 FPM.addPass(ControlHeightReductionPass());
527
Chandler Carruthe3f50642016-12-22 06:59:15 +0000528 return FPM;
529}
530
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000531void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
532 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000533 bool RunProfileGen, bool IsCS,
534 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000535 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000536 // Generally running simplification passes and the inliner with an high
537 // threshold results in smaller executables, but there may be cases where
538 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000539 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
540 // IsCS is true).
541 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000542 InlineParams IP;
543
544 // In the old pass manager, this is a cl::opt. Should still this be one?
545 IP.DefaultThreshold = 75;
546
547 // FIXME: The hint threshold has the same value used by the regular inliner.
548 // This should probably be lowered after performance testing.
549 // FIXME: this comment is cargo culted from the old pass manager, revisit).
550 IP.HintThreshold = 325;
551
552 CGSCCPassManager CGPipeline(DebugLogging);
553
554 CGPipeline.addPass(InlinerPass(IP));
555
556 FunctionPassManager FPM;
557 FPM.addPass(SROA());
558 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
559 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
560 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000561 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000562
Davide Italiano513dfaa2017-02-13 15:26:22 +0000563 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
564
565 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
566 }
567
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000568 // Delete anything that is now dead to make sure that we don't instrument
569 // dead code. Instrumentation can end up keeping dead code around and
570 // dramatically increase code size.
571 MPM.addPass(GlobalDCEPass());
572
Davide Italiano513dfaa2017-02-13 15:26:22 +0000573 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000574 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000575
Xinliang David Lib67530e2017-06-25 00:26:43 +0000576 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000577 FPM.addPass(
578 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000579 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
580
Davide Italiano513dfaa2017-02-13 15:26:22 +0000581 // Add the profile lowering pass.
582 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000583 if (!ProfileFile.empty())
584 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000585 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000586 Options.UseBFIInPromotion = IsCS;
587 MPM.addPass(InstrProfiling(Options, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000588 } else if (!ProfileFile.empty()) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000589 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000590 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
591 // RequireAnalysisPass for PSI before subsequent non-module passes.
592 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
593 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000594}
595
Easwaran Raman8249fac2017-06-28 13:33:49 +0000596static InlineParams
597getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
598 auto O3 = PassBuilder::O3;
599 unsigned OptLevel = Level > O3 ? 2 : Level;
600 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
601 return getInlineParams(OptLevel, SizeLevel);
602}
603
Chandler Carruthe3f50642016-12-22 06:59:15 +0000604ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000605PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000606 ThinLTOPhase Phase,
607 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000608 ModulePassManager MPM(DebugLogging);
609
Rong Xudb29a3a2019-03-04 20:21:27 +0000610 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000611
612 // In ThinLTO mode, when flattened profile is used, all the available
613 // profile information will be annotated in PreLink phase so there is
614 // no need to load the profile again in PostLink.
615 bool LoadSampleProfile =
616 HasSampleProfile &&
617 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
618
619 // During the ThinLTO backend phase we perform early indirect call promotion
620 // here, before globalopt. Otherwise imported available_externally functions
621 // look unreferenced and are removed. If we are going to load the sample
622 // profile then defer until later.
623 // TODO: See if we can move later and consolidate with the location where
624 // we perform ICP when we are loading a sample profile.
625 // TODO: We pass HasSampleProfile (whether there was a sample profile file
626 // passed to the compile) to the SamplePGO flag of ICP. This is used to
627 // determine whether the new direct calls are annotated with prof metadata.
628 // Ideally this should be determined from whether the IR is annotated with
629 // sample profile, and not whether the a sample profile was provided on the
630 // command line. E.g. for flattened profiles where we will not be reloading
631 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
632 // provide the sample profile file.
633 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
634 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
635
Chandler Carruthe3f50642016-12-22 06:59:15 +0000636 // Do basic inference of function attributes from known properties of system
637 // libraries and other oracles.
638 MPM.addPass(InferFunctionAttrsPass());
639
640 // Create an early function pass manager to cleanup the output of the
641 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000642 FunctionPassManager EarlyFPM(DebugLogging);
643 EarlyFPM.addPass(SimplifyCFGPass());
644 EarlyFPM.addPass(SROA());
645 EarlyFPM.addPass(EarlyCSEPass());
646 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000647 if (Level == O3)
648 EarlyFPM.addPass(CallSiteSplittingPass());
649
Dehao Chen08f88312017-08-07 20:23:20 +0000650 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
651 // to convert bitcast to direct calls so that they can be inlined during the
652 // profile annotation prepration step.
653 // More details about SamplePGO design can be found in:
654 // https://research.google.com/pubs/pub45290.html
655 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000656 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000657 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000658 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000659
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000660 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000661 // Annotate sample profile right after early FPM to ensure freshness of
662 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000663 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000664 PGOOpt->ProfileRemappingFile,
665 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000666 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
667 // RequireAnalysisPass for PSI before subsequent non-module passes.
668 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000669 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
670 // for the profile annotation to be accurate in the ThinLTO backend.
671 if (Phase != ThinLTOPhase::PreLink)
672 // We perform early indirect call promotion here, before globalopt.
673 // This is important for the ThinLTO backend phase because otherwise
674 // imported available_externally functions look unreferenced and are
675 // removed.
676 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000677 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000678 }
679
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000680 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000681 // and prior to optimizing globals.
682 // FIXME: This position in the pipeline hasn't been carefully considered in
683 // years, it should be re-analyzed.
684 MPM.addPass(IPSCCPPass());
685
Matthew Simpsoncb585582017-10-25 13:40:08 +0000686 // Attach metadata to indirect call sites indicating the set of functions
687 // they may target at run-time. This should follow IPSCCP.
688 MPM.addPass(CalledValuePropagationPass());
689
Chandler Carruthe3f50642016-12-22 06:59:15 +0000690 // Optimize globals to try and fold them into constants.
691 MPM.addPass(GlobalOptPass());
692
693 // Promote any localized globals to SSA registers.
694 // FIXME: Should this instead by a run of SROA?
695 // FIXME: We should probably run instcombine and simplify-cfg afterward to
696 // delete control flows that are dead once globals have been folded to
697 // constants.
698 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
699
700 // Remove any dead arguments exposed by cleanups and constand folding
701 // globals.
702 MPM.addPass(DeadArgumentEliminationPass());
703
704 // Create a small function pass pipeline to cleanup after all the global
705 // optimizations.
706 FunctionPassManager GlobalCleanupPM(DebugLogging);
707 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000708 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
709
Chandler Carruthe3f50642016-12-22 06:59:15 +0000710 GlobalCleanupPM.addPass(SimplifyCFGPass());
711 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
712
Dehao Chen89d32262017-08-02 01:28:31 +0000713 // Add all the requested passes for instrumentation PGO, if requested.
714 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000715 (PGOOpt->Action == PGOOptions::IRInstr ||
716 PGOOpt->Action == PGOOptions::IRUse)) {
717 addPGOInstrPasses(MPM, DebugLogging, Level,
718 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
719 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000720 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000721 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000722 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000723 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
724 PGOOpt->CSAction == PGOOptions::CSIRInstr)
725 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000726
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000727 // Synthesize function entry counts for non-PGO compilation.
728 if (EnableSyntheticCounts && !PGOOpt)
729 MPM.addPass(SyntheticCountsPropagation());
730
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000731 // Require the GlobalsAA analysis for the module so we can query it within
732 // the CGSCC pipeline.
733 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000734
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000735 // Require the ProfileSummaryAnalysis for the module so we can query it within
736 // the inliner pass.
737 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
738
Chandler Carruthe3f50642016-12-22 06:59:15 +0000739 // Now begin the main postorder CGSCC pipeline.
740 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
741 // manager and trying to emulate its precise behavior. Much of this doesn't
742 // make a lot of sense and we should revisit the core CGSCC structure.
743 CGSCCPassManager MainCGPipeline(DebugLogging);
744
745 // Note: historically, the PruneEH pass was run first to deduce nounwind and
746 // generally clean up exception handling overhead. It isn't clear this is
747 // valuable as the inliner doesn't currently care whether it is inlining an
748 // invoke or a call.
749
750 // Run the inliner first. The theory is that we are walking bottom-up and so
751 // the callees have already been fully optimized, and we want to inline them
752 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000753 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000754 // because it makes profile annotation in the backend inaccurate.
755 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000756 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
757 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000758 IP.HotCallSiteThreshold = 0;
759 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000760
761 // Now deduce any function attributes based in the current code.
762 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
763
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000764 // When at O3 add argument promotion to the pass pipeline.
765 // FIXME: It isn't at all clear why this should be limited to O3.
766 if (Level == O3)
767 MainCGPipeline.addPass(ArgumentPromotionPass());
768
Chandler Carruthe3f50642016-12-22 06:59:15 +0000769 // Lastly, add the core function simplification pipeline nested inside the
770 // CGSCC walk.
771 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000772 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000773
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000774 for (auto &C : CGSCCOptimizerLateEPCallbacks)
775 C(MainCGPipeline, Level);
776
Chandler Carruth719ffe12017-02-12 05:38:04 +0000777 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
778 // to detect when we devirtualize indirect calls and iterate the SCC passes
779 // in that case to try and catch knock-on inlining or function attrs
780 // opportunities. Then we add it to the module pipeline by walking the SCCs
781 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000782 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000783 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000784 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000785
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000786 return MPM;
787}
788
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000789ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
790 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000791 ModulePassManager MPM(DebugLogging);
792
793 // Optimize globals now that the module is fully simplified.
794 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000795 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000796
Xinliang David Li126157c2017-05-22 16:41:57 +0000797 // Run partial inlining pass to partially inline functions that have
798 // large bodies.
799 if (RunPartialInlining)
800 MPM.addPass(PartialInlinerPass());
801
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000802 // Remove avail extern fns and globals definitions since we aren't compiling
803 // an object file for later LTO. For LTO we want to preserve these so they
804 // are eligible for inlining at link-time. Note if they are unreferenced they
805 // will be removed by GlobalDCE later, so this only impacts referenced
806 // available externally globals. Eventually they will be suppressed during
807 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
808 // may make globals referenced by available external functions dead and saves
809 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000810 MPM.addPass(EliminateAvailableExternallyPass());
811
Manman Ren18295122019-02-28 20:13:38 +0000812 if (EnableOrderFileInstrumentation)
813 MPM.addPass(InstrOrderFilePass());
814
Chandler Carruthe3f50642016-12-22 06:59:15 +0000815 // Do RPO function attribute inference across the module to forward-propagate
816 // attributes where applicable.
817 // FIXME: Is this really an optimization rather than a canonicalization?
818 MPM.addPass(ReversePostOrderFunctionAttrsPass());
819
Rong Xudb29a3a2019-03-04 20:21:27 +0000820 // Do a post inline PGO instrumentation and use pass. This is a context
821 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
822 // cross-module inline has not been done yet. The context sensitive
823 // instrumentation is after all the inlines are done.
824 if (!LTOPreLink && PGOOpt) {
825 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
826 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
827 /* IsCS */ true, PGOOpt->CSProfileGenFile,
828 PGOOpt->ProfileRemappingFile);
829 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
830 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
831 /* IsCS */ true, PGOOpt->ProfileFile,
832 PGOOpt->ProfileRemappingFile);
833 }
834
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000835 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000836 // useful as the above will have inlined, DCE'ed, and function-attr
837 // propagated everything. We should at this point have a reasonably minimal
838 // and richly annotated call graph. By computing aliasing and mod/ref
839 // information for all local globals here, the late loop passes and notably
840 // the vectorizer will be able to use them to help recognize vectorizable
841 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000842 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000843
844 FunctionPassManager OptimizePM(DebugLogging);
845 OptimizePM.addPass(Float2IntPass());
846 // FIXME: We need to run some loop optimizations to re-rotate loops after
847 // simplify-cfg and others undo their rotation.
848
849 // Optimize the loop execution. These passes operate on entire loop nests
850 // rather than on each loop in an inside-out manner, and so they are actually
851 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000852
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000853 for (auto &C : VectorizerStartEPCallbacks)
854 C(OptimizePM, Level);
855
Chandler Carrutha95ff382017-01-27 00:50:21 +0000856 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000857 OptimizePM.addPass(
858 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000859
860 // Distribute loops to allow partial vectorization. I.e. isolate dependences
861 // into separate loop that would otherwise inhibit vectorization. This is
862 // currently only performed for loops marked with the metadata
863 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000864 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000865
866 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000867 OptimizePM.addPass(LoopVectorizePass(
868 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000869
Chandler Carruthbaabda92017-01-27 01:32:26 +0000870 // Eliminate loads by forwarding stores from the previous iteration to loads
871 // of the current iteration.
872 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000873
874 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000875 OptimizePM.addPass(InstCombinePass());
876
Chandler Carrutha95ff382017-01-27 00:50:21 +0000877 // Now that we've formed fast to execute loop structures, we do further
878 // optimizations. These are run afterward as they might block doing complex
879 // analyses and transforms such as what are needed for loop vectorization.
880
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000881 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
882 // GVN, loop transforms, and others have already run, so it's now better to
883 // convert to more optimized IR using more aggressive simplify CFG options.
884 // The extra sinking transform can create larger basic blocks, so do this
885 // before SLP vectorization.
886 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
887 forwardSwitchCondToPhi(true).
888 convertSwitchToLookupTable(true).
889 needCanonicalLoops(false).
890 sinkCommonInsts(true)));
891
Chandler Carruthe3f50642016-12-22 06:59:15 +0000892 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000893 if (PTO.SLPVectorization)
894 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000895
Chandler Carruthe3f50642016-12-22 06:59:15 +0000896 OptimizePM.addPass(InstCombinePass());
897
898 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000899 // execution resources of an out-of-order processor. We also then need to
900 // clean up redundancies and loop invariant code.
901 // FIXME: It would be really good to use a loop-integrated instruction
902 // combiner for cleanup here so that the unrolling and LICM can be pipelined
903 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000904 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
905 if (EnableUnrollAndJam) {
906 OptimizePM.addPass(
907 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
908 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000909 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000910 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000911 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000912 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000913 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
914 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
915 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000916
917 // Now that we've vectorized and unrolled loops, we may have more refined
918 // alignment information, try to re-derive it here.
919 OptimizePM.addPass(AlignmentFromAssumptionsPass());
920
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000921 // Split out cold code. Splitting is done late to avoid hiding context from
922 // other optimizations and inadvertently regressing performance. The tradeoff
923 // is that this has a higher code size cost than splitting early.
924 if (EnableHotColdSplit && !LTOPreLink)
925 MPM.addPass(HotColdSplittingPass());
926
Chandler Carrutha95ff382017-01-27 00:50:21 +0000927 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
928 // canonicalization pass that enables other optimizations. As a result,
929 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
930 // result too early.
931 OptimizePM.addPass(LoopSinkPass());
932
933 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000934 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000935
Sanjay Patel6fd43912017-09-09 13:38:18 +0000936 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
937 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
938 // flattening of blocks.
939 OptimizePM.addPass(DivRemPairsPass());
940
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000941 // LoopSink (and other loop passes since the last simplifyCFG) might have
942 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
943 OptimizePM.addPass(SimplifyCFGPass());
944
Chandler Carruthc34f7892017-11-28 11:32:31 +0000945 // Optimize PHIs by speculating around them when profitable. Note that this
946 // pass needs to be run after any PRE or similar pass as it is essentially
Joerg Sonnenbergerec6ee792019-05-16 18:01:57 +0000947 // inserting redundancies into the program. This even includes SimplifyCFG.
Chandler Carruthc34f7892017-11-28 11:32:31 +0000948 OptimizePM.addPass(SpeculateAroundPHIsPass());
949
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000950 for (auto &C : OptimizerLastEPCallbacks)
951 C(OptimizePM, Level);
952
Chandler Carrutha95ff382017-01-27 00:50:21 +0000953 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000954 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
955
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000956 MPM.addPass(CGProfilePass());
957
Chandler Carruthe3f50642016-12-22 06:59:15 +0000958 // Now we need to do some global optimization transforms.
959 // FIXME: It would seem like these should come first in the optimization
960 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
961 // ordering here.
962 MPM.addPass(GlobalDCEPass());
963 MPM.addPass(ConstantMergePass());
964
965 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000966}
967
Chandler Carruthe3f50642016-12-22 06:59:15 +0000968ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000969PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000970 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000971 assert(Level != O0 && "Must request optimizations for the default pipeline!");
972
973 ModulePassManager MPM(DebugLogging);
974
975 // Force any function attributes we want the rest of the pipeline to observe.
976 MPM.addPass(ForceFunctionAttrsPass());
977
David Blaikie0c64f5a2018-01-23 01:25:20 +0000978 // Apply module pipeline start EP callback.
979 for (auto &C : PipelineStartEPCallbacks)
980 C(MPM);
981
Dehao Chen08f88312017-08-07 20:23:20 +0000982 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000983 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
984
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000985 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000986 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
987 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000988
989 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000990 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000991
992 return MPM;
993}
994
995ModulePassManager
996PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
997 bool DebugLogging) {
998 assert(Level != O0 && "Must request optimizations for the default pipeline!");
999
1000 ModulePassManager MPM(DebugLogging);
1001
1002 // Force any function attributes we want the rest of the pipeline to observe.
1003 MPM.addPass(ForceFunctionAttrsPass());
1004
Dehao Chen08f88312017-08-07 20:23:20 +00001005 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001006 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1007
David Blaikie0c64f5a2018-01-23 01:25:20 +00001008 // Apply module pipeline start EP callback.
1009 for (auto &C : PipelineStartEPCallbacks)
1010 C(MPM);
1011
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001012 // If we are planning to perform ThinLTO later, we don't bloat the code with
1013 // unrolling/vectorization/... now. Just simplify the module as much as we
1014 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001015 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1016 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001017
1018 // Run partial inlining pass to partially inline functions that have
1019 // large bodies.
1020 // FIXME: It isn't clear whether this is really the right place to run this
1021 // in ThinLTO. Because there is another canonicalization and simplification
1022 // phase that will run after the thin link, running this here ends up with
1023 // less information than will be available later and it may grow functions in
1024 // ways that aren't beneficial.
1025 if (RunPartialInlining)
1026 MPM.addPass(PartialInlinerPass());
1027
1028 // Reduce the size of the IR as much as possible.
1029 MPM.addPass(GlobalOptPass());
1030
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001031 return MPM;
1032}
1033
Teresa Johnson28023db2018-07-19 14:51:32 +00001034ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1035 OptimizationLevel Level, bool DebugLogging,
1036 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001037 ModulePassManager MPM(DebugLogging);
1038
Teresa Johnson28023db2018-07-19 14:51:32 +00001039 if (ImportSummary) {
1040 // These passes import type identifier resolutions for whole-program
1041 // devirtualization and CFI. They must run early because other passes may
1042 // disturb the specific instruction patterns that these passes look for,
1043 // creating dependencies on resolutions that may not appear in the summary.
1044 //
1045 // For example, GVN may transform the pattern assume(type.test) appearing in
1046 // two basic blocks into assume(phi(type.test, type.test)), which would
1047 // transform a dependency on a WPD resolution into a dependency on a type
1048 // identifier resolution for CFI.
1049 //
1050 // Also, WPD has access to more precise information than ICP and can
1051 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001052 //
1053 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1054 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001055 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1056 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1057 }
1058
Teresa Johnson867bc392019-04-23 18:56:19 +00001059 if (Level == O0)
1060 return MPM;
1061
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001062 // Force any function attributes we want the rest of the pipeline to observe.
1063 MPM.addPass(ForceFunctionAttrsPass());
1064
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001065 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001066 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1067 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001068
1069 // Now add the optimization pipeline.
1070 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1071
1072 return MPM;
1073}
1074
1075ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001076PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1077 bool DebugLogging) {
1078 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001079 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001080 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001081 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001082}
1083
Teresa Johnson28023db2018-07-19 14:51:32 +00001084ModulePassManager
1085PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1086 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001087 ModulePassManager MPM(DebugLogging);
1088
Teresa Johnson867bc392019-04-23 18:56:19 +00001089 if (Level == O0) {
1090 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1091 // metadata and intrinsics.
1092 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1093 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1094 return MPM;
1095 }
1096
Rong Xudb29a3a2019-03-04 20:21:27 +00001097 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001098 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001099 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001100 PGOOpt->ProfileRemappingFile,
1101 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001102 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1103 // RequireAnalysisPass for PSI before subsequent non-module passes.
1104 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001105 }
1106
Davide Italiano089a9122017-01-24 00:57:39 +00001107 // Remove unused virtual tables to improve the quality of code generated by
1108 // whole-program devirtualization and bitset lowering.
1109 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001110
Davide Italiano089a9122017-01-24 00:57:39 +00001111 // Force any function attributes we want the rest of the pipeline to observe.
1112 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001113
Davide Italiano089a9122017-01-24 00:57:39 +00001114 // Do basic inference of function attributes from known properties of system
1115 // libraries and other oracles.
1116 MPM.addPass(InferFunctionAttrsPass());
1117
1118 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001119 FunctionPassManager EarlyFPM(DebugLogging);
1120 EarlyFPM.addPass(CallSiteSplittingPass());
1121 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1122
Davide Italiano089a9122017-01-24 00:57:39 +00001123 // Indirect call promotion. This should promote all the targets that are
1124 // left by the earlier promotion pass that promotes intra-module targets.
1125 // This two-step promotion is to save the compile time. For LTO, it should
1126 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001127 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001128 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001129 // Propagate constants at call sites into the functions they call. This
1130 // opens opportunities for globalopt (and inlining) by substituting function
1131 // pointers passed as arguments to direct uses of functions.
1132 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001133
1134 // Attach metadata to indirect call sites indicating the set of functions
1135 // they may target at run-time. This should follow IPSCCP.
1136 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001137 }
1138
1139 // Now deduce any function attributes based in the current code.
1140 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1141 PostOrderFunctionAttrsPass()));
1142
1143 // Do RPO function attribute inference across the module to forward-propagate
1144 // attributes where applicable.
1145 // FIXME: Is this really an optimization rather than a canonicalization?
1146 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1147
Eric Christopher721eaef2019-02-26 20:33:22 +00001148 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001149 MPM.addPass(GlobalSplitPass());
1150
1151 // Run whole program optimization of virtual call when the list of callees
1152 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001153 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001154
1155 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001156 if (Level == 1) {
1157 // The LowerTypeTestsPass needs to run to lower type metadata and the
1158 // type.test intrinsics. The pass does nothing if CFI is disabled.
1159 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001160 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001161 }
Davide Italiano089a9122017-01-24 00:57:39 +00001162
1163 // Optimize globals to try and fold them into constants.
1164 MPM.addPass(GlobalOptPass());
1165
1166 // Promote any localized globals to SSA registers.
1167 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1168
1169 // Linking modules together can lead to duplicate global constant, only
1170 // keep one copy of each constant.
1171 MPM.addPass(ConstantMergePass());
1172
1173 // Remove unused arguments from functions.
1174 MPM.addPass(DeadArgumentEliminationPass());
1175
1176 // Reduce the code after globalopt and ipsccp. Both can open up significant
1177 // simplification opportunities, and both can propagate functions through
1178 // function pointers. When this happens, we often have to resolve varargs
1179 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001180 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001181 if (Level == O3)
1182 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001183 PeepholeFPM.addPass(InstCombinePass());
1184 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1185
1186 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001187
1188 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1189 // generally clean up exception handling overhead. It isn't clear this is
1190 // valuable as the inliner doesn't currently care whether it is inlining an
1191 // invoke or a call.
1192 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001193 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1194 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001195
1196 // Optimize globals again after we ran the inliner.
1197 MPM.addPass(GlobalOptPass());
1198
1199 // Garbage collect dead functions.
1200 // FIXME: Add ArgumentPromotion pass after once it's ported.
1201 MPM.addPass(GlobalDCEPass());
1202
1203 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001204 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001205 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001206 invokePeepholeEPCallbacks(FPM, Level);
1207
Davide Italiano089a9122017-01-24 00:57:39 +00001208 FPM.addPass(JumpThreadingPass());
1209
Rong Xudb29a3a2019-03-04 20:21:27 +00001210 // Do a post inline PGO instrumentation and use pass. This is a context
1211 // sensitive PGO pass.
1212 if (PGOOpt) {
1213 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1214 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1215 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1216 PGOOpt->ProfileRemappingFile);
1217 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1218 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1219 /* IsCS */ true, PGOOpt->ProfileFile,
1220 PGOOpt->ProfileRemappingFile);
1221 }
1222
Davide Italiano089a9122017-01-24 00:57:39 +00001223 // Break up allocas
1224 FPM.addPass(SROA());
1225
Robert Lougherf2158a82019-03-20 19:08:18 +00001226 // LTO provides additional opportunities for tailcall elimination due to
1227 // link-time inlining, and visibility of nocapture attribute.
1228 FPM.addPass(TailCallElimPass());
1229
Davide Italiano089a9122017-01-24 00:57:39 +00001230 // Run a few AA driver optimizations here and now to cleanup the code.
1231 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1232
1233 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1234 PostOrderFunctionAttrsPass()));
1235 // FIXME: here we run IP alias analysis in the legacy PM.
1236
1237 FunctionPassManager MainFPM;
1238
1239 // FIXME: once we fix LoopPass Manager, add LICM here.
1240 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001241 if (RunNewGVN)
1242 MainFPM.addPass(NewGVNPass());
1243 else
1244 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001245
1246 // Remove dead memcpy()'s.
1247 MainFPM.addPass(MemCpyOptPass());
1248
1249 // Nuke dead stores.
1250 MainFPM.addPass(DSEPass());
1251
1252 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001253 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001254 // loopVectorize. Enable them once the remaining issue with LPM
1255 // are sorted out.
1256
1257 MainFPM.addPass(InstCombinePass());
1258 MainFPM.addPass(SimplifyCFGPass());
1259 MainFPM.addPass(SCCPPass());
1260 MainFPM.addPass(InstCombinePass());
1261 MainFPM.addPass(BDCEPass());
1262
1263 // FIXME: We may want to run SLPVectorizer here.
1264 // After vectorization, assume intrinsics may tell us more
1265 // about pointer alignments.
1266#if 0
1267 MainFPM.add(AlignmentFromAssumptionsPass());
1268#endif
1269
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001270 // FIXME: Conditionally run LoadCombine here, after it's ported
1271 // (in case we still have this pass, given its questionable usefulness).
1272
Davide Italiano089a9122017-01-24 00:57:39 +00001273 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001274 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001275 MainFPM.addPass(JumpThreadingPass());
1276 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1277
1278 // Create a function that performs CFI checks for cross-DSO calls with
1279 // targets in the current module.
1280 MPM.addPass(CrossDSOCFIPass());
1281
1282 // Lower type metadata and the type.test intrinsic. This pass supports
1283 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1284 // to be run at link time if CFI is enabled. This pass does nothing if
1285 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001286 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001287
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001288 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1289 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1290 if (EnableHotColdSplit)
1291 MPM.addPass(HotColdSplittingPass());
1292
Davide Italiano089a9122017-01-24 00:57:39 +00001293 // Add late LTO optimization passes.
1294 // Delete basic blocks, which optimization passes may have killed.
1295 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1296
1297 // Drop bodies of available eternally objects to improve GlobalDCE.
1298 MPM.addPass(EliminateAvailableExternallyPass());
1299
1300 // Now that we have optimized the program, discard unreachable functions.
1301 MPM.addPass(GlobalDCEPass());
1302
Eric Christopher86e2f162019-05-03 00:15:23 +00001303 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001304 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001305}
1306
Chandler Carruth060ad612016-12-23 20:38:19 +00001307AAManager PassBuilder::buildDefaultAAPipeline() {
1308 AAManager AA;
1309
1310 // The order in which these are registered determines their priority when
1311 // being queried.
1312
1313 // First we register the basic alias analysis that provides the majority of
1314 // per-function local AA logic. This is a stateless, on-demand local set of
1315 // AA techniques.
1316 AA.registerFunctionAnalysis<BasicAA>();
1317
1318 // Next we query fast, specialized alias analyses that wrap IR-embedded
1319 // information about aliasing.
1320 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1321 AA.registerFunctionAnalysis<TypeBasedAA>();
1322
1323 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001324 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1325 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001326 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001327 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001328
1329 return AA;
1330}
1331
Chandler Carruth241bf242016-08-03 07:44:48 +00001332static Optional<int> parseRepeatPassName(StringRef Name) {
1333 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1334 return None;
1335 int Count;
1336 if (Name.getAsInteger(0, Count) || Count <= 0)
1337 return None;
1338 return Count;
1339}
1340
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001341static Optional<int> parseDevirtPassName(StringRef Name) {
1342 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1343 return None;
1344 int Count;
1345 if (Name.getAsInteger(0, Count) || Count <= 0)
1346 return None;
1347 return Count;
1348}
1349
Fedor Sergeevb7871402019-01-10 10:01:53 +00001350static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1351 if (!Name.consume_front(PassName))
1352 return false;
1353 // normal pass name w/o parameters == default parameters
1354 if (Name.empty())
1355 return true;
1356 return Name.startswith("<") && Name.endswith(">");
1357}
1358
1359namespace {
1360
1361/// This performs customized parsing of pass name with parameters.
1362///
1363/// We do not need parametrization of passes in textual pipeline very often,
1364/// yet on a rare occasion ability to specify parameters right there can be
1365/// useful.
1366///
1367/// \p Name - parameterized specification of a pass from a textual pipeline
1368/// is a string in a form of :
1369/// PassName '<' parameter-list '>'
1370///
1371/// Parameter list is being parsed by the parser callable argument, \p Parser,
1372/// It takes a string-ref of parameters and returns either StringError or a
1373/// parameter list in a form of a custom parameters type, all wrapped into
1374/// Expected<> template class.
1375///
1376template <typename ParametersParseCallableT>
1377auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1378 StringRef PassName) -> decltype(Parser(StringRef{})) {
1379 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1380
1381 StringRef Params = Name;
1382 if (!Params.consume_front(PassName)) {
1383 assert(false &&
1384 "unable to strip pass name from parametrized pass specification");
1385 }
1386 if (Params.empty())
1387 return ParametersT{};
1388 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1389 assert(false && "invalid format for parametrized pass name");
1390 }
1391
1392 Expected<ParametersT> Result = Parser(Params);
1393 assert((Result || Result.template errorIsA<StringError>()) &&
1394 "Pass parameter parser can only return StringErrors.");
1395 return std::move(Result);
1396}
1397
1398/// Parser of parameters for LoopUnroll pass.
1399Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1400 LoopUnrollOptions UnrollOpts;
1401 while (!Params.empty()) {
1402 StringRef ParamName;
1403 std::tie(ParamName, Params) = Params.split(';');
1404 int OptLevel = StringSwitch<int>(ParamName)
1405 .Case("O0", 0)
1406 .Case("O1", 1)
1407 .Case("O2", 2)
1408 .Case("O3", 3)
1409 .Default(-1);
1410 if (OptLevel >= 0) {
1411 UnrollOpts.setOptLevel(OptLevel);
1412 continue;
1413 }
1414
1415 bool Enable = !ParamName.consume_front("no-");
1416 if (ParamName == "partial") {
1417 UnrollOpts.setPartial(Enable);
1418 } else if (ParamName == "peeling") {
1419 UnrollOpts.setPeeling(Enable);
1420 } else if (ParamName == "runtime") {
1421 UnrollOpts.setRuntime(Enable);
1422 } else if (ParamName == "upperbound") {
1423 UnrollOpts.setUpperBound(Enable);
1424 } else {
1425 return make_error<StringError>(
1426 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1427 inconvertibleErrorCode());
1428 }
1429 }
1430 return UnrollOpts;
1431}
1432
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001433Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1434 MemorySanitizerOptions Result;
1435 while (!Params.empty()) {
1436 StringRef ParamName;
1437 std::tie(ParamName, Params) = Params.split(';');
1438
1439 if (ParamName == "recover") {
1440 Result.Recover = true;
1441 } else if (ParamName == "kernel") {
1442 Result.Kernel = true;
1443 } else if (ParamName.consume_front("track-origins=")) {
1444 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1445 return make_error<StringError>(
1446 formatv("invalid argument to MemorySanitizer pass track-origins "
1447 "parameter: '{0}' ",
1448 ParamName)
1449 .str(),
1450 inconvertibleErrorCode());
1451 } else {
1452 return make_error<StringError>(
1453 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1454 .str(),
1455 inconvertibleErrorCode());
1456 }
1457 }
1458 return Result;
1459}
1460
Serguei Katkovf5432832019-04-15 08:57:53 +00001461/// Parser of parameters for SimplifyCFG pass.
1462Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1463 SimplifyCFGOptions Result;
1464 while (!Params.empty()) {
1465 StringRef ParamName;
1466 std::tie(ParamName, Params) = Params.split(';');
1467
1468 bool Enable = !ParamName.consume_front("no-");
1469 if (ParamName == "forward-switch-cond") {
1470 Result.forwardSwitchCondToPhi(Enable);
1471 } else if (ParamName == "switch-to-lookup") {
1472 Result.convertSwitchToLookupTable(Enable);
1473 } else if (ParamName == "keep-loops") {
1474 Result.needCanonicalLoops(Enable);
1475 } else if (ParamName == "sink-common-insts") {
1476 Result.sinkCommonInsts(Enable);
1477 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1478 APInt BonusInstThreshold;
1479 if (ParamName.getAsInteger(0, BonusInstThreshold))
1480 return make_error<StringError>(
1481 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1482 "parameter: '{0}' ",
1483 ParamName).str(),
1484 inconvertibleErrorCode());
1485 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1486 } else {
1487 return make_error<StringError>(
1488 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1489 inconvertibleErrorCode());
1490 }
1491 }
1492 return Result;
1493}
1494
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001495/// Parser of parameters for LoopVectorize pass.
1496Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1497 LoopVectorizeOptions Opts;
1498 while (!Params.empty()) {
1499 StringRef ParamName;
1500 std::tie(ParamName, Params) = Params.split(';');
1501
1502 bool Enable = !ParamName.consume_front("no-");
1503 if (ParamName == "interleave-forced-only") {
1504 Opts.setInterleaveOnlyWhenForced(Enable);
1505 } else if (ParamName == "vectorize-forced-only") {
1506 Opts.setVectorizeOnlyWhenForced(Enable);
1507 } else {
1508 return make_error<StringError>(
1509 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1510 inconvertibleErrorCode());
1511 }
1512 }
1513 return Opts;
1514}
1515
Serguei Katkov40a3b962019-04-22 10:35:07 +00001516Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1517 bool Result = false;
1518 while (!Params.empty()) {
1519 StringRef ParamName;
1520 std::tie(ParamName, Params) = Params.split(';');
1521
1522 bool Enable = !ParamName.consume_front("no-");
1523 if (ParamName == "nontrivial") {
1524 Result = Enable;
1525 } else {
1526 return make_error<StringError>(
1527 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1528 .str(),
1529 inconvertibleErrorCode());
1530 }
1531 }
1532 return Result;
1533}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001534} // namespace
1535
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001536/// Tests whether a pass name starts with a valid prefix for a default pipeline
1537/// alias.
1538static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1539 return Name.startswith("default") || Name.startswith("thinlto") ||
1540 Name.startswith("lto");
1541}
1542
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001543/// Tests whether registered callbacks will accept a given pass name.
1544///
1545/// When parsing a pipeline text, the type of the outermost pipeline may be
1546/// omitted, in which case the type is automatically determined from the first
1547/// pass name in the text. This may be a name that is handled through one of the
1548/// callbacks. We check this through the oridinary parsing callbacks by setting
1549/// up a dummy PassManager in order to not force the client to also handle this
1550/// type of query.
1551template <typename PassManagerT, typename CallbacksT>
1552static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1553 if (!Callbacks.empty()) {
1554 PassManagerT DummyPM;
1555 for (auto &CB : Callbacks)
1556 if (CB(Name, DummyPM, {}))
1557 return true;
1558 }
1559 return false;
1560}
1561
1562template <typename CallbacksT>
1563static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001564 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001565 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001566 return DefaultAliasRegex.match(Name);
1567
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001568 // Explicitly handle pass manager names.
1569 if (Name == "module")
1570 return true;
1571 if (Name == "cgscc")
1572 return true;
1573 if (Name == "function")
1574 return true;
1575
Chandler Carruth241bf242016-08-03 07:44:48 +00001576 // Explicitly handle custom-parsed pass names.
1577 if (parseRepeatPassName(Name))
1578 return true;
1579
Chandler Carruth74a8a222016-06-17 07:15:29 +00001580#define MODULE_PASS(NAME, CREATE_PASS) \
1581 if (Name == NAME) \
1582 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001583#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001584 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001585 return true;
1586#include "PassRegistry.def"
1587
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001588 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001589}
1590
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001591template <typename CallbacksT>
1592static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001593 // Explicitly handle pass manager names.
1594 if (Name == "cgscc")
1595 return true;
1596 if (Name == "function")
1597 return true;
1598
Chandler Carruth241bf242016-08-03 07:44:48 +00001599 // Explicitly handle custom-parsed pass names.
1600 if (parseRepeatPassName(Name))
1601 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001602 if (parseDevirtPassName(Name))
1603 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001604
Chandler Carruth74a8a222016-06-17 07:15:29 +00001605#define CGSCC_PASS(NAME, CREATE_PASS) \
1606 if (Name == NAME) \
1607 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001608#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001609 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001610 return true;
1611#include "PassRegistry.def"
1612
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001613 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001614}
1615
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001616template <typename CallbacksT>
1617static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001618 // Explicitly handle pass manager names.
1619 if (Name == "function")
1620 return true;
1621 if (Name == "loop")
1622 return true;
1623
Chandler Carruth241bf242016-08-03 07:44:48 +00001624 // Explicitly handle custom-parsed pass names.
1625 if (parseRepeatPassName(Name))
1626 return true;
1627
Chandler Carruth74a8a222016-06-17 07:15:29 +00001628#define FUNCTION_PASS(NAME, CREATE_PASS) \
1629 if (Name == NAME) \
1630 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001631#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1632 if (checkParametrizedPassName(Name, NAME)) \
1633 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001634#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001635 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001636 return true;
1637#include "PassRegistry.def"
1638
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001639 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001640}
1641
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001642template <typename CallbacksT>
1643static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001644 // Explicitly handle pass manager names.
1645 if (Name == "loop")
1646 return true;
1647
Chandler Carruth241bf242016-08-03 07:44:48 +00001648 // Explicitly handle custom-parsed pass names.
1649 if (parseRepeatPassName(Name))
1650 return true;
1651
Chandler Carruth74a8a222016-06-17 07:15:29 +00001652#define LOOP_PASS(NAME, CREATE_PASS) \
1653 if (Name == NAME) \
1654 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001655#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1656 if (checkParametrizedPassName(Name, NAME)) \
1657 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001658#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1659 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1660 return true;
1661#include "PassRegistry.def"
1662
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001663 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001664}
1665
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001666Optional<std::vector<PassBuilder::PipelineElement>>
1667PassBuilder::parsePipelineText(StringRef Text) {
1668 std::vector<PipelineElement> ResultPipeline;
1669
1670 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1671 &ResultPipeline};
1672 for (;;) {
1673 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1674 size_t Pos = Text.find_first_of(",()");
1675 Pipeline.push_back({Text.substr(0, Pos), {}});
1676
1677 // If we have a single terminating name, we're done.
1678 if (Pos == Text.npos)
1679 break;
1680
1681 char Sep = Text[Pos];
1682 Text = Text.substr(Pos + 1);
1683 if (Sep == ',')
1684 // Just a name ending in a comma, continue.
1685 continue;
1686
1687 if (Sep == '(') {
1688 // Push the inner pipeline onto the stack to continue processing.
1689 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1690 continue;
1691 }
1692
1693 assert(Sep == ')' && "Bogus separator!");
1694 // When handling the close parenthesis, we greedily consume them to avoid
1695 // empty strings in the pipeline.
1696 do {
1697 // If we try to pop the outer pipeline we have unbalanced parentheses.
1698 if (PipelineStack.size() == 1)
1699 return None;
1700
1701 PipelineStack.pop_back();
1702 } while (Text.consume_front(")"));
1703
1704 // Check if we've finished parsing.
1705 if (Text.empty())
1706 break;
1707
1708 // Otherwise, the end of an inner pipeline always has to be followed by
1709 // a comma, and then we can continue.
1710 if (!Text.consume_front(","))
1711 return None;
1712 }
1713
1714 if (PipelineStack.size() > 1)
1715 // Unbalanced paretheses.
1716 return None;
1717
1718 assert(PipelineStack.back() == &ResultPipeline &&
1719 "Wrong pipeline at the bottom of the stack!");
1720 return {std::move(ResultPipeline)};
1721}
1722
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001723Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1724 const PipelineElement &E,
1725 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001726 auto &Name = E.Name;
1727 auto &InnerPipeline = E.InnerPipeline;
1728
1729 // First handle complex passes like the pass managers which carry pipelines.
1730 if (!InnerPipeline.empty()) {
1731 if (Name == "module") {
1732 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001733 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1734 VerifyEachPass, DebugLogging))
1735 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001736 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001737 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001738 }
1739 if (Name == "cgscc") {
1740 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001741 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1742 DebugLogging))
1743 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001744 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001745 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001746 }
1747 if (Name == "function") {
1748 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001749 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1750 VerifyEachPass, DebugLogging))
1751 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001752 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001753 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001754 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001755 if (auto Count = parseRepeatPassName(Name)) {
1756 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001757 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1758 VerifyEachPass, DebugLogging))
1759 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001760 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001761 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001762 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001763
1764 for (auto &C : ModulePipelineParsingCallbacks)
1765 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001766 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001767
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001768 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001769 return make_error<StringError>(
1770 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1771 inconvertibleErrorCode());
1772 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001773 }
1774
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001775 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001776 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001777 SmallVector<StringRef, 3> Matches;
1778 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001779 return make_error<StringError>(
1780 formatv("unknown default pipeline alias '{0}'", Name).str(),
1781 inconvertibleErrorCode());
1782
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001783 assert(Matches.size() == 3 && "Must capture two matched strings!");
1784
Jordan Rosef85a95f2016-07-25 18:34:51 +00001785 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001786 .Case("O0", O0)
1787 .Case("O1", O1)
1788 .Case("O2", O2)
1789 .Case("O3", O3)
1790 .Case("Os", Os)
1791 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001792 if (L == O0)
1793 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001794 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001795
1796 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001797 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001798 } else if (Matches[1] == "thinlto-pre-link") {
1799 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1800 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001801 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001802 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001803 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001804 } else {
1805 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001806 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001807 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001808 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001809 }
1810
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001811 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001812#define MODULE_PASS(NAME, CREATE_PASS) \
1813 if (Name == NAME) { \
1814 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001815 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001816 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001817#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1818 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001819 MPM.addPass( \
1820 RequireAnalysisPass< \
1821 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001822 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001823 } \
1824 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001825 MPM.addPass(InvalidateAnalysisPass< \
1826 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001827 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001828 }
1829#include "PassRegistry.def"
1830
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001831 for (auto &C : ModulePipelineParsingCallbacks)
1832 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001833 return Error::success();
1834 return make_error<StringError>(
1835 formatv("unknown module pass '{0}'", Name).str(),
1836 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001837}
1838
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001839Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1840 const PipelineElement &E, bool VerifyEachPass,
1841 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001842 auto &Name = E.Name;
1843 auto &InnerPipeline = E.InnerPipeline;
1844
1845 // First handle complex passes like the pass managers which carry pipelines.
1846 if (!InnerPipeline.empty()) {
1847 if (Name == "cgscc") {
1848 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001849 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1850 VerifyEachPass, DebugLogging))
1851 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001852 // Add the nested pass manager with the appropriate adaptor.
1853 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001854 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001855 }
1856 if (Name == "function") {
1857 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001858 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1859 VerifyEachPass, DebugLogging))
1860 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001861 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001862 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001863 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001864 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001865 if (auto Count = parseRepeatPassName(Name)) {
1866 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001867 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1868 VerifyEachPass, DebugLogging))
1869 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001870 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001871 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001872 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001873 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1874 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001875 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1876 VerifyEachPass, DebugLogging))
1877 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001878 CGPM.addPass(
1879 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001880 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001881 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001882
1883 for (auto &C : CGSCCPipelineParsingCallbacks)
1884 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001885 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001886
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001887 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001888 return make_error<StringError>(
1889 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1890 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001891 }
1892
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001893// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001894#define CGSCC_PASS(NAME, CREATE_PASS) \
1895 if (Name == NAME) { \
1896 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001897 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001898 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001899#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1900 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001901 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001902 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001903 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1904 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001905 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001906 } \
1907 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001908 CGPM.addPass(InvalidateAnalysisPass< \
1909 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001910 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001911 }
1912#include "PassRegistry.def"
1913
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001914 for (auto &C : CGSCCPipelineParsingCallbacks)
1915 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001916 return Error::success();
1917 return make_error<StringError>(
1918 formatv("unknown cgscc pass '{0}'", Name).str(),
1919 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001920}
1921
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001922Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1923 const PipelineElement &E,
1924 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001925 auto &Name = E.Name;
1926 auto &InnerPipeline = E.InnerPipeline;
1927
1928 // First handle complex passes like the pass managers which carry pipelines.
1929 if (!InnerPipeline.empty()) {
1930 if (Name == "function") {
1931 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001932 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1933 VerifyEachPass, DebugLogging))
1934 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001935 // Add the nested pass manager with the appropriate adaptor.
1936 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001937 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001938 }
1939 if (Name == "loop") {
1940 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001941 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1942 DebugLogging))
1943 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001944 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001945 FPM.addPass(
1946 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001947 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001948 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001949 if (auto Count = parseRepeatPassName(Name)) {
1950 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001951 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1952 VerifyEachPass, DebugLogging))
1953 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001954 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001955 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001956 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001957
1958 for (auto &C : FunctionPipelineParsingCallbacks)
1959 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001960 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001961
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001962 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001963 return make_error<StringError>(
1964 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1965 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001966 }
1967
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001968// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001969#define FUNCTION_PASS(NAME, CREATE_PASS) \
1970 if (Name == NAME) { \
1971 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001972 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001973 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001974#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1975 if (checkParametrizedPassName(Name, NAME)) { \
1976 auto Params = parsePassParameters(PARSER, Name, NAME); \
1977 if (!Params) \
1978 return Params.takeError(); \
1979 FPM.addPass(CREATE_PASS(Params.get())); \
1980 return Error::success(); \
1981 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001982#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1983 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001984 FPM.addPass( \
1985 RequireAnalysisPass< \
1986 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001987 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001988 } \
1989 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001990 FPM.addPass(InvalidateAnalysisPass< \
1991 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001992 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001993 }
1994#include "PassRegistry.def"
1995
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001996 for (auto &C : FunctionPipelineParsingCallbacks)
1997 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001998 return Error::success();
1999 return make_error<StringError>(
2000 formatv("unknown function pass '{0}'", Name).str(),
2001 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002002}
2003
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002004Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2005 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002006 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002007 auto &InnerPipeline = E.InnerPipeline;
2008
2009 // First handle complex passes like the pass managers which carry pipelines.
2010 if (!InnerPipeline.empty()) {
2011 if (Name == "loop") {
2012 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002013 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2014 VerifyEachPass, DebugLogging))
2015 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002016 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002017 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002018 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002019 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002020 if (auto Count = parseRepeatPassName(Name)) {
2021 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002022 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2023 VerifyEachPass, DebugLogging))
2024 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002025 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002026 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002027 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002028
2029 for (auto &C : LoopPipelineParsingCallbacks)
2030 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002031 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002032
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002033 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002034 return make_error<StringError>(
2035 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2036 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002037 }
2038
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002039// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002040#define LOOP_PASS(NAME, CREATE_PASS) \
2041 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002042 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002043 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002044 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002045#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2046 if (checkParametrizedPassName(Name, NAME)) { \
2047 auto Params = parsePassParameters(PARSER, Name, NAME); \
2048 if (!Params) \
2049 return Params.takeError(); \
2050 LPM.addPass(CREATE_PASS(Params.get())); \
2051 return Error::success(); \
2052 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002053#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2054 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002055 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002056 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2057 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2058 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002059 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002060 } \
2061 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002062 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002063 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002064 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002065 }
2066#include "PassRegistry.def"
2067
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002068 for (auto &C : LoopPipelineParsingCallbacks)
2069 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002070 return Error::success();
2071 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2072 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002073}
2074
Chandler Carruthedf59962016-02-18 09:45:17 +00002075bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002076#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2077 if (Name == NAME) { \
2078 AA.registerModuleAnalysis< \
2079 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2080 return true; \
2081 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002082#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2083 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002084 AA.registerFunctionAnalysis< \
2085 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002086 return true; \
2087 }
2088#include "PassRegistry.def"
2089
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002090 for (auto &C : AAParsingCallbacks)
2091 if (C(Name, AA))
2092 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002093 return false;
2094}
2095
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002096Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002097 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002098 bool VerifyEachPass,
2099 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002100 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002101 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2102 return Err;
2103 // FIXME: No verifier support for Loop passes!
2104 }
2105 return Error::success();
2106}
2107
2108Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2109 ArrayRef<PipelineElement> Pipeline,
2110 bool VerifyEachPass,
2111 bool DebugLogging) {
2112 for (const auto &Element : Pipeline) {
2113 if (auto Err =
2114 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2115 return Err;
2116 if (VerifyEachPass)
2117 FPM.addPass(VerifierPass());
2118 }
2119 return Error::success();
2120}
2121
2122Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2123 ArrayRef<PipelineElement> Pipeline,
2124 bool VerifyEachPass,
2125 bool DebugLogging) {
2126 for (const auto &Element : Pipeline) {
2127 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2128 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002129 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002130 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002131 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002132}
2133
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002134void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2135 FunctionAnalysisManager &FAM,
2136 CGSCCAnalysisManager &CGAM,
2137 ModuleAnalysisManager &MAM) {
2138 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2139 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002140 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2141 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2142 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2143 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2144 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2145}
2146
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002147Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2148 ArrayRef<PipelineElement> Pipeline,
2149 bool VerifyEachPass,
2150 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002151 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002152 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2153 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002154 if (VerifyEachPass)
2155 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002156 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002157 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002158}
2159
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002160// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002161// FIXME: Should this routine accept a TargetMachine or require the caller to
2162// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002163Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2164 StringRef PipelineText,
2165 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002166 auto Pipeline = parsePipelineText(PipelineText);
2167 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002168 return make_error<StringError>(
2169 formatv("invalid pipeline '{0}'", PipelineText).str(),
2170 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002171
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002172 // If the first name isn't at the module layer, wrap the pipeline up
2173 // automatically.
2174 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002175
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002176 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2177 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002178 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002179 } else if (isFunctionPassName(FirstName,
2180 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002181 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002182 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002183 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002184 } else {
2185 for (auto &C : TopLevelPipelineParsingCallbacks)
2186 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002187 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002188
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002189 // Unknown pass or pipeline name!
2190 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2191 return make_error<StringError>(
2192 formatv("unknown {0} name '{1}'",
2193 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2194 .str(),
2195 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002196 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002197 }
2198
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002199 if (auto Err =
2200 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2201 return Err;
2202 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002203}
Chandler Carruthedf59962016-02-18 09:45:17 +00002204
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002205// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002206Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2207 StringRef PipelineText,
2208 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002209 auto Pipeline = parsePipelineText(PipelineText);
2210 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002211 return make_error<StringError>(
2212 formatv("invalid pipeline '{0}'", PipelineText).str(),
2213 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002214
2215 StringRef FirstName = Pipeline->front().Name;
2216 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002217 return make_error<StringError>(
2218 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2219 PipelineText)
2220 .str(),
2221 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002222
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002223 if (auto Err =
2224 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2225 return Err;
2226 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002227}
2228
2229// Primary pass pipeline description parsing routine for a \c
2230// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002231Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2232 StringRef PipelineText,
2233 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002234 auto Pipeline = parsePipelineText(PipelineText);
2235 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002236 return make_error<StringError>(
2237 formatv("invalid pipeline '{0}'", PipelineText).str(),
2238 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002239
2240 StringRef FirstName = Pipeline->front().Name;
2241 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002242 return make_error<StringError>(
2243 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2244 PipelineText)
2245 .str(),
2246 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002247
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002248 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2249 DebugLogging))
2250 return Err;
2251 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002252}
2253
2254// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002255Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2256 StringRef PipelineText,
2257 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002258 auto Pipeline = parsePipelineText(PipelineText);
2259 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002260 return make_error<StringError>(
2261 formatv("invalid pipeline '{0}'", PipelineText).str(),
2262 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002263
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002264 if (auto Err =
2265 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2266 return Err;
2267
2268 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002269}
2270
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002271Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002272 // If the pipeline just consists of the word 'default' just replace the AA
2273 // manager with our default one.
2274 if (PipelineText == "default") {
2275 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002276 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002277 }
2278
Chandler Carruthedf59962016-02-18 09:45:17 +00002279 while (!PipelineText.empty()) {
2280 StringRef Name;
2281 std::tie(Name, PipelineText) = PipelineText.split(',');
2282 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002283 return make_error<StringError>(
2284 formatv("unknown alias analysis name '{0}'", Name).str(),
2285 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002286 }
2287
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002288 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002289}