blob: bfa3ecfb2806024eacbccc4e420effd635a37c59 [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"
Bardia Mahjourdb800c22019-09-18 17:43:45 +000030#include "llvm/Analysis/DDG.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000031#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000032#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000033#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000034#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000035#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000036#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000037#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000038#include "llvm/Analysis/LoopAccessAnalysis.h"
Whitney Tsangdd3b6492019-08-09 13:56:29 +000039#include "llvm/Analysis/LoopCacheAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000040#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000041#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000042#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000043#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000044#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000045#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000046#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000047#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000048#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000049#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000050#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000051#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000052#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000053#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000054#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000055#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Yuanfang Chencc382cf2019-09-30 17:54:50 +000056#include "llvm/CodeGen/MachineModuleInfo.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000057#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000058#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000059#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000060#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000061#include "llvm/IR/PassManager.h"
Fedor Sergeeva2ed4482019-03-31 10:15:39 +000062#include "llvm/IR/SafepointIRVerifier.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000063#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000064#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000065#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000066#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000067#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000068#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000069#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000070#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Johannes Doerfertaade7822019-06-05 03:02:24 +000071#include "llvm/Transforms/IPO/Attributor.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000072#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000073#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000074#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000075#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000076#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000077#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000078#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000079#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000080#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000081#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000082#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000083#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000084#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000085#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000086#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000087#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000088#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000089#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000090#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000091#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000092#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000093#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000094#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000095#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000096#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000097#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000098#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000099#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000100#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000101#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Manman Ren18295122019-02-28 20:13:38 +0000102#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000103#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +0000104#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000105#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Philip Reamesf47a3132019-07-09 18:49:29 +0000106#include "llvm/Transforms/Instrumentation/PoisonChecking.h"
Leonard Chan007f6742019-07-25 20:53:15 +0000107#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000108#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000109#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000110#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000111#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000112#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000113#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000114#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000115#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000116#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000117#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000118#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000119#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000120#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000121#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000122#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000123#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000124#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000125#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000126#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000127#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000128#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000129#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000130#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000131#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000132#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000133#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000134#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000135#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000136#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000137#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000138#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000139#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000140#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000141#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000142#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000143#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000144#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000145#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000146#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000147#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000148#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000149#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Leonard Chanbb147aa2019-07-15 23:18:31 +0000150#include "llvm/Transforms/Scalar/MergeICmps.h"
Leonard Chan007f6742019-07-25 20:53:15 +0000151#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000152#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000153#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000154#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000155#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000156#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000157#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000158#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000159#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000160#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000161#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000162#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000163#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000164#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000165#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000166#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000167#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000168#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000169#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000170#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000171#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000172#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000173#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000174#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000175#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000176#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000177#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000178#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000179#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000180#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000181
Chandler Carruth66445382014-01-11 08:16:35 +0000182using namespace llvm;
183
Chandler Carruth719ffe12017-02-12 05:38:04 +0000184static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
185 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000186static cl::opt<bool>
187 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
188 cl::Hidden, cl::ZeroOrMore,
189 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000190
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000191static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000192 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000193 cl::Hidden, cl::ZeroOrMore,
194 cl::desc("Run NewGVN instead of GVN"));
195
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000196static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000197 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
198 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000199
Davide Italianobe1b6a92017-06-03 23:18:29 +0000200static cl::opt<bool> EnableGVNSink(
201 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
202 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
203
David Green963401d2018-07-01 12:47:30 +0000204static cl::opt<bool> EnableUnrollAndJam(
205 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
206 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
207
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000208static cl::opt<bool> EnableSyntheticCounts(
209 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
210 cl::desc("Run synthetic function entry count generation "
211 "pass"));
212
Thomas Preud'homme5f738942019-09-24 14:42:36 +0000213static const Regex DefaultAliasRegex(
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000214 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000215
Eric Christophereff3b6f2019-04-18 06:17:40 +0000216// This option is used in simplifying testing SampleFDO optimizations for
217// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000218static cl::opt<bool>
219 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
220 cl::desc("Enable control height reduction optimization (CHR)"));
221
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000222PipelineTuningOptions::PipelineTuningOptions() {
223 LoopInterleaving = EnableLoopInterleaving;
224 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea458c7332019-05-08 17:58:35 +0000225 SLPVectorization = RunSLPVectorization;
Alina Sbirleae4b27862019-05-23 19:35:40 +0000226 LoopUnrolling = true;
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000227 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000228 LicmMssaOptCap = SetLicmMssaOptCap;
229 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000230}
231
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000232extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000233extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000234
Wei Mi3bcccdf2019-01-17 20:48:34 +0000235extern cl::opt<bool> FlattenedProfileUsed;
236
Chandler Carruthe3f50642016-12-22 06:59:15 +0000237static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
238 switch (Level) {
239 case PassBuilder::O0:
240 case PassBuilder::O1:
241 case PassBuilder::O2:
242 case PassBuilder::O3:
243 return false;
244
245 case PassBuilder::Os:
246 case PassBuilder::Oz:
247 return true;
248 }
249 llvm_unreachable("Invalid optimization level!");
250}
251
Chandler Carruth66445382014-01-11 08:16:35 +0000252namespace {
253
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000254/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000255struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000256 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000257 return PreservedAnalyses::all();
258 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000259 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000260};
261
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000262/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000263class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
264 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000265 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000266
267public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000268 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000269 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000270 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000271};
272
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000273/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000274struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000275 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
276 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000277 return PreservedAnalyses::all();
278 }
279 static StringRef name() { return "NoOpCGSCCPass"; }
280};
281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000282/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000283class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
284 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000285 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000286
287public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000288 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000289 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000290 return Result();
291 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000292 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000293};
294
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000295/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000296struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000297 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000298 return PreservedAnalyses::all();
299 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000300 static StringRef name() { return "NoOpFunctionPass"; }
301};
302
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000303/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000304class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
305 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000306 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000307
308public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000309 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000310 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000311 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000312};
313
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000314/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000315struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000316 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
317 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000318 return PreservedAnalyses::all();
319 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000320 static StringRef name() { return "NoOpLoopPass"; }
321};
322
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000323/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000324class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
325 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000326 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000327
328public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000329 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000330 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
331 return Result();
332 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000333 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000334};
335
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000336AnalysisKey NoOpModuleAnalysis::Key;
337AnalysisKey NoOpCGSCCAnalysis::Key;
338AnalysisKey NoOpFunctionAnalysis::Key;
339AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000340
Chandler Carruth66445382014-01-11 08:16:35 +0000341} // End anonymous namespace.
342
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000343void PassBuilder::invokePeepholeEPCallbacks(
344 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
345 for (auto &C : PeepholeEPCallbacks)
346 C(FPM, Level);
347}
348
Chandler Carruth1ff77242015-03-07 09:02:36 +0000349void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000350#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000351 MAM.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 : ModuleAnalysisRegistrationCallbacks)
355 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000356}
357
Chandler Carruth1ff77242015-03-07 09:02:36 +0000358void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000359#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000360 CGAM.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 : CGSCCAnalysisRegistrationCallbacks)
364 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000365}
366
Chandler Carruth1ff77242015-03-07 09:02:36 +0000367void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000368#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000369 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000370#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000371
372 for (auto &C : FunctionAnalysisRegistrationCallbacks)
373 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000374}
375
Justin Bognereecc3c82016-02-25 07:23:08 +0000376void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000377#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000378 LAM.registerPass([&] { return CREATE_PASS; });
379#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000380
381 for (auto &C : LoopAnalysisRegistrationCallbacks)
382 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000383}
384
Chandler Carruthe3f50642016-12-22 06:59:15 +0000385FunctionPassManager
386PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000387 ThinLTOPhase Phase,
388 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000389 assert(Level != O0 && "Must request optimizations!");
390 FunctionPassManager FPM(DebugLogging);
391
392 // Form SSA out of local memory accesses after breaking apart aggregates into
393 // scalars.
394 FPM.addPass(SROA());
395
396 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000397 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000398
Davide Italianoc3688312017-06-01 23:08:14 +0000399 // Hoisting of scalars and load expressions.
400 if (EnableGVNHoist)
401 FPM.addPass(GVNHoistPass());
402
Davide Italianobe1b6a92017-06-03 23:18:29 +0000403 // Global value numbering based sinking.
404 if (EnableGVNSink) {
405 FPM.addPass(GVNSinkPass());
406 FPM.addPass(SimplifyCFGPass());
407 }
408
Chandler Carruthe3f50642016-12-22 06:59:15 +0000409 // Speculative execution if the target has divergent branches; otherwise nop.
410 FPM.addPass(SpeculativeExecutionPass());
411
412 // Optimize based on known information about branches, and cleanup afterward.
413 FPM.addPass(JumpThreadingPass());
414 FPM.addPass(CorrelatedValuePropagationPass());
415 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000416 if (Level == O3)
417 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000418 FPM.addPass(InstCombinePass());
419
420 if (!isOptimizingForSize(Level))
421 FPM.addPass(LibCallsShrinkWrapPass());
422
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000423 invokePeepholeEPCallbacks(FPM, Level);
424
Rong Xue1f42452017-10-23 22:21:29 +0000425 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
426 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000427 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000428 !isOptimizingForSize(Level))
429 FPM.addPass(PGOMemOPSizeOpt());
430
Chandler Carruthe3f50642016-12-22 06:59:15 +0000431 FPM.addPass(TailCallElimPass());
432 FPM.addPass(SimplifyCFGPass());
433
434 // Form canonically associated expression trees, and simplify the trees using
435 // basic mathematical properties. For example, this will form (nearly)
436 // minimal multiplication trees.
437 FPM.addPass(ReassociatePass());
438
439 // Add the primary loop simplification pipeline.
440 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000441 // some function passes in between them. These can and should be removed
442 // and/or replaced by scheduling the loop pass equivalents in the correct
443 // positions. But those equivalent passes aren't powerful enough yet.
444 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
445 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
446 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
447 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000448 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
449
Chandler Carruth71fd2702018-05-30 02:46:45 +0000450 // Simplify the loop body. We do this initially to clean up after other loop
451 // passes run, either when iterating on a loop or on inner loops with
452 // implications on the outer loop.
453 LPM1.addPass(LoopInstSimplifyPass());
454 LPM1.addPass(LoopSimplifyCFGPass());
455
Chandler Carruthe3f50642016-12-22 06:59:15 +0000456 // Rotate Loop - disable header duplication at -Oz
457 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000458 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000459 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000460 LPM2.addPass(IndVarSimplifyPass());
461 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000462
463 for (auto &C : LateLoopOptimizationsEPCallbacks)
464 C(LPM2, Level);
465
Chandler Carruth79b733b2017-01-26 23:21:17 +0000466 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000467 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000468 // because it changes IR to makes profile annotation in back compile
469 // inaccurate.
Alina Sbirleae4b27862019-05-23 19:35:40 +0000470 if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
471 PGOOpt->Action != PGOOptions::SampleUse) &&
472 PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000473 LPM2.addPass(
474 LoopFullUnrollPass(Level, false, PTO.ForgetAllSCEVInLoopUnroll));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000475
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000476 for (auto &C : LoopOptimizerEndEPCallbacks)
477 C(LPM2, Level);
478
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000479 // We provide the opt remark emitter pass for LICM to use. We only need to do
480 // this once as it is immutable.
481 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea74251792019-08-21 17:00:57 +0000482 FPM.addPass(createFunctionToLoopPassAdaptor(
483 std::move(LPM1), EnableMSSALoopDependency, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000484 FPM.addPass(SimplifyCFGPass());
485 FPM.addPass(InstCombinePass());
Alina Sbirlea74251792019-08-21 17:00:57 +0000486 // The loop passes in LPM2 (IndVarSimplifyPass, LoopIdiomRecognizePass,
487 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
488 // *All* loop passes must preserve it, in order to be able to use it.
489 FPM.addPass(createFunctionToLoopPassAdaptor(
490 std::move(LPM2), /*UseMemorySSA=*/false, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000491
492 // Eliminate redundancies.
493 if (Level != O1) {
494 // These passes add substantial compile time so skip them at O1.
495 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000496 if (RunNewGVN)
497 FPM.addPass(NewGVNPass());
498 else
499 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000500 }
501
502 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
503 FPM.addPass(MemCpyOptPass());
504
505 // Sparse conditional constant propagation.
506 // FIXME: It isn't clear why we do this *after* loop passes rather than
507 // before...
508 FPM.addPass(SCCPPass());
509
510 // Delete dead bit computations (instcombine runs after to fold away the dead
511 // computations, and then ADCE will run later to exploit any new DCE
512 // opportunities that creates).
513 FPM.addPass(BDCEPass());
514
515 // Run instcombine after redundancy and dead bit elimination to exploit
516 // opportunities opened up by them.
517 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000518 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000519
520 // Re-consider control flow based optimizations after redundancy elimination,
521 // redo DCE, etc.
522 FPM.addPass(JumpThreadingPass());
523 FPM.addPass(CorrelatedValuePropagationPass());
524 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000525 FPM.addPass(createFunctionToLoopPassAdaptor(
526 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
Alina Sbirlea74251792019-08-21 17:00:57 +0000527 EnableMSSALoopDependency, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000528
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000529 for (auto &C : ScalarOptimizerLateEPCallbacks)
530 C(FPM, Level);
531
Chandler Carruthe3f50642016-12-22 06:59:15 +0000532 // Finally, do an expensive DCE pass to catch all the dead code exposed by
533 // the simplifications and basic cleanup after all the simplifications.
534 FPM.addPass(ADCEPass());
535 FPM.addPass(SimplifyCFGPass());
536 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000537 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000538
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000539 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000540 (PGOOpt->Action == PGOOptions::IRUse ||
541 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000542 FPM.addPass(ControlHeightReductionPass());
543
Chandler Carruthe3f50642016-12-22 06:59:15 +0000544 return FPM;
545}
546
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000547void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
548 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000549 bool RunProfileGen, bool IsCS,
550 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000551 std::string ProfileRemappingFile) {
Rong Xuca161fa2019-08-01 22:36:34 +0000552 assert(Level != O0 && "Not expecting O0 here!");
Davide Italiano513dfaa2017-02-13 15:26:22 +0000553 // Generally running simplification passes and the inliner with an high
554 // threshold results in smaller executables, but there may be cases where
555 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000556 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
557 // IsCS is true).
558 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000559 InlineParams IP;
560
561 // In the old pass manager, this is a cl::opt. Should still this be one?
562 IP.DefaultThreshold = 75;
563
564 // FIXME: The hint threshold has the same value used by the regular inliner.
565 // This should probably be lowered after performance testing.
566 // FIXME: this comment is cargo culted from the old pass manager, revisit).
567 IP.HintThreshold = 325;
568
569 CGSCCPassManager CGPipeline(DebugLogging);
570
571 CGPipeline.addPass(InlinerPass(IP));
572
573 FunctionPassManager FPM;
574 FPM.addPass(SROA());
575 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
576 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
577 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000578 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000579
Davide Italiano513dfaa2017-02-13 15:26:22 +0000580 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
581
582 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
Rong Xuca161fa2019-08-01 22:36:34 +0000583
584 // Delete anything that is now dead to make sure that we don't instrument
585 // dead code. Instrumentation can end up keeping dead code around and
586 // dramatically increase code size.
587 MPM.addPass(GlobalDCEPass());
Davide Italiano513dfaa2017-02-13 15:26:22 +0000588 }
589
Rong Xuca161fa2019-08-01 22:36:34 +0000590 if (!RunProfileGen) {
591 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
Rong Xudb29a3a2019-03-04 20:21:27 +0000592 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000593 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
594 // RequireAnalysisPass for PSI before subsequent non-module passes.
595 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Rong Xuca161fa2019-08-01 22:36:34 +0000596 return;
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000597 }
Rong Xuca161fa2019-08-01 22:36:34 +0000598
599 // Perform PGO instrumentation.
600 MPM.addPass(PGOInstrumentationGen(IsCS));
601
602 FunctionPassManager FPM;
Alina Sbirlea74251792019-08-21 17:00:57 +0000603 FPM.addPass(createFunctionToLoopPassAdaptor(
604 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
Rong Xuca161fa2019-08-01 22:36:34 +0000605 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
606
607 // Add the profile lowering pass.
608 InstrProfOptions Options;
609 if (!ProfileFile.empty())
610 Options.InstrProfileOutput = ProfileFile;
611 // Do counter promotion at Level greater than O0.
612 Options.DoCounterPromotion = true;
613 Options.UseBFIInPromotion = IsCS;
614 MPM.addPass(InstrProfiling(Options, IsCS));
615}
616
617void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
618 bool DebugLogging, bool RunProfileGen,
619 bool IsCS, std::string ProfileFile,
620 std::string ProfileRemappingFile) {
621 if (!RunProfileGen) {
622 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
623 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
624 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
625 // RequireAnalysisPass for PSI before subsequent non-module passes.
626 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
627 return;
628 }
629
630 // Perform PGO instrumentation.
631 MPM.addPass(PGOInstrumentationGen(IsCS));
632 // Add the profile lowering pass.
633 InstrProfOptions Options;
634 if (!ProfileFile.empty())
635 Options.InstrProfileOutput = ProfileFile;
636 // Do not do counter promotion at O0.
637 Options.DoCounterPromotion = false;
638 Options.UseBFIInPromotion = IsCS;
639 MPM.addPass(InstrProfiling(Options, IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000640}
641
Easwaran Raman8249fac2017-06-28 13:33:49 +0000642static InlineParams
643getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
644 auto O3 = PassBuilder::O3;
645 unsigned OptLevel = Level > O3 ? 2 : Level;
646 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
647 return getInlineParams(OptLevel, SizeLevel);
648}
649
Chandler Carruthe3f50642016-12-22 06:59:15 +0000650ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000651PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000652 ThinLTOPhase Phase,
653 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000654 ModulePassManager MPM(DebugLogging);
655
Rong Xudb29a3a2019-03-04 20:21:27 +0000656 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000657
658 // In ThinLTO mode, when flattened profile is used, all the available
659 // profile information will be annotated in PreLink phase so there is
660 // no need to load the profile again in PostLink.
661 bool LoadSampleProfile =
662 HasSampleProfile &&
663 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
664
665 // During the ThinLTO backend phase we perform early indirect call promotion
666 // here, before globalopt. Otherwise imported available_externally functions
667 // look unreferenced and are removed. If we are going to load the sample
668 // profile then defer until later.
669 // TODO: See if we can move later and consolidate with the location where
670 // we perform ICP when we are loading a sample profile.
671 // TODO: We pass HasSampleProfile (whether there was a sample profile file
672 // passed to the compile) to the SamplePGO flag of ICP. This is used to
673 // determine whether the new direct calls are annotated with prof metadata.
674 // Ideally this should be determined from whether the IR is annotated with
675 // sample profile, and not whether the a sample profile was provided on the
676 // command line. E.g. for flattened profiles where we will not be reloading
677 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
678 // provide the sample profile file.
679 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
680 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
681
Chandler Carruthe3f50642016-12-22 06:59:15 +0000682 // Do basic inference of function attributes from known properties of system
683 // libraries and other oracles.
684 MPM.addPass(InferFunctionAttrsPass());
685
686 // Create an early function pass manager to cleanup the output of the
687 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000688 FunctionPassManager EarlyFPM(DebugLogging);
689 EarlyFPM.addPass(SimplifyCFGPass());
690 EarlyFPM.addPass(SROA());
691 EarlyFPM.addPass(EarlyCSEPass());
692 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000693 if (Level == O3)
694 EarlyFPM.addPass(CallSiteSplittingPass());
695
Dehao Chen08f88312017-08-07 20:23:20 +0000696 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
697 // to convert bitcast to direct calls so that they can be inlined during the
698 // profile annotation prepration step.
699 // More details about SamplePGO design can be found in:
700 // https://research.google.com/pubs/pub45290.html
701 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000702 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000703 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000704 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000705
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000706 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000707 // Annotate sample profile right after early FPM to ensure freshness of
708 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000709 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000710 PGOOpt->ProfileRemappingFile,
711 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000712 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
713 // RequireAnalysisPass for PSI before subsequent non-module passes.
714 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000715 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
716 // for the profile annotation to be accurate in the ThinLTO backend.
717 if (Phase != ThinLTOPhase::PreLink)
718 // We perform early indirect call promotion here, before globalopt.
719 // This is important for the ThinLTO backend phase because otherwise
720 // imported available_externally functions look unreferenced and are
721 // removed.
722 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000723 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000724 }
725
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000726 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000727 // and prior to optimizing globals.
728 // FIXME: This position in the pipeline hasn't been carefully considered in
729 // years, it should be re-analyzed.
730 MPM.addPass(IPSCCPPass());
731
Matthew Simpsoncb585582017-10-25 13:40:08 +0000732 // Attach metadata to indirect call sites indicating the set of functions
733 // they may target at run-time. This should follow IPSCCP.
734 MPM.addPass(CalledValuePropagationPass());
735
Chandler Carruthe3f50642016-12-22 06:59:15 +0000736 // Optimize globals to try and fold them into constants.
737 MPM.addPass(GlobalOptPass());
738
739 // Promote any localized globals to SSA registers.
740 // FIXME: Should this instead by a run of SROA?
741 // FIXME: We should probably run instcombine and simplify-cfg afterward to
742 // delete control flows that are dead once globals have been folded to
743 // constants.
744 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
745
746 // Remove any dead arguments exposed by cleanups and constand folding
747 // globals.
748 MPM.addPass(DeadArgumentEliminationPass());
749
750 // Create a small function pass pipeline to cleanup after all the global
751 // optimizations.
752 FunctionPassManager GlobalCleanupPM(DebugLogging);
753 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000754 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
755
Chandler Carruthe3f50642016-12-22 06:59:15 +0000756 GlobalCleanupPM.addPass(SimplifyCFGPass());
757 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
758
Dehao Chen89d32262017-08-02 01:28:31 +0000759 // Add all the requested passes for instrumentation PGO, if requested.
760 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000761 (PGOOpt->Action == PGOOptions::IRInstr ||
762 PGOOpt->Action == PGOOptions::IRUse)) {
763 addPGOInstrPasses(MPM, DebugLogging, Level,
764 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
765 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000766 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000767 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000768 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000769 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
770 PGOOpt->CSAction == PGOOptions::CSIRInstr)
771 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000772
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000773 // Synthesize function entry counts for non-PGO compilation.
774 if (EnableSyntheticCounts && !PGOOpt)
775 MPM.addPass(SyntheticCountsPropagation());
776
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000777 // Require the GlobalsAA analysis for the module so we can query it within
778 // the CGSCC pipeline.
779 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000780
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000781 // Require the ProfileSummaryAnalysis for the module so we can query it within
782 // the inliner pass.
783 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
784
Chandler Carruthe3f50642016-12-22 06:59:15 +0000785 // Now begin the main postorder CGSCC pipeline.
786 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
787 // manager and trying to emulate its precise behavior. Much of this doesn't
788 // make a lot of sense and we should revisit the core CGSCC structure.
789 CGSCCPassManager MainCGPipeline(DebugLogging);
790
791 // Note: historically, the PruneEH pass was run first to deduce nounwind and
792 // generally clean up exception handling overhead. It isn't clear this is
793 // valuable as the inliner doesn't currently care whether it is inlining an
794 // invoke or a call.
795
796 // Run the inliner first. The theory is that we are walking bottom-up and so
797 // the callees have already been fully optimized, and we want to inline them
798 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000799 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000800 // because it makes profile annotation in the backend inaccurate.
801 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000802 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
803 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000804 IP.HotCallSiteThreshold = 0;
805 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000806
807 // Now deduce any function attributes based in the current code.
808 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
809
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000810 // When at O3 add argument promotion to the pass pipeline.
811 // FIXME: It isn't at all clear why this should be limited to O3.
812 if (Level == O3)
813 MainCGPipeline.addPass(ArgumentPromotionPass());
814
Chandler Carruthe3f50642016-12-22 06:59:15 +0000815 // Lastly, add the core function simplification pipeline nested inside the
816 // CGSCC walk.
817 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000818 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000819
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000820 for (auto &C : CGSCCOptimizerLateEPCallbacks)
821 C(MainCGPipeline, Level);
822
Chandler Carruth719ffe12017-02-12 05:38:04 +0000823 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
824 // to detect when we devirtualize indirect calls and iterate the SCC passes
825 // in that case to try and catch knock-on inlining or function attrs
826 // opportunities. Then we add it to the module pipeline by walking the SCCs
827 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000828 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000829 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000830 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000831
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000832 return MPM;
833}
834
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000835ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
836 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000837 ModulePassManager MPM(DebugLogging);
838
839 // Optimize globals now that the module is fully simplified.
840 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000841 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000842
Xinliang David Li126157c2017-05-22 16:41:57 +0000843 // Run partial inlining pass to partially inline functions that have
844 // large bodies.
845 if (RunPartialInlining)
846 MPM.addPass(PartialInlinerPass());
847
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000848 // Remove avail extern fns and globals definitions since we aren't compiling
849 // an object file for later LTO. For LTO we want to preserve these so they
850 // are eligible for inlining at link-time. Note if they are unreferenced they
851 // will be removed by GlobalDCE later, so this only impacts referenced
852 // available externally globals. Eventually they will be suppressed during
853 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
854 // may make globals referenced by available external functions dead and saves
Leonard Chan97dc6222019-06-20 19:44:51 +0000855 // running remaining passes on the eliminated functions. These should be
856 // preserved during prelinking for link-time inlining decisions.
857 if (!LTOPreLink)
858 MPM.addPass(EliminateAvailableExternallyPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000859
Manman Ren18295122019-02-28 20:13:38 +0000860 if (EnableOrderFileInstrumentation)
861 MPM.addPass(InstrOrderFilePass());
862
Chandler Carruthe3f50642016-12-22 06:59:15 +0000863 // Do RPO function attribute inference across the module to forward-propagate
864 // attributes where applicable.
865 // FIXME: Is this really an optimization rather than a canonicalization?
866 MPM.addPass(ReversePostOrderFunctionAttrsPass());
867
Rong Xudb29a3a2019-03-04 20:21:27 +0000868 // Do a post inline PGO instrumentation and use pass. This is a context
869 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
870 // cross-module inline has not been done yet. The context sensitive
871 // instrumentation is after all the inlines are done.
872 if (!LTOPreLink && PGOOpt) {
873 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
874 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
875 /* IsCS */ true, PGOOpt->CSProfileGenFile,
876 PGOOpt->ProfileRemappingFile);
877 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
878 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
879 /* IsCS */ true, PGOOpt->ProfileFile,
880 PGOOpt->ProfileRemappingFile);
881 }
882
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000883 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000884 // useful as the above will have inlined, DCE'ed, and function-attr
885 // propagated everything. We should at this point have a reasonably minimal
886 // and richly annotated call graph. By computing aliasing and mod/ref
887 // information for all local globals here, the late loop passes and notably
888 // the vectorizer will be able to use them to help recognize vectorizable
889 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000890 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000891
892 FunctionPassManager OptimizePM(DebugLogging);
893 OptimizePM.addPass(Float2IntPass());
894 // FIXME: We need to run some loop optimizations to re-rotate loops after
895 // simplify-cfg and others undo their rotation.
896
897 // Optimize the loop execution. These passes operate on entire loop nests
898 // rather than on each loop in an inside-out manner, and so they are actually
899 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000900
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000901 for (auto &C : VectorizerStartEPCallbacks)
902 C(OptimizePM, Level);
903
Chandler Carrutha95ff382017-01-27 00:50:21 +0000904 // First rotate loops that may have been un-rotated by prior passes.
Alina Sbirlea74251792019-08-21 17:00:57 +0000905 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
906 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000907
908 // Distribute loops to allow partial vectorization. I.e. isolate dependences
909 // into separate loop that would otherwise inhibit vectorization. This is
910 // currently only performed for loops marked with the metadata
911 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000912 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000913
914 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000915 OptimizePM.addPass(LoopVectorizePass(
916 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000917
Chandler Carruthbaabda92017-01-27 01:32:26 +0000918 // Eliminate loads by forwarding stores from the previous iteration to loads
919 // of the current iteration.
920 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000921
922 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000923 OptimizePM.addPass(InstCombinePass());
924
Chandler Carrutha95ff382017-01-27 00:50:21 +0000925 // Now that we've formed fast to execute loop structures, we do further
926 // optimizations. These are run afterward as they might block doing complex
927 // analyses and transforms such as what are needed for loop vectorization.
928
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000929 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
930 // GVN, loop transforms, and others have already run, so it's now better to
931 // convert to more optimized IR using more aggressive simplify CFG options.
932 // The extra sinking transform can create larger basic blocks, so do this
933 // before SLP vectorization.
934 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
935 forwardSwitchCondToPhi(true).
936 convertSwitchToLookupTable(true).
937 needCanonicalLoops(false).
938 sinkCommonInsts(true)));
939
Chandler Carruthe3f50642016-12-22 06:59:15 +0000940 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000941 if (PTO.SLPVectorization)
942 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000943
Chandler Carruthe3f50642016-12-22 06:59:15 +0000944 OptimizePM.addPass(InstCombinePass());
945
946 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000947 // execution resources of an out-of-order processor. We also then need to
948 // clean up redundancies and loop invariant code.
949 // FIXME: It would be really good to use a loop-integrated instruction
950 // combiner for cleanup here so that the unrolling and LICM can be pipelined
951 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000952 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
953 if (EnableUnrollAndJam) {
954 OptimizePM.addPass(
955 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
956 }
Alina Sbirleae4b27862019-05-23 19:35:40 +0000957 if (PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000958 OptimizePM.addPass(LoopUnrollPass(
959 LoopUnrollOptions(Level, false, PTO.ForgetAllSCEVInLoopUnroll)));
Michael Kruse72448522018-12-12 17:32:52 +0000960 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000961 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000962 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000963 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
964 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
Alina Sbirlea74251792019-08-21 17:00:57 +0000965 EnableMSSALoopDependency, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000966
967 // Now that we've vectorized and unrolled loops, we may have more refined
968 // alignment information, try to re-derive it here.
969 OptimizePM.addPass(AlignmentFromAssumptionsPass());
970
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000971 // Split out cold code. Splitting is done late to avoid hiding context from
972 // other optimizations and inadvertently regressing performance. The tradeoff
973 // is that this has a higher code size cost than splitting early.
974 if (EnableHotColdSplit && !LTOPreLink)
975 MPM.addPass(HotColdSplittingPass());
976
Chandler Carrutha95ff382017-01-27 00:50:21 +0000977 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
978 // canonicalization pass that enables other optimizations. As a result,
979 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
980 // result too early.
981 OptimizePM.addPass(LoopSinkPass());
982
983 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000984 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000985
Sanjay Patel6fd43912017-09-09 13:38:18 +0000986 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
987 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
988 // flattening of blocks.
989 OptimizePM.addPass(DivRemPairsPass());
990
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000991 // LoopSink (and other loop passes since the last simplifyCFG) might have
992 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
993 OptimizePM.addPass(SimplifyCFGPass());
994
Chandler Carruthc34f7892017-11-28 11:32:31 +0000995 // Optimize PHIs by speculating around them when profitable. Note that this
996 // pass needs to be run after any PRE or similar pass as it is essentially
Joerg Sonnenbergerec6ee792019-05-16 18:01:57 +0000997 // inserting redundancies into the program. This even includes SimplifyCFG.
Chandler Carruthc34f7892017-11-28 11:32:31 +0000998 OptimizePM.addPass(SpeculateAroundPHIsPass());
999
Philip Pfaffe2d4effb2018-11-12 11:17:07 +00001000 for (auto &C : OptimizerLastEPCallbacks)
1001 C(OptimizePM, Level);
1002
Chandler Carrutha95ff382017-01-27 00:50:21 +00001003 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001004 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
1005
Michael J. Spencer7bb27672018-07-16 00:28:24 +00001006 MPM.addPass(CGProfilePass());
1007
Chandler Carruthe3f50642016-12-22 06:59:15 +00001008 // Now we need to do some global optimization transforms.
1009 // FIXME: It would seem like these should come first in the optimization
1010 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1011 // ordering here.
1012 MPM.addPass(GlobalDCEPass());
1013 MPM.addPass(ConstantMergePass());
1014
1015 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001016}
1017
Chandler Carruthe3f50642016-12-22 06:59:15 +00001018ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001019PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001020 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001021 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1022
1023 ModulePassManager MPM(DebugLogging);
1024
1025 // Force any function attributes we want the rest of the pipeline to observe.
1026 MPM.addPass(ForceFunctionAttrsPass());
1027
David Blaikie0c64f5a2018-01-23 01:25:20 +00001028 // Apply module pipeline start EP callback.
1029 for (auto &C : PipelineStartEPCallbacks)
1030 C(MPM);
1031
Dehao Chen08f88312017-08-07 20:23:20 +00001032 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001033 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1034
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001035 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001036 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
1037 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001038
1039 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001040 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001041
1042 return MPM;
1043}
1044
1045ModulePassManager
1046PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1047 bool DebugLogging) {
1048 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1049
1050 ModulePassManager MPM(DebugLogging);
1051
1052 // Force any function attributes we want the rest of the pipeline to observe.
1053 MPM.addPass(ForceFunctionAttrsPass());
1054
Dehao Chen08f88312017-08-07 20:23:20 +00001055 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001056 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1057
David Blaikie0c64f5a2018-01-23 01:25:20 +00001058 // Apply module pipeline start EP callback.
1059 for (auto &C : PipelineStartEPCallbacks)
1060 C(MPM);
1061
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001062 // If we are planning to perform ThinLTO later, we don't bloat the code with
1063 // unrolling/vectorization/... now. Just simplify the module as much as we
1064 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001065 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1066 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001067
1068 // Run partial inlining pass to partially inline functions that have
1069 // large bodies.
1070 // FIXME: It isn't clear whether this is really the right place to run this
1071 // in ThinLTO. Because there is another canonicalization and simplification
1072 // phase that will run after the thin link, running this here ends up with
1073 // less information than will be available later and it may grow functions in
1074 // ways that aren't beneficial.
1075 if (RunPartialInlining)
1076 MPM.addPass(PartialInlinerPass());
1077
1078 // Reduce the size of the IR as much as possible.
1079 MPM.addPass(GlobalOptPass());
1080
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001081 return MPM;
1082}
1083
Teresa Johnson28023db2018-07-19 14:51:32 +00001084ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1085 OptimizationLevel Level, bool DebugLogging,
1086 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001087 ModulePassManager MPM(DebugLogging);
1088
Teresa Johnson28023db2018-07-19 14:51:32 +00001089 if (ImportSummary) {
1090 // These passes import type identifier resolutions for whole-program
1091 // devirtualization and CFI. They must run early because other passes may
1092 // disturb the specific instruction patterns that these passes look for,
1093 // creating dependencies on resolutions that may not appear in the summary.
1094 //
1095 // For example, GVN may transform the pattern assume(type.test) appearing in
1096 // two basic blocks into assume(phi(type.test, type.test)), which would
1097 // transform a dependency on a WPD resolution into a dependency on a type
1098 // identifier resolution for CFI.
1099 //
1100 // Also, WPD has access to more precise information than ICP and can
1101 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001102 //
1103 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1104 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001105 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1106 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1107 }
1108
Teresa Johnson867bc392019-04-23 18:56:19 +00001109 if (Level == O0)
1110 return MPM;
1111
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001112 // Force any function attributes we want the rest of the pipeline to observe.
1113 MPM.addPass(ForceFunctionAttrsPass());
1114
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001115 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001116 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1117 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001118
1119 // Now add the optimization pipeline.
1120 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1121
1122 return MPM;
1123}
1124
1125ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001126PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1127 bool DebugLogging) {
1128 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001129 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001130 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001131 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001132}
1133
Teresa Johnson28023db2018-07-19 14:51:32 +00001134ModulePassManager
1135PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1136 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001137 ModulePassManager MPM(DebugLogging);
1138
Teresa Johnson867bc392019-04-23 18:56:19 +00001139 if (Level == O0) {
1140 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1141 // metadata and intrinsics.
1142 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1143 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1144 return MPM;
1145 }
1146
Rong Xudb29a3a2019-03-04 20:21:27 +00001147 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001148 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001149 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001150 PGOOpt->ProfileRemappingFile,
1151 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001152 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1153 // RequireAnalysisPass for PSI before subsequent non-module passes.
1154 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001155 }
1156
Davide Italiano089a9122017-01-24 00:57:39 +00001157 // Remove unused virtual tables to improve the quality of code generated by
1158 // whole-program devirtualization and bitset lowering.
1159 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001160
Davide Italiano089a9122017-01-24 00:57:39 +00001161 // Force any function attributes we want the rest of the pipeline to observe.
1162 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001163
Davide Italiano089a9122017-01-24 00:57:39 +00001164 // Do basic inference of function attributes from known properties of system
1165 // libraries and other oracles.
1166 MPM.addPass(InferFunctionAttrsPass());
1167
1168 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001169 FunctionPassManager EarlyFPM(DebugLogging);
1170 EarlyFPM.addPass(CallSiteSplittingPass());
1171 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1172
Davide Italiano089a9122017-01-24 00:57:39 +00001173 // Indirect call promotion. This should promote all the targets that are
1174 // left by the earlier promotion pass that promotes intra-module targets.
1175 // This two-step promotion is to save the compile time. For LTO, it should
1176 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001177 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001178 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001179 // Propagate constants at call sites into the functions they call. This
1180 // opens opportunities for globalopt (and inlining) by substituting function
1181 // pointers passed as arguments to direct uses of functions.
1182 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001183
1184 // Attach metadata to indirect call sites indicating the set of functions
1185 // they may target at run-time. This should follow IPSCCP.
1186 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001187 }
1188
1189 // Now deduce any function attributes based in the current code.
1190 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1191 PostOrderFunctionAttrsPass()));
1192
1193 // Do RPO function attribute inference across the module to forward-propagate
1194 // attributes where applicable.
1195 // FIXME: Is this really an optimization rather than a canonicalization?
1196 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1197
Eric Christopher721eaef2019-02-26 20:33:22 +00001198 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001199 MPM.addPass(GlobalSplitPass());
1200
1201 // Run whole program optimization of virtual call when the list of callees
1202 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001203 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001204
1205 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001206 if (Level == 1) {
1207 // The LowerTypeTestsPass needs to run to lower type metadata and the
1208 // type.test intrinsics. The pass does nothing if CFI is disabled.
1209 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001210 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001211 }
Davide Italiano089a9122017-01-24 00:57:39 +00001212
1213 // Optimize globals to try and fold them into constants.
1214 MPM.addPass(GlobalOptPass());
1215
1216 // Promote any localized globals to SSA registers.
1217 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1218
1219 // Linking modules together can lead to duplicate global constant, only
1220 // keep one copy of each constant.
1221 MPM.addPass(ConstantMergePass());
1222
1223 // Remove unused arguments from functions.
1224 MPM.addPass(DeadArgumentEliminationPass());
1225
1226 // Reduce the code after globalopt and ipsccp. Both can open up significant
1227 // simplification opportunities, and both can propagate functions through
1228 // function pointers. When this happens, we often have to resolve varargs
1229 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001230 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001231 if (Level == O3)
1232 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001233 PeepholeFPM.addPass(InstCombinePass());
1234 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1235
1236 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001237
1238 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1239 // generally clean up exception handling overhead. It isn't clear this is
1240 // valuable as the inliner doesn't currently care whether it is inlining an
1241 // invoke or a call.
1242 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001243 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1244 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001245
1246 // Optimize globals again after we ran the inliner.
1247 MPM.addPass(GlobalOptPass());
1248
1249 // Garbage collect dead functions.
1250 // FIXME: Add ArgumentPromotion pass after once it's ported.
1251 MPM.addPass(GlobalDCEPass());
1252
1253 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001254 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001255 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001256 invokePeepholeEPCallbacks(FPM, Level);
1257
Davide Italiano089a9122017-01-24 00:57:39 +00001258 FPM.addPass(JumpThreadingPass());
1259
Rong Xudb29a3a2019-03-04 20:21:27 +00001260 // Do a post inline PGO instrumentation and use pass. This is a context
1261 // sensitive PGO pass.
1262 if (PGOOpt) {
1263 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1264 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1265 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1266 PGOOpt->ProfileRemappingFile);
1267 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1268 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1269 /* IsCS */ true, PGOOpt->ProfileFile,
1270 PGOOpt->ProfileRemappingFile);
1271 }
1272
Davide Italiano089a9122017-01-24 00:57:39 +00001273 // Break up allocas
1274 FPM.addPass(SROA());
1275
Robert Lougherf2158a82019-03-20 19:08:18 +00001276 // LTO provides additional opportunities for tailcall elimination due to
1277 // link-time inlining, and visibility of nocapture attribute.
1278 FPM.addPass(TailCallElimPass());
1279
Davide Italiano089a9122017-01-24 00:57:39 +00001280 // Run a few AA driver optimizations here and now to cleanup the code.
1281 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1282
1283 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1284 PostOrderFunctionAttrsPass()));
1285 // FIXME: here we run IP alias analysis in the legacy PM.
1286
1287 FunctionPassManager MainFPM;
1288
1289 // FIXME: once we fix LoopPass Manager, add LICM here.
1290 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001291 if (RunNewGVN)
1292 MainFPM.addPass(NewGVNPass());
1293 else
1294 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001295
1296 // Remove dead memcpy()'s.
1297 MainFPM.addPass(MemCpyOptPass());
1298
1299 // Nuke dead stores.
1300 MainFPM.addPass(DSEPass());
1301
1302 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001303 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001304 // loopVectorize. Enable them once the remaining issue with LPM
1305 // are sorted out.
1306
1307 MainFPM.addPass(InstCombinePass());
1308 MainFPM.addPass(SimplifyCFGPass());
1309 MainFPM.addPass(SCCPPass());
1310 MainFPM.addPass(InstCombinePass());
1311 MainFPM.addPass(BDCEPass());
1312
1313 // FIXME: We may want to run SLPVectorizer here.
1314 // After vectorization, assume intrinsics may tell us more
1315 // about pointer alignments.
1316#if 0
1317 MainFPM.add(AlignmentFromAssumptionsPass());
1318#endif
1319
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001320 // FIXME: Conditionally run LoadCombine here, after it's ported
1321 // (in case we still have this pass, given its questionable usefulness).
1322
Davide Italiano089a9122017-01-24 00:57:39 +00001323 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001324 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001325 MainFPM.addPass(JumpThreadingPass());
1326 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1327
1328 // Create a function that performs CFI checks for cross-DSO calls with
1329 // targets in the current module.
1330 MPM.addPass(CrossDSOCFIPass());
1331
1332 // Lower type metadata and the type.test intrinsic. This pass supports
1333 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1334 // to be run at link time if CFI is enabled. This pass does nothing if
1335 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001336 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001337
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001338 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1339 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1340 if (EnableHotColdSplit)
1341 MPM.addPass(HotColdSplittingPass());
1342
Davide Italiano089a9122017-01-24 00:57:39 +00001343 // Add late LTO optimization passes.
1344 // Delete basic blocks, which optimization passes may have killed.
1345 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1346
1347 // Drop bodies of available eternally objects to improve GlobalDCE.
1348 MPM.addPass(EliminateAvailableExternallyPass());
1349
1350 // Now that we have optimized the program, discard unreachable functions.
1351 MPM.addPass(GlobalDCEPass());
1352
Eric Christopher86e2f162019-05-03 00:15:23 +00001353 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001354 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001355}
1356
Chandler Carruth060ad612016-12-23 20:38:19 +00001357AAManager PassBuilder::buildDefaultAAPipeline() {
1358 AAManager AA;
1359
1360 // The order in which these are registered determines their priority when
1361 // being queried.
1362
1363 // First we register the basic alias analysis that provides the majority of
1364 // per-function local AA logic. This is a stateless, on-demand local set of
1365 // AA techniques.
1366 AA.registerFunctionAnalysis<BasicAA>();
1367
1368 // Next we query fast, specialized alias analyses that wrap IR-embedded
1369 // information about aliasing.
1370 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1371 AA.registerFunctionAnalysis<TypeBasedAA>();
1372
1373 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001374 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1375 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001376 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001377 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001378
1379 return AA;
1380}
1381
Chandler Carruth241bf242016-08-03 07:44:48 +00001382static Optional<int> parseRepeatPassName(StringRef Name) {
1383 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1384 return None;
1385 int Count;
1386 if (Name.getAsInteger(0, Count) || Count <= 0)
1387 return None;
1388 return Count;
1389}
1390
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001391static Optional<int> parseDevirtPassName(StringRef Name) {
1392 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1393 return None;
1394 int Count;
1395 if (Name.getAsInteger(0, Count) || Count <= 0)
1396 return None;
1397 return Count;
1398}
1399
Fedor Sergeevb7871402019-01-10 10:01:53 +00001400static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1401 if (!Name.consume_front(PassName))
1402 return false;
1403 // normal pass name w/o parameters == default parameters
1404 if (Name.empty())
1405 return true;
1406 return Name.startswith("<") && Name.endswith(">");
1407}
1408
1409namespace {
1410
1411/// This performs customized parsing of pass name with parameters.
1412///
1413/// We do not need parametrization of passes in textual pipeline very often,
1414/// yet on a rare occasion ability to specify parameters right there can be
1415/// useful.
1416///
1417/// \p Name - parameterized specification of a pass from a textual pipeline
1418/// is a string in a form of :
1419/// PassName '<' parameter-list '>'
1420///
1421/// Parameter list is being parsed by the parser callable argument, \p Parser,
1422/// It takes a string-ref of parameters and returns either StringError or a
1423/// parameter list in a form of a custom parameters type, all wrapped into
1424/// Expected<> template class.
1425///
1426template <typename ParametersParseCallableT>
1427auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1428 StringRef PassName) -> decltype(Parser(StringRef{})) {
1429 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1430
1431 StringRef Params = Name;
1432 if (!Params.consume_front(PassName)) {
1433 assert(false &&
1434 "unable to strip pass name from parametrized pass specification");
1435 }
1436 if (Params.empty())
1437 return ParametersT{};
1438 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1439 assert(false && "invalid format for parametrized pass name");
1440 }
1441
1442 Expected<ParametersT> Result = Parser(Params);
1443 assert((Result || Result.template errorIsA<StringError>()) &&
1444 "Pass parameter parser can only return StringErrors.");
1445 return std::move(Result);
1446}
1447
1448/// Parser of parameters for LoopUnroll pass.
1449Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1450 LoopUnrollOptions UnrollOpts;
1451 while (!Params.empty()) {
1452 StringRef ParamName;
1453 std::tie(ParamName, Params) = Params.split(';');
1454 int OptLevel = StringSwitch<int>(ParamName)
1455 .Case("O0", 0)
1456 .Case("O1", 1)
1457 .Case("O2", 2)
1458 .Case("O3", 3)
1459 .Default(-1);
1460 if (OptLevel >= 0) {
1461 UnrollOpts.setOptLevel(OptLevel);
1462 continue;
1463 }
Serguei Katkova4476882019-09-19 06:57:29 +00001464 if (ParamName.consume_front("full-unroll-max=")) {
1465 int Count;
1466 if (ParamName.getAsInteger(0, Count))
1467 return make_error<StringError>(
1468 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1469 inconvertibleErrorCode());
1470 UnrollOpts.setFullUnrollMaxCount(Count);
1471 continue;
1472 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001473
1474 bool Enable = !ParamName.consume_front("no-");
1475 if (ParamName == "partial") {
1476 UnrollOpts.setPartial(Enable);
1477 } else if (ParamName == "peeling") {
1478 UnrollOpts.setPeeling(Enable);
Serguei Katkovde67aff2019-08-02 09:32:52 +00001479 } else if (ParamName == "profile-peeling") {
1480 UnrollOpts.setProfileBasedPeeling(Enable);
Fedor Sergeevb7871402019-01-10 10:01:53 +00001481 } else if (ParamName == "runtime") {
1482 UnrollOpts.setRuntime(Enable);
1483 } else if (ParamName == "upperbound") {
1484 UnrollOpts.setUpperBound(Enable);
1485 } else {
1486 return make_error<StringError>(
1487 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1488 inconvertibleErrorCode());
1489 }
1490 }
1491 return UnrollOpts;
1492}
1493
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001494Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1495 MemorySanitizerOptions Result;
1496 while (!Params.empty()) {
1497 StringRef ParamName;
1498 std::tie(ParamName, Params) = Params.split(';');
1499
1500 if (ParamName == "recover") {
1501 Result.Recover = true;
1502 } else if (ParamName == "kernel") {
1503 Result.Kernel = true;
1504 } else if (ParamName.consume_front("track-origins=")) {
1505 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1506 return make_error<StringError>(
1507 formatv("invalid argument to MemorySanitizer pass track-origins "
1508 "parameter: '{0}' ",
1509 ParamName)
1510 .str(),
1511 inconvertibleErrorCode());
1512 } else {
1513 return make_error<StringError>(
1514 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1515 .str(),
1516 inconvertibleErrorCode());
1517 }
1518 }
1519 return Result;
1520}
1521
Serguei Katkovf5432832019-04-15 08:57:53 +00001522/// Parser of parameters for SimplifyCFG pass.
1523Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1524 SimplifyCFGOptions Result;
1525 while (!Params.empty()) {
1526 StringRef ParamName;
1527 std::tie(ParamName, Params) = Params.split(';');
1528
1529 bool Enable = !ParamName.consume_front("no-");
1530 if (ParamName == "forward-switch-cond") {
1531 Result.forwardSwitchCondToPhi(Enable);
1532 } else if (ParamName == "switch-to-lookup") {
1533 Result.convertSwitchToLookupTable(Enable);
1534 } else if (ParamName == "keep-loops") {
1535 Result.needCanonicalLoops(Enable);
1536 } else if (ParamName == "sink-common-insts") {
1537 Result.sinkCommonInsts(Enable);
1538 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1539 APInt BonusInstThreshold;
1540 if (ParamName.getAsInteger(0, BonusInstThreshold))
1541 return make_error<StringError>(
1542 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1543 "parameter: '{0}' ",
1544 ParamName).str(),
1545 inconvertibleErrorCode());
1546 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1547 } else {
1548 return make_error<StringError>(
1549 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1550 inconvertibleErrorCode());
1551 }
1552 }
1553 return Result;
1554}
1555
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001556/// Parser of parameters for LoopVectorize pass.
1557Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1558 LoopVectorizeOptions Opts;
1559 while (!Params.empty()) {
1560 StringRef ParamName;
1561 std::tie(ParamName, Params) = Params.split(';');
1562
1563 bool Enable = !ParamName.consume_front("no-");
1564 if (ParamName == "interleave-forced-only") {
1565 Opts.setInterleaveOnlyWhenForced(Enable);
1566 } else if (ParamName == "vectorize-forced-only") {
1567 Opts.setVectorizeOnlyWhenForced(Enable);
1568 } else {
1569 return make_error<StringError>(
1570 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1571 inconvertibleErrorCode());
1572 }
1573 }
1574 return Opts;
1575}
1576
Serguei Katkov40a3b962019-04-22 10:35:07 +00001577Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1578 bool Result = false;
1579 while (!Params.empty()) {
1580 StringRef ParamName;
1581 std::tie(ParamName, Params) = Params.split(';');
1582
1583 bool Enable = !ParamName.consume_front("no-");
1584 if (ParamName == "nontrivial") {
1585 Result = Enable;
1586 } else {
1587 return make_error<StringError>(
1588 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1589 .str(),
1590 inconvertibleErrorCode());
1591 }
1592 }
1593 return Result;
1594}
Denis Bakhvalov58f172f2019-09-05 17:00:32 +00001595
1596Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) {
1597 bool Result = false;
1598 while (!Params.empty()) {
1599 StringRef ParamName;
1600 std::tie(ParamName, Params) = Params.split(';');
1601
1602 bool Enable = !ParamName.consume_front("no-");
1603 if (ParamName == "split-footer-bb") {
1604 Result = Enable;
1605 } else {
1606 return make_error<StringError>(
1607 formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
1608 ParamName)
1609 .str(),
1610 inconvertibleErrorCode());
1611 }
1612 }
1613 return Result;
1614}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001615} // namespace
1616
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001617/// Tests whether a pass name starts with a valid prefix for a default pipeline
1618/// alias.
1619static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1620 return Name.startswith("default") || Name.startswith("thinlto") ||
1621 Name.startswith("lto");
1622}
1623
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001624/// Tests whether registered callbacks will accept a given pass name.
1625///
1626/// When parsing a pipeline text, the type of the outermost pipeline may be
1627/// omitted, in which case the type is automatically determined from the first
1628/// pass name in the text. This may be a name that is handled through one of the
1629/// callbacks. We check this through the oridinary parsing callbacks by setting
1630/// up a dummy PassManager in order to not force the client to also handle this
1631/// type of query.
1632template <typename PassManagerT, typename CallbacksT>
1633static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1634 if (!Callbacks.empty()) {
1635 PassManagerT DummyPM;
1636 for (auto &CB : Callbacks)
1637 if (CB(Name, DummyPM, {}))
1638 return true;
1639 }
1640 return false;
1641}
1642
1643template <typename CallbacksT>
1644static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001645 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001646 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001647 return DefaultAliasRegex.match(Name);
1648
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001649 // Explicitly handle pass manager names.
1650 if (Name == "module")
1651 return true;
1652 if (Name == "cgscc")
1653 return true;
1654 if (Name == "function")
1655 return true;
1656
Chandler Carruth241bf242016-08-03 07:44:48 +00001657 // Explicitly handle custom-parsed pass names.
1658 if (parseRepeatPassName(Name))
1659 return true;
1660
Chandler Carruth74a8a222016-06-17 07:15:29 +00001661#define MODULE_PASS(NAME, CREATE_PASS) \
1662 if (Name == NAME) \
1663 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001664#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001665 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001666 return true;
1667#include "PassRegistry.def"
1668
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001669 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001670}
1671
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001672template <typename CallbacksT>
1673static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001674 // Explicitly handle pass manager names.
1675 if (Name == "cgscc")
1676 return true;
1677 if (Name == "function")
1678 return true;
1679
Chandler Carruth241bf242016-08-03 07:44:48 +00001680 // Explicitly handle custom-parsed pass names.
1681 if (parseRepeatPassName(Name))
1682 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001683 if (parseDevirtPassName(Name))
1684 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001685
Chandler Carruth74a8a222016-06-17 07:15:29 +00001686#define CGSCC_PASS(NAME, CREATE_PASS) \
1687 if (Name == NAME) \
1688 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001689#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001690 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001691 return true;
1692#include "PassRegistry.def"
1693
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001694 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001695}
1696
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001697template <typename CallbacksT>
1698static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001699 // Explicitly handle pass manager names.
1700 if (Name == "function")
1701 return true;
Alina Sbirlea74251792019-08-21 17:00:57 +00001702 if (Name == "loop" || Name == "loop-mssa")
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001703 return true;
1704
Chandler Carruth241bf242016-08-03 07:44:48 +00001705 // Explicitly handle custom-parsed pass names.
1706 if (parseRepeatPassName(Name))
1707 return true;
1708
Chandler Carruth74a8a222016-06-17 07:15:29 +00001709#define FUNCTION_PASS(NAME, CREATE_PASS) \
1710 if (Name == NAME) \
1711 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001712#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1713 if (checkParametrizedPassName(Name, NAME)) \
1714 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001715#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001716 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001717 return true;
1718#include "PassRegistry.def"
1719
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001720 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001721}
1722
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001723template <typename CallbacksT>
1724static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001725 // Explicitly handle pass manager names.
Alina Sbirlea74251792019-08-21 17:00:57 +00001726 if (Name == "loop" || Name == "loop-mssa")
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001727 return true;
1728
Chandler Carruth241bf242016-08-03 07:44:48 +00001729 // Explicitly handle custom-parsed pass names.
1730 if (parseRepeatPassName(Name))
1731 return true;
1732
Chandler Carruth74a8a222016-06-17 07:15:29 +00001733#define LOOP_PASS(NAME, CREATE_PASS) \
1734 if (Name == NAME) \
1735 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001736#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1737 if (checkParametrizedPassName(Name, NAME)) \
1738 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001739#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1740 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1741 return true;
1742#include "PassRegistry.def"
1743
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001744 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001745}
1746
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001747Optional<std::vector<PassBuilder::PipelineElement>>
1748PassBuilder::parsePipelineText(StringRef Text) {
1749 std::vector<PipelineElement> ResultPipeline;
1750
1751 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1752 &ResultPipeline};
1753 for (;;) {
1754 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1755 size_t Pos = Text.find_first_of(",()");
1756 Pipeline.push_back({Text.substr(0, Pos), {}});
1757
1758 // If we have a single terminating name, we're done.
1759 if (Pos == Text.npos)
1760 break;
1761
1762 char Sep = Text[Pos];
1763 Text = Text.substr(Pos + 1);
1764 if (Sep == ',')
1765 // Just a name ending in a comma, continue.
1766 continue;
1767
1768 if (Sep == '(') {
1769 // Push the inner pipeline onto the stack to continue processing.
1770 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1771 continue;
1772 }
1773
1774 assert(Sep == ')' && "Bogus separator!");
1775 // When handling the close parenthesis, we greedily consume them to avoid
1776 // empty strings in the pipeline.
1777 do {
1778 // If we try to pop the outer pipeline we have unbalanced parentheses.
1779 if (PipelineStack.size() == 1)
1780 return None;
1781
1782 PipelineStack.pop_back();
1783 } while (Text.consume_front(")"));
1784
1785 // Check if we've finished parsing.
1786 if (Text.empty())
1787 break;
1788
1789 // Otherwise, the end of an inner pipeline always has to be followed by
1790 // a comma, and then we can continue.
1791 if (!Text.consume_front(","))
1792 return None;
1793 }
1794
1795 if (PipelineStack.size() > 1)
1796 // Unbalanced paretheses.
1797 return None;
1798
1799 assert(PipelineStack.back() == &ResultPipeline &&
1800 "Wrong pipeline at the bottom of the stack!");
1801 return {std::move(ResultPipeline)};
1802}
1803
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001804Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1805 const PipelineElement &E,
1806 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001807 auto &Name = E.Name;
1808 auto &InnerPipeline = E.InnerPipeline;
1809
1810 // First handle complex passes like the pass managers which carry pipelines.
1811 if (!InnerPipeline.empty()) {
1812 if (Name == "module") {
1813 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001814 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1815 VerifyEachPass, DebugLogging))
1816 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001817 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001818 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001819 }
1820 if (Name == "cgscc") {
1821 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001822 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1823 DebugLogging))
1824 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001825 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001826 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001827 }
1828 if (Name == "function") {
1829 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001830 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1831 VerifyEachPass, DebugLogging))
1832 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001833 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001834 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001835 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001836 if (auto Count = parseRepeatPassName(Name)) {
1837 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001838 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1839 VerifyEachPass, DebugLogging))
1840 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001841 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001842 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001843 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001844
1845 for (auto &C : ModulePipelineParsingCallbacks)
1846 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001847 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001848
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001849 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001850 return make_error<StringError>(
1851 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1852 inconvertibleErrorCode());
1853 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001854 }
1855
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001856 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001857 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001858 SmallVector<StringRef, 3> Matches;
1859 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001860 return make_error<StringError>(
1861 formatv("unknown default pipeline alias '{0}'", Name).str(),
1862 inconvertibleErrorCode());
1863
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001864 assert(Matches.size() == 3 && "Must capture two matched strings!");
1865
Jordan Rosef85a95f2016-07-25 18:34:51 +00001866 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001867 .Case("O0", O0)
1868 .Case("O1", O1)
1869 .Case("O2", O2)
1870 .Case("O3", O3)
1871 .Case("Os", Os)
1872 .Case("Oz", Oz);
Rong Xuca161fa2019-08-01 22:36:34 +00001873 if (L == O0) {
1874 // Add instrumentation PGO passes -- at O0 we can still do PGO.
1875 if (PGOOpt && Matches[1] != "thinlto" &&
1876 (PGOOpt->Action == PGOOptions::IRInstr ||
1877 PGOOpt->Action == PGOOptions::IRUse))
1878 addPGOInstrPassesForO0(
1879 MPM, DebugLogging,
1880 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1881 /* IsCS */ false, PGOOpt->ProfileFile,
1882 PGOOpt->ProfileRemappingFile);
1883 // Do nothing else at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001884 return Error::success();
Rong Xuca161fa2019-08-01 22:36:34 +00001885 }
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001886
1887 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001888 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001889 } else if (Matches[1] == "thinlto-pre-link") {
1890 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1891 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001892 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001893 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001894 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001895 } else {
1896 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001897 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001898 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001899 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001900 }
1901
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001902 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001903#define MODULE_PASS(NAME, CREATE_PASS) \
1904 if (Name == NAME) { \
1905 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001906 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001907 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001908#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1909 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001910 MPM.addPass( \
1911 RequireAnalysisPass< \
1912 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001913 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001914 } \
1915 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001916 MPM.addPass(InvalidateAnalysisPass< \
1917 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001918 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001919 }
1920#include "PassRegistry.def"
1921
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001922 for (auto &C : ModulePipelineParsingCallbacks)
1923 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001924 return Error::success();
1925 return make_error<StringError>(
1926 formatv("unknown module pass '{0}'", Name).str(),
1927 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001928}
1929
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001930Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1931 const PipelineElement &E, bool VerifyEachPass,
1932 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001933 auto &Name = E.Name;
1934 auto &InnerPipeline = E.InnerPipeline;
1935
1936 // First handle complex passes like the pass managers which carry pipelines.
1937 if (!InnerPipeline.empty()) {
1938 if (Name == "cgscc") {
1939 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001940 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1941 VerifyEachPass, DebugLogging))
1942 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001943 // Add the nested pass manager with the appropriate adaptor.
1944 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001945 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001946 }
1947 if (Name == "function") {
1948 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001949 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1950 VerifyEachPass, DebugLogging))
1951 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001952 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001953 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001954 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001955 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001956 if (auto Count = parseRepeatPassName(Name)) {
1957 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001958 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1959 VerifyEachPass, DebugLogging))
1960 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001961 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001962 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001963 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001964 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1965 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001966 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1967 VerifyEachPass, DebugLogging))
1968 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001969 CGPM.addPass(
1970 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001971 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001972 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001973
1974 for (auto &C : CGSCCPipelineParsingCallbacks)
1975 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001976 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001977
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001978 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001979 return make_error<StringError>(
1980 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1981 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001982 }
1983
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001984// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001985#define CGSCC_PASS(NAME, CREATE_PASS) \
1986 if (Name == NAME) { \
1987 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001988 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001989 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001990#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1991 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001992 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001993 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001994 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1995 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001996 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001997 } \
1998 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001999 CGPM.addPass(InvalidateAnalysisPass< \
2000 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002001 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002002 }
2003#include "PassRegistry.def"
2004
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002005 for (auto &C : CGSCCPipelineParsingCallbacks)
2006 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002007 return Error::success();
2008 return make_error<StringError>(
2009 formatv("unknown cgscc pass '{0}'", Name).str(),
2010 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00002011}
2012
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002013Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
2014 const PipelineElement &E,
2015 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002016 auto &Name = E.Name;
2017 auto &InnerPipeline = E.InnerPipeline;
2018
2019 // First handle complex passes like the pass managers which carry pipelines.
2020 if (!InnerPipeline.empty()) {
2021 if (Name == "function") {
2022 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002023 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2024 VerifyEachPass, DebugLogging))
2025 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002026 // Add the nested pass manager with the appropriate adaptor.
2027 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002028 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002029 }
Alina Sbirlea74251792019-08-21 17:00:57 +00002030 if (Name == "loop" || Name == "loop-mssa") {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002031 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002032 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
2033 DebugLogging))
2034 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002035 // Add the nested pass manager with the appropriate adaptor.
Alina Sbirlea74251792019-08-21 17:00:57 +00002036 bool UseMemorySSA = (Name == "loop-mssa");
2037 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
2038 DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002039 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002040 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002041 if (auto Count = parseRepeatPassName(Name)) {
2042 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002043 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2044 VerifyEachPass, DebugLogging))
2045 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002046 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002047 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002048 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002049
2050 for (auto &C : FunctionPipelineParsingCallbacks)
2051 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002052 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002053
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002054 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002055 return make_error<StringError>(
2056 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
2057 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002058 }
2059
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002060// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00002061#define FUNCTION_PASS(NAME, CREATE_PASS) \
2062 if (Name == NAME) { \
2063 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002064 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00002065 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00002066#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2067 if (checkParametrizedPassName(Name, NAME)) { \
2068 auto Params = parsePassParameters(PARSER, Name, NAME); \
2069 if (!Params) \
2070 return Params.takeError(); \
2071 FPM.addPass(CREATE_PASS(Params.get())); \
2072 return Error::success(); \
2073 }
Chandler Carruth628503e2015-01-06 02:10:51 +00002074#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
2075 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00002076 FPM.addPass( \
2077 RequireAnalysisPass< \
2078 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002079 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00002080 } \
2081 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00002082 FPM.addPass(InvalidateAnalysisPass< \
2083 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002084 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002085 }
2086#include "PassRegistry.def"
2087
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002088 for (auto &C : FunctionPipelineParsingCallbacks)
2089 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002090 return Error::success();
2091 return make_error<StringError>(
2092 formatv("unknown function pass '{0}'", Name).str(),
2093 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002094}
2095
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002096Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2097 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002098 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002099 auto &InnerPipeline = E.InnerPipeline;
2100
2101 // First handle complex passes like the pass managers which carry pipelines.
2102 if (!InnerPipeline.empty()) {
2103 if (Name == "loop") {
2104 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002105 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2106 VerifyEachPass, DebugLogging))
2107 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002108 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002109 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002110 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002111 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002112 if (auto Count = parseRepeatPassName(Name)) {
2113 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002114 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2115 VerifyEachPass, DebugLogging))
2116 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002117 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002118 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002119 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002120
2121 for (auto &C : LoopPipelineParsingCallbacks)
2122 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002123 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002124
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002125 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002126 return make_error<StringError>(
2127 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2128 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002129 }
2130
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002131// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002132#define LOOP_PASS(NAME, CREATE_PASS) \
2133 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002134 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002135 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002136 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002137#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2138 if (checkParametrizedPassName(Name, NAME)) { \
2139 auto Params = parsePassParameters(PARSER, Name, NAME); \
2140 if (!Params) \
2141 return Params.takeError(); \
2142 LPM.addPass(CREATE_PASS(Params.get())); \
2143 return Error::success(); \
2144 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002145#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2146 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002147 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002148 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2149 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2150 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002151 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002152 } \
2153 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002154 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002155 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002156 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002157 }
2158#include "PassRegistry.def"
2159
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002160 for (auto &C : LoopPipelineParsingCallbacks)
2161 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002162 return Error::success();
2163 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2164 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002165}
2166
Chandler Carruthedf59962016-02-18 09:45:17 +00002167bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002168#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2169 if (Name == NAME) { \
2170 AA.registerModuleAnalysis< \
2171 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2172 return true; \
2173 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002174#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2175 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002176 AA.registerFunctionAnalysis< \
2177 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002178 return true; \
2179 }
2180#include "PassRegistry.def"
2181
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002182 for (auto &C : AAParsingCallbacks)
2183 if (C(Name, AA))
2184 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002185 return false;
2186}
2187
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002188Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002189 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002190 bool VerifyEachPass,
2191 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002192 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002193 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2194 return Err;
2195 // FIXME: No verifier support for Loop passes!
2196 }
2197 return Error::success();
2198}
2199
2200Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2201 ArrayRef<PipelineElement> Pipeline,
2202 bool VerifyEachPass,
2203 bool DebugLogging) {
2204 for (const auto &Element : Pipeline) {
2205 if (auto Err =
2206 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2207 return Err;
2208 if (VerifyEachPass)
2209 FPM.addPass(VerifierPass());
2210 }
2211 return Error::success();
2212}
2213
2214Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2215 ArrayRef<PipelineElement> Pipeline,
2216 bool VerifyEachPass,
2217 bool DebugLogging) {
2218 for (const auto &Element : Pipeline) {
2219 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2220 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002221 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002222 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002223 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002224}
2225
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002226void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2227 FunctionAnalysisManager &FAM,
2228 CGSCCAnalysisManager &CGAM,
2229 ModuleAnalysisManager &MAM) {
2230 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2231 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002232 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2233 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2234 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2235 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2236 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2237}
2238
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002239Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2240 ArrayRef<PipelineElement> Pipeline,
2241 bool VerifyEachPass,
2242 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002243 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002244 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2245 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002246 if (VerifyEachPass)
2247 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002248 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002249 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002250}
2251
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002252// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002253// FIXME: Should this routine accept a TargetMachine or require the caller to
2254// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002255Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2256 StringRef PipelineText,
2257 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +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());
Chandler Carruth66445382014-01-11 08:16:35 +00002263
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002264 // If the first name isn't at the module layer, wrap the pipeline up
2265 // automatically.
2266 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002267
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002268 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2269 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002270 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002271 } else if (isFunctionPassName(FirstName,
2272 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002273 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002274 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002275 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002276 } else {
2277 for (auto &C : TopLevelPipelineParsingCallbacks)
2278 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002279 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002280
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002281 // Unknown pass or pipeline name!
2282 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2283 return make_error<StringError>(
2284 formatv("unknown {0} name '{1}'",
2285 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2286 .str(),
2287 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002288 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002289 }
2290
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002291 if (auto Err =
2292 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2293 return Err;
2294 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002295}
Chandler Carruthedf59962016-02-18 09:45:17 +00002296
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002297// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002298Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2299 StringRef PipelineText,
2300 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002301 auto Pipeline = parsePipelineText(PipelineText);
2302 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002303 return make_error<StringError>(
2304 formatv("invalid pipeline '{0}'", PipelineText).str(),
2305 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002306
2307 StringRef FirstName = Pipeline->front().Name;
2308 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002309 return make_error<StringError>(
2310 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2311 PipelineText)
2312 .str(),
2313 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002314
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002315 if (auto Err =
2316 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2317 return Err;
2318 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002319}
2320
2321// Primary pass pipeline description parsing routine for a \c
2322// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002323Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2324 StringRef PipelineText,
2325 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002326 auto Pipeline = parsePipelineText(PipelineText);
2327 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002328 return make_error<StringError>(
2329 formatv("invalid pipeline '{0}'", PipelineText).str(),
2330 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002331
2332 StringRef FirstName = Pipeline->front().Name;
2333 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002334 return make_error<StringError>(
2335 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2336 PipelineText)
2337 .str(),
2338 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002339
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002340 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2341 DebugLogging))
2342 return Err;
2343 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002344}
2345
2346// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002347Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2348 StringRef PipelineText,
2349 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002350 auto Pipeline = parsePipelineText(PipelineText);
2351 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002352 return make_error<StringError>(
2353 formatv("invalid pipeline '{0}'", PipelineText).str(),
2354 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002355
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002356 if (auto Err =
2357 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2358 return Err;
2359
2360 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002361}
2362
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002363Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002364 // If the pipeline just consists of the word 'default' just replace the AA
2365 // manager with our default one.
2366 if (PipelineText == "default") {
2367 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002368 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002369 }
2370
Chandler Carruthedf59962016-02-18 09:45:17 +00002371 while (!PipelineText.empty()) {
2372 StringRef Name;
2373 std::tie(Name, PipelineText) = PipelineText.split(',');
2374 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002375 return make_error<StringError>(
2376 formatv("unknown alias analysis name '{0}'", Name).str(),
2377 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002378 }
2379
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002380 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002381}