blob: 5c4874de855c634712ca2b2328a11ae01b3db1aa [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"
Joerg Sonnenberger9681ea92019-10-14 16:15:14 +0000145#include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000146#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000147#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000148#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000149#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000150#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Leonard Chanbb147aa2019-07-15 23:18:31 +0000151#include "llvm/Transforms/Scalar/MergeICmps.h"
Leonard Chan007f6742019-07-25 20:53:15 +0000152#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000153#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000154#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000155#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000156#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000157#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000158#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000159#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000160#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000161#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000162#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000163#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000164#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000165#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000166#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000167#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000168#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000169#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000170#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000171#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000172#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000173#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000174#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000175#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000176#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000177#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000178#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000179#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000180#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000181#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000182
Chandler Carruth66445382014-01-11 08:16:35 +0000183using namespace llvm;
184
Chandler Carruth719ffe12017-02-12 05:38:04 +0000185static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
186 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000187static cl::opt<bool>
188 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
189 cl::Hidden, cl::ZeroOrMore,
190 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000191
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000192static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000193 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000194 cl::Hidden, cl::ZeroOrMore,
195 cl::desc("Run NewGVN instead of GVN"));
196
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000197static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000198 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
199 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000200
Davide Italianobe1b6a92017-06-03 23:18:29 +0000201static cl::opt<bool> EnableGVNSink(
202 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
203 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
204
David Green963401d2018-07-01 12:47:30 +0000205static cl::opt<bool> EnableUnrollAndJam(
206 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
207 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
208
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000209static cl::opt<bool> EnableSyntheticCounts(
210 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
211 cl::desc("Run synthetic function entry count generation "
212 "pass"));
213
Thomas Preud'homme5f738942019-09-24 14:42:36 +0000214static const Regex DefaultAliasRegex(
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000215 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000216
Eric Christophereff3b6f2019-04-18 06:17:40 +0000217// This option is used in simplifying testing SampleFDO optimizations for
218// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000219static cl::opt<bool>
220 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
221 cl::desc("Enable control height reduction optimization (CHR)"));
222
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000223PipelineTuningOptions::PipelineTuningOptions() {
224 LoopInterleaving = EnableLoopInterleaving;
225 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea458c7332019-05-08 17:58:35 +0000226 SLPVectorization = RunSLPVectorization;
Alina Sbirleae4b27862019-05-23 19:35:40 +0000227 LoopUnrolling = true;
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000228 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000229 LicmMssaOptCap = SetLicmMssaOptCap;
230 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000231}
232
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000233extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000234extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000235
Wei Mi3bcccdf2019-01-17 20:48:34 +0000236extern cl::opt<bool> FlattenedProfileUsed;
237
Chandler Carruthe3f50642016-12-22 06:59:15 +0000238static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
239 switch (Level) {
240 case PassBuilder::O0:
241 case PassBuilder::O1:
242 case PassBuilder::O2:
243 case PassBuilder::O3:
244 return false;
245
246 case PassBuilder::Os:
247 case PassBuilder::Oz:
248 return true;
249 }
250 llvm_unreachable("Invalid optimization level!");
251}
252
Chandler Carruth66445382014-01-11 08:16:35 +0000253namespace {
254
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000255/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000256struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000257 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000258 return PreservedAnalyses::all();
259 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000260 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000261};
262
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000263/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000264class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
265 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000266 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000267
268public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000269 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000270 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000271 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000272};
273
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000274/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000275struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000276 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
277 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000278 return PreservedAnalyses::all();
279 }
280 static StringRef name() { return "NoOpCGSCCPass"; }
281};
282
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000283/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000284class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
285 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000286 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000287
288public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000289 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000290 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000291 return Result();
292 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000293 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000294};
295
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000296/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000297struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000298 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000299 return PreservedAnalyses::all();
300 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000301 static StringRef name() { return "NoOpFunctionPass"; }
302};
303
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000304/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000305class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
306 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000307 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000308
309public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000310 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000311 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000312 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000313};
314
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000315/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000316struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000317 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
318 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000319 return PreservedAnalyses::all();
320 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000321 static StringRef name() { return "NoOpLoopPass"; }
322};
323
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000324/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000325class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
326 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000327 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000328
329public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000330 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000331 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
332 return Result();
333 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000334 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000335};
336
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000337AnalysisKey NoOpModuleAnalysis::Key;
338AnalysisKey NoOpCGSCCAnalysis::Key;
339AnalysisKey NoOpFunctionAnalysis::Key;
340AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000341
Chandler Carruth66445382014-01-11 08:16:35 +0000342} // End anonymous namespace.
343
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000344void PassBuilder::invokePeepholeEPCallbacks(
345 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
346 for (auto &C : PeepholeEPCallbacks)
347 C(FPM, Level);
348}
349
Chandler Carruth1ff77242015-03-07 09:02:36 +0000350void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000351#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000352 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000353#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000354
355 for (auto &C : ModuleAnalysisRegistrationCallbacks)
356 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000357}
358
Chandler Carruth1ff77242015-03-07 09:02:36 +0000359void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000360#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000361 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000362#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000363
364 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
365 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000366}
367
Chandler Carruth1ff77242015-03-07 09:02:36 +0000368void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000369#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000370 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000371#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000372
373 for (auto &C : FunctionAnalysisRegistrationCallbacks)
374 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000375}
376
Justin Bognereecc3c82016-02-25 07:23:08 +0000377void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000378#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000379 LAM.registerPass([&] { return CREATE_PASS; });
380#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000381
382 for (auto &C : LoopAnalysisRegistrationCallbacks)
383 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000384}
385
Chandler Carruthe3f50642016-12-22 06:59:15 +0000386FunctionPassManager
387PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000388 ThinLTOPhase Phase,
389 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000390 assert(Level != O0 && "Must request optimizations!");
391 FunctionPassManager FPM(DebugLogging);
392
393 // Form SSA out of local memory accesses after breaking apart aggregates into
394 // scalars.
395 FPM.addPass(SROA());
396
397 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000398 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000399
Davide Italianoc3688312017-06-01 23:08:14 +0000400 // Hoisting of scalars and load expressions.
401 if (EnableGVNHoist)
402 FPM.addPass(GVNHoistPass());
403
Davide Italianobe1b6a92017-06-03 23:18:29 +0000404 // Global value numbering based sinking.
405 if (EnableGVNSink) {
406 FPM.addPass(GVNSinkPass());
407 FPM.addPass(SimplifyCFGPass());
408 }
409
Chandler Carruthe3f50642016-12-22 06:59:15 +0000410 // Speculative execution if the target has divergent branches; otherwise nop.
411 FPM.addPass(SpeculativeExecutionPass());
412
413 // Optimize based on known information about branches, and cleanup afterward.
414 FPM.addPass(JumpThreadingPass());
415 FPM.addPass(CorrelatedValuePropagationPass());
416 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000417 if (Level == O3)
418 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000419 FPM.addPass(InstCombinePass());
420
421 if (!isOptimizingForSize(Level))
422 FPM.addPass(LibCallsShrinkWrapPass());
423
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000424 invokePeepholeEPCallbacks(FPM, Level);
425
Rong Xue1f42452017-10-23 22:21:29 +0000426 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
427 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000428 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000429 !isOptimizingForSize(Level))
430 FPM.addPass(PGOMemOPSizeOpt());
431
Chandler Carruthe3f50642016-12-22 06:59:15 +0000432 FPM.addPass(TailCallElimPass());
433 FPM.addPass(SimplifyCFGPass());
434
435 // Form canonically associated expression trees, and simplify the trees using
436 // basic mathematical properties. For example, this will form (nearly)
437 // minimal multiplication trees.
438 FPM.addPass(ReassociatePass());
439
440 // Add the primary loop simplification pipeline.
441 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000442 // some function passes in between them. These can and should be removed
443 // and/or replaced by scheduling the loop pass equivalents in the correct
444 // positions. But those equivalent passes aren't powerful enough yet.
445 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
446 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
447 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
448 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000449 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
450
Chandler Carruth71fd2702018-05-30 02:46:45 +0000451 // Simplify the loop body. We do this initially to clean up after other loop
452 // passes run, either when iterating on a loop or on inner loops with
453 // implications on the outer loop.
454 LPM1.addPass(LoopInstSimplifyPass());
455 LPM1.addPass(LoopSimplifyCFGPass());
456
Chandler Carruthe3f50642016-12-22 06:59:15 +0000457 // Rotate Loop - disable header duplication at -Oz
458 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000459 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000460 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000461 LPM2.addPass(IndVarSimplifyPass());
462 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000463
464 for (auto &C : LateLoopOptimizationsEPCallbacks)
465 C(LPM2, Level);
466
Chandler Carruth79b733b2017-01-26 23:21:17 +0000467 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000468 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000469 // because it changes IR to makes profile annotation in back compile
470 // inaccurate.
Alina Sbirleae4b27862019-05-23 19:35:40 +0000471 if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
472 PGOOpt->Action != PGOOptions::SampleUse) &&
473 PTO.LoopUnrolling)
Eric Christopherc3649a02019-10-14 22:56:07 +0000474 LPM2.addPass(LoopFullUnrollPass(Level, /*OnlyWhenForced=*/false,
475 PTO.ForgetAllSCEVInLoopUnroll));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000476
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000477 for (auto &C : LoopOptimizerEndEPCallbacks)
478 C(LPM2, Level);
479
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000480 // We provide the opt remark emitter pass for LICM to use. We only need to do
481 // this once as it is immutable.
482 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea74251792019-08-21 17:00:57 +0000483 FPM.addPass(createFunctionToLoopPassAdaptor(
484 std::move(LPM1), EnableMSSALoopDependency, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000485 FPM.addPass(SimplifyCFGPass());
486 FPM.addPass(InstCombinePass());
Alina Sbirlea74251792019-08-21 17:00:57 +0000487 // The loop passes in LPM2 (IndVarSimplifyPass, LoopIdiomRecognizePass,
488 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
489 // *All* loop passes must preserve it, in order to be able to use it.
490 FPM.addPass(createFunctionToLoopPassAdaptor(
491 std::move(LPM2), /*UseMemorySSA=*/false, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000492
493 // Eliminate redundancies.
494 if (Level != O1) {
495 // These passes add substantial compile time so skip them at O1.
496 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000497 if (RunNewGVN)
498 FPM.addPass(NewGVNPass());
499 else
500 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000501 }
502
503 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
504 FPM.addPass(MemCpyOptPass());
505
506 // Sparse conditional constant propagation.
507 // FIXME: It isn't clear why we do this *after* loop passes rather than
508 // before...
509 FPM.addPass(SCCPPass());
510
511 // Delete dead bit computations (instcombine runs after to fold away the dead
512 // computations, and then ADCE will run later to exploit any new DCE
513 // opportunities that creates).
514 FPM.addPass(BDCEPass());
515
516 // Run instcombine after redundancy and dead bit elimination to exploit
517 // opportunities opened up by them.
518 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000519 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000520
521 // Re-consider control flow based optimizations after redundancy elimination,
522 // redo DCE, etc.
523 FPM.addPass(JumpThreadingPass());
524 FPM.addPass(CorrelatedValuePropagationPass());
525 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000526 FPM.addPass(createFunctionToLoopPassAdaptor(
527 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
Alina Sbirlea74251792019-08-21 17:00:57 +0000528 EnableMSSALoopDependency, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000529
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000530 for (auto &C : ScalarOptimizerLateEPCallbacks)
531 C(FPM, Level);
532
Chandler Carruthe3f50642016-12-22 06:59:15 +0000533 // Finally, do an expensive DCE pass to catch all the dead code exposed by
534 // the simplifications and basic cleanup after all the simplifications.
535 FPM.addPass(ADCEPass());
536 FPM.addPass(SimplifyCFGPass());
537 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000538 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000539
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000540 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000541 (PGOOpt->Action == PGOOptions::IRUse ||
542 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000543 FPM.addPass(ControlHeightReductionPass());
544
Chandler Carruthe3f50642016-12-22 06:59:15 +0000545 return FPM;
546}
547
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000548void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
549 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000550 bool RunProfileGen, bool IsCS,
551 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000552 std::string ProfileRemappingFile) {
Rong Xuca161fa2019-08-01 22:36:34 +0000553 assert(Level != O0 && "Not expecting O0 here!");
Davide Italiano513dfaa2017-02-13 15:26:22 +0000554 // Generally running simplification passes and the inliner with an high
555 // threshold results in smaller executables, but there may be cases where
556 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000557 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
558 // IsCS is true).
559 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000560 InlineParams IP;
561
562 // In the old pass manager, this is a cl::opt. Should still this be one?
563 IP.DefaultThreshold = 75;
564
565 // FIXME: The hint threshold has the same value used by the regular inliner.
566 // This should probably be lowered after performance testing.
567 // FIXME: this comment is cargo culted from the old pass manager, revisit).
568 IP.HintThreshold = 325;
569
570 CGSCCPassManager CGPipeline(DebugLogging);
571
572 CGPipeline.addPass(InlinerPass(IP));
573
574 FunctionPassManager FPM;
575 FPM.addPass(SROA());
576 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
577 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
578 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000579 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000580
Davide Italiano513dfaa2017-02-13 15:26:22 +0000581 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
582
583 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
Rong Xuca161fa2019-08-01 22:36:34 +0000584
585 // Delete anything that is now dead to make sure that we don't instrument
586 // dead code. Instrumentation can end up keeping dead code around and
587 // dramatically increase code size.
588 MPM.addPass(GlobalDCEPass());
Davide Italiano513dfaa2017-02-13 15:26:22 +0000589 }
590
Rong Xuca161fa2019-08-01 22:36:34 +0000591 if (!RunProfileGen) {
592 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
Rong Xudb29a3a2019-03-04 20:21:27 +0000593 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000594 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
595 // RequireAnalysisPass for PSI before subsequent non-module passes.
596 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Rong Xuca161fa2019-08-01 22:36:34 +0000597 return;
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000598 }
Rong Xuca161fa2019-08-01 22:36:34 +0000599
600 // Perform PGO instrumentation.
601 MPM.addPass(PGOInstrumentationGen(IsCS));
602
603 FunctionPassManager FPM;
Alina Sbirlea74251792019-08-21 17:00:57 +0000604 FPM.addPass(createFunctionToLoopPassAdaptor(
605 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
Rong Xuca161fa2019-08-01 22:36:34 +0000606 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
607
608 // Add the profile lowering pass.
609 InstrProfOptions Options;
610 if (!ProfileFile.empty())
611 Options.InstrProfileOutput = ProfileFile;
612 // Do counter promotion at Level greater than O0.
613 Options.DoCounterPromotion = true;
614 Options.UseBFIInPromotion = IsCS;
615 MPM.addPass(InstrProfiling(Options, IsCS));
616}
617
618void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
619 bool DebugLogging, bool RunProfileGen,
620 bool IsCS, std::string ProfileFile,
621 std::string ProfileRemappingFile) {
622 if (!RunProfileGen) {
623 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
624 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
625 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
626 // RequireAnalysisPass for PSI before subsequent non-module passes.
627 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
628 return;
629 }
630
631 // Perform PGO instrumentation.
632 MPM.addPass(PGOInstrumentationGen(IsCS));
633 // Add the profile lowering pass.
634 InstrProfOptions Options;
635 if (!ProfileFile.empty())
636 Options.InstrProfileOutput = ProfileFile;
637 // Do not do counter promotion at O0.
638 Options.DoCounterPromotion = false;
639 Options.UseBFIInPromotion = IsCS;
640 MPM.addPass(InstrProfiling(Options, IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000641}
642
Easwaran Raman8249fac2017-06-28 13:33:49 +0000643static InlineParams
644getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
645 auto O3 = PassBuilder::O3;
646 unsigned OptLevel = Level > O3 ? 2 : Level;
647 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
648 return getInlineParams(OptLevel, SizeLevel);
649}
650
Chandler Carruthe3f50642016-12-22 06:59:15 +0000651ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000652PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000653 ThinLTOPhase Phase,
654 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000655 ModulePassManager MPM(DebugLogging);
656
Rong Xudb29a3a2019-03-04 20:21:27 +0000657 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000658
659 // In ThinLTO mode, when flattened profile is used, all the available
660 // profile information will be annotated in PreLink phase so there is
661 // no need to load the profile again in PostLink.
662 bool LoadSampleProfile =
663 HasSampleProfile &&
664 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
665
666 // During the ThinLTO backend phase we perform early indirect call promotion
667 // here, before globalopt. Otherwise imported available_externally functions
668 // look unreferenced and are removed. If we are going to load the sample
669 // profile then defer until later.
670 // TODO: See if we can move later and consolidate with the location where
671 // we perform ICP when we are loading a sample profile.
672 // TODO: We pass HasSampleProfile (whether there was a sample profile file
673 // passed to the compile) to the SamplePGO flag of ICP. This is used to
674 // determine whether the new direct calls are annotated with prof metadata.
675 // Ideally this should be determined from whether the IR is annotated with
676 // sample profile, and not whether the a sample profile was provided on the
677 // command line. E.g. for flattened profiles where we will not be reloading
678 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
679 // provide the sample profile file.
680 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
681 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
682
Chandler Carruthe3f50642016-12-22 06:59:15 +0000683 // Do basic inference of function attributes from known properties of system
684 // libraries and other oracles.
685 MPM.addPass(InferFunctionAttrsPass());
686
687 // Create an early function pass manager to cleanup the output of the
688 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000689 FunctionPassManager EarlyFPM(DebugLogging);
690 EarlyFPM.addPass(SimplifyCFGPass());
691 EarlyFPM.addPass(SROA());
692 EarlyFPM.addPass(EarlyCSEPass());
693 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000694 if (Level == O3)
695 EarlyFPM.addPass(CallSiteSplittingPass());
696
Dehao Chen08f88312017-08-07 20:23:20 +0000697 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
698 // to convert bitcast to direct calls so that they can be inlined during the
699 // profile annotation prepration step.
700 // More details about SamplePGO design can be found in:
701 // https://research.google.com/pubs/pub45290.html
702 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000703 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000704 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000705 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000706
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000707 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000708 // Annotate sample profile right after early FPM to ensure freshness of
709 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000710 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000711 PGOOpt->ProfileRemappingFile,
712 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000713 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
714 // RequireAnalysisPass for PSI before subsequent non-module passes.
715 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000716 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
717 // for the profile annotation to be accurate in the ThinLTO backend.
718 if (Phase != ThinLTOPhase::PreLink)
719 // We perform early indirect call promotion here, before globalopt.
720 // This is important for the ThinLTO backend phase because otherwise
721 // imported available_externally functions look unreferenced and are
722 // removed.
723 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000724 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000725 }
726
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000727 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000728 // and prior to optimizing globals.
729 // FIXME: This position in the pipeline hasn't been carefully considered in
730 // years, it should be re-analyzed.
731 MPM.addPass(IPSCCPPass());
732
Matthew Simpsoncb585582017-10-25 13:40:08 +0000733 // Attach metadata to indirect call sites indicating the set of functions
734 // they may target at run-time. This should follow IPSCCP.
735 MPM.addPass(CalledValuePropagationPass());
736
Chandler Carruthe3f50642016-12-22 06:59:15 +0000737 // Optimize globals to try and fold them into constants.
738 MPM.addPass(GlobalOptPass());
739
740 // Promote any localized globals to SSA registers.
741 // FIXME: Should this instead by a run of SROA?
742 // FIXME: We should probably run instcombine and simplify-cfg afterward to
743 // delete control flows that are dead once globals have been folded to
744 // constants.
745 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
746
747 // Remove any dead arguments exposed by cleanups and constand folding
748 // globals.
749 MPM.addPass(DeadArgumentEliminationPass());
750
751 // Create a small function pass pipeline to cleanup after all the global
752 // optimizations.
753 FunctionPassManager GlobalCleanupPM(DebugLogging);
754 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000755 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
756
Chandler Carruthe3f50642016-12-22 06:59:15 +0000757 GlobalCleanupPM.addPass(SimplifyCFGPass());
758 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
759
Dehao Chen89d32262017-08-02 01:28:31 +0000760 // Add all the requested passes for instrumentation PGO, if requested.
761 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000762 (PGOOpt->Action == PGOOptions::IRInstr ||
763 PGOOpt->Action == PGOOptions::IRUse)) {
764 addPGOInstrPasses(MPM, DebugLogging, Level,
765 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
766 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000767 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000768 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000769 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000770 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
771 PGOOpt->CSAction == PGOOptions::CSIRInstr)
772 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000773
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000774 // Synthesize function entry counts for non-PGO compilation.
775 if (EnableSyntheticCounts && !PGOOpt)
776 MPM.addPass(SyntheticCountsPropagation());
777
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000778 // Require the GlobalsAA analysis for the module so we can query it within
779 // the CGSCC pipeline.
780 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000781
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000782 // Require the ProfileSummaryAnalysis for the module so we can query it within
783 // the inliner pass.
784 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
785
Chandler Carruthe3f50642016-12-22 06:59:15 +0000786 // Now begin the main postorder CGSCC pipeline.
787 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
788 // manager and trying to emulate its precise behavior. Much of this doesn't
789 // make a lot of sense and we should revisit the core CGSCC structure.
790 CGSCCPassManager MainCGPipeline(DebugLogging);
791
792 // Note: historically, the PruneEH pass was run first to deduce nounwind and
793 // generally clean up exception handling overhead. It isn't clear this is
794 // valuable as the inliner doesn't currently care whether it is inlining an
795 // invoke or a call.
796
797 // Run the inliner first. The theory is that we are walking bottom-up and so
798 // the callees have already been fully optimized, and we want to inline them
799 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000800 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000801 // because it makes profile annotation in the backend inaccurate.
802 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000803 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
804 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000805 IP.HotCallSiteThreshold = 0;
806 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000807
808 // Now deduce any function attributes based in the current code.
809 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
810
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000811 // When at O3 add argument promotion to the pass pipeline.
812 // FIXME: It isn't at all clear why this should be limited to O3.
813 if (Level == O3)
814 MainCGPipeline.addPass(ArgumentPromotionPass());
815
Chandler Carruthe3f50642016-12-22 06:59:15 +0000816 // Lastly, add the core function simplification pipeline nested inside the
817 // CGSCC walk.
818 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000819 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000820
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000821 for (auto &C : CGSCCOptimizerLateEPCallbacks)
822 C(MainCGPipeline, Level);
823
Chandler Carruth719ffe12017-02-12 05:38:04 +0000824 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
825 // to detect when we devirtualize indirect calls and iterate the SCC passes
826 // in that case to try and catch knock-on inlining or function attrs
827 // opportunities. Then we add it to the module pipeline by walking the SCCs
828 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000829 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000830 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000831 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000832
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000833 return MPM;
834}
835
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000836ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
837 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000838 ModulePassManager MPM(DebugLogging);
839
840 // Optimize globals now that the module is fully simplified.
841 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000842 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000843
Xinliang David Li126157c2017-05-22 16:41:57 +0000844 // Run partial inlining pass to partially inline functions that have
845 // large bodies.
846 if (RunPartialInlining)
847 MPM.addPass(PartialInlinerPass());
848
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000849 // Remove avail extern fns and globals definitions since we aren't compiling
850 // an object file for later LTO. For LTO we want to preserve these so they
851 // are eligible for inlining at link-time. Note if they are unreferenced they
852 // will be removed by GlobalDCE later, so this only impacts referenced
853 // available externally globals. Eventually they will be suppressed during
854 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
855 // may make globals referenced by available external functions dead and saves
Leonard Chan97dc6222019-06-20 19:44:51 +0000856 // running remaining passes on the eliminated functions. These should be
857 // preserved during prelinking for link-time inlining decisions.
858 if (!LTOPreLink)
859 MPM.addPass(EliminateAvailableExternallyPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000860
Manman Ren18295122019-02-28 20:13:38 +0000861 if (EnableOrderFileInstrumentation)
862 MPM.addPass(InstrOrderFilePass());
863
Chandler Carruthe3f50642016-12-22 06:59:15 +0000864 // Do RPO function attribute inference across the module to forward-propagate
865 // attributes where applicable.
866 // FIXME: Is this really an optimization rather than a canonicalization?
867 MPM.addPass(ReversePostOrderFunctionAttrsPass());
868
Rong Xudb29a3a2019-03-04 20:21:27 +0000869 // Do a post inline PGO instrumentation and use pass. This is a context
870 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
871 // cross-module inline has not been done yet. The context sensitive
872 // instrumentation is after all the inlines are done.
873 if (!LTOPreLink && PGOOpt) {
874 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
875 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
876 /* IsCS */ true, PGOOpt->CSProfileGenFile,
877 PGOOpt->ProfileRemappingFile);
878 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
879 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
880 /* IsCS */ true, PGOOpt->ProfileFile,
881 PGOOpt->ProfileRemappingFile);
882 }
883
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000884 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000885 // useful as the above will have inlined, DCE'ed, and function-attr
886 // propagated everything. We should at this point have a reasonably minimal
887 // and richly annotated call graph. By computing aliasing and mod/ref
888 // information for all local globals here, the late loop passes and notably
889 // the vectorizer will be able to use them to help recognize vectorizable
890 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000891 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000892
893 FunctionPassManager OptimizePM(DebugLogging);
894 OptimizePM.addPass(Float2IntPass());
Joerg Sonnenberger9681ea92019-10-14 16:15:14 +0000895 OptimizePM.addPass(LowerConstantIntrinsicsPass());
896
Chandler Carruthe3f50642016-12-22 06:59:15 +0000897 // FIXME: We need to run some loop optimizations to re-rotate loops after
898 // simplify-cfg and others undo their rotation.
899
900 // Optimize the loop execution. These passes operate on entire loop nests
901 // rather than on each loop in an inside-out manner, and so they are actually
902 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000903
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000904 for (auto &C : VectorizerStartEPCallbacks)
905 C(OptimizePM, Level);
906
Chandler Carrutha95ff382017-01-27 00:50:21 +0000907 // First rotate loops that may have been un-rotated by prior passes.
Alina Sbirlea74251792019-08-21 17:00:57 +0000908 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
909 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000910
911 // Distribute loops to allow partial vectorization. I.e. isolate dependences
912 // into separate loop that would otherwise inhibit vectorization. This is
913 // currently only performed for loops marked with the metadata
914 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000915 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000916
917 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000918 OptimizePM.addPass(LoopVectorizePass(
919 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000920
Chandler Carruthbaabda92017-01-27 01:32:26 +0000921 // Eliminate loads by forwarding stores from the previous iteration to loads
922 // of the current iteration.
923 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000924
925 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000926 OptimizePM.addPass(InstCombinePass());
927
Chandler Carrutha95ff382017-01-27 00:50:21 +0000928 // Now that we've formed fast to execute loop structures, we do further
929 // optimizations. These are run afterward as they might block doing complex
930 // analyses and transforms such as what are needed for loop vectorization.
931
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000932 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
933 // GVN, loop transforms, and others have already run, so it's now better to
934 // convert to more optimized IR using more aggressive simplify CFG options.
935 // The extra sinking transform can create larger basic blocks, so do this
936 // before SLP vectorization.
937 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
938 forwardSwitchCondToPhi(true).
939 convertSwitchToLookupTable(true).
940 needCanonicalLoops(false).
941 sinkCommonInsts(true)));
942
Chandler Carruthe3f50642016-12-22 06:59:15 +0000943 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000944 if (PTO.SLPVectorization)
945 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000946
Chandler Carruthe3f50642016-12-22 06:59:15 +0000947 OptimizePM.addPass(InstCombinePass());
948
949 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000950 // execution resources of an out-of-order processor. We also then need to
951 // clean up redundancies and loop invariant code.
952 // FIXME: It would be really good to use a loop-integrated instruction
953 // combiner for cleanup here so that the unrolling and LICM can be pipelined
954 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000955 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
Eric Christopherc3649a02019-10-14 22:56:07 +0000956 if (EnableUnrollAndJam && PTO.LoopUnrolling) {
David Green963401d2018-07-01 12:47:30 +0000957 OptimizePM.addPass(
958 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
959 }
Eric Christopherc3649a02019-10-14 22:56:07 +0000960 OptimizePM.addPass(LoopUnrollPass(
961 LoopUnrollOptions(Level, /*OnlyWhenForced=*/!PTO.LoopUnrolling,
962 PTO.ForgetAllSCEVInLoopUnroll)));
Michael Kruse72448522018-12-12 17:32:52 +0000963 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000964 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000965 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000966 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
967 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
Alina Sbirlea74251792019-08-21 17:00:57 +0000968 EnableMSSALoopDependency, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000969
970 // Now that we've vectorized and unrolled loops, we may have more refined
971 // alignment information, try to re-derive it here.
972 OptimizePM.addPass(AlignmentFromAssumptionsPass());
973
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000974 // Split out cold code. Splitting is done late to avoid hiding context from
975 // other optimizations and inadvertently regressing performance. The tradeoff
976 // is that this has a higher code size cost than splitting early.
977 if (EnableHotColdSplit && !LTOPreLink)
978 MPM.addPass(HotColdSplittingPass());
979
Chandler Carrutha95ff382017-01-27 00:50:21 +0000980 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
981 // canonicalization pass that enables other optimizations. As a result,
982 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
983 // result too early.
984 OptimizePM.addPass(LoopSinkPass());
985
986 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000987 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000988
Sanjay Patel6fd43912017-09-09 13:38:18 +0000989 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
990 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
991 // flattening of blocks.
992 OptimizePM.addPass(DivRemPairsPass());
993
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000994 // LoopSink (and other loop passes since the last simplifyCFG) might have
995 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
996 OptimizePM.addPass(SimplifyCFGPass());
997
Chandler Carruthc34f7892017-11-28 11:32:31 +0000998 // Optimize PHIs by speculating around them when profitable. Note that this
999 // pass needs to be run after any PRE or similar pass as it is essentially
Joerg Sonnenbergerec6ee792019-05-16 18:01:57 +00001000 // inserting redundancies into the program. This even includes SimplifyCFG.
Chandler Carruthc34f7892017-11-28 11:32:31 +00001001 OptimizePM.addPass(SpeculateAroundPHIsPass());
1002
Philip Pfaffe2d4effb2018-11-12 11:17:07 +00001003 for (auto &C : OptimizerLastEPCallbacks)
1004 C(OptimizePM, Level);
1005
Chandler Carrutha95ff382017-01-27 00:50:21 +00001006 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001007 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
1008
Michael J. Spencer7bb27672018-07-16 00:28:24 +00001009 MPM.addPass(CGProfilePass());
1010
Chandler Carruthe3f50642016-12-22 06:59:15 +00001011 // Now we need to do some global optimization transforms.
1012 // FIXME: It would seem like these should come first in the optimization
1013 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1014 // ordering here.
1015 MPM.addPass(GlobalDCEPass());
1016 MPM.addPass(ConstantMergePass());
1017
1018 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001019}
1020
Chandler Carruthe3f50642016-12-22 06:59:15 +00001021ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001022PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001023 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001024 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1025
1026 ModulePassManager MPM(DebugLogging);
1027
1028 // Force any function attributes we want the rest of the pipeline to observe.
1029 MPM.addPass(ForceFunctionAttrsPass());
1030
David Blaikie0c64f5a2018-01-23 01:25:20 +00001031 // Apply module pipeline start EP callback.
1032 for (auto &C : PipelineStartEPCallbacks)
1033 C(MPM);
1034
Dehao Chen08f88312017-08-07 20:23:20 +00001035 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001036 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1037
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001038 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001039 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
1040 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001041
1042 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001043 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001044
1045 return MPM;
1046}
1047
1048ModulePassManager
1049PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1050 bool DebugLogging) {
1051 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1052
1053 ModulePassManager MPM(DebugLogging);
1054
1055 // Force any function attributes we want the rest of the pipeline to observe.
1056 MPM.addPass(ForceFunctionAttrsPass());
1057
Dehao Chen08f88312017-08-07 20:23:20 +00001058 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001059 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1060
David Blaikie0c64f5a2018-01-23 01:25:20 +00001061 // Apply module pipeline start EP callback.
1062 for (auto &C : PipelineStartEPCallbacks)
1063 C(MPM);
1064
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001065 // If we are planning to perform ThinLTO later, we don't bloat the code with
1066 // unrolling/vectorization/... now. Just simplify the module as much as we
1067 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001068 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1069 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001070
1071 // Run partial inlining pass to partially inline functions that have
1072 // large bodies.
1073 // FIXME: It isn't clear whether this is really the right place to run this
1074 // in ThinLTO. Because there is another canonicalization and simplification
1075 // phase that will run after the thin link, running this here ends up with
1076 // less information than will be available later and it may grow functions in
1077 // ways that aren't beneficial.
1078 if (RunPartialInlining)
1079 MPM.addPass(PartialInlinerPass());
1080
1081 // Reduce the size of the IR as much as possible.
1082 MPM.addPass(GlobalOptPass());
1083
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001084 return MPM;
1085}
1086
Teresa Johnson28023db2018-07-19 14:51:32 +00001087ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1088 OptimizationLevel Level, bool DebugLogging,
1089 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001090 ModulePassManager MPM(DebugLogging);
1091
Teresa Johnson28023db2018-07-19 14:51:32 +00001092 if (ImportSummary) {
1093 // These passes import type identifier resolutions for whole-program
1094 // devirtualization and CFI. They must run early because other passes may
1095 // disturb the specific instruction patterns that these passes look for,
1096 // creating dependencies on resolutions that may not appear in the summary.
1097 //
1098 // For example, GVN may transform the pattern assume(type.test) appearing in
1099 // two basic blocks into assume(phi(type.test, type.test)), which would
1100 // transform a dependency on a WPD resolution into a dependency on a type
1101 // identifier resolution for CFI.
1102 //
1103 // Also, WPD has access to more precise information than ICP and can
1104 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001105 //
1106 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1107 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001108 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1109 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1110 }
1111
Teresa Johnson867bc392019-04-23 18:56:19 +00001112 if (Level == O0)
1113 return MPM;
1114
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001115 // Force any function attributes we want the rest of the pipeline to observe.
1116 MPM.addPass(ForceFunctionAttrsPass());
1117
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001118 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001119 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1120 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001121
1122 // Now add the optimization pipeline.
1123 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1124
1125 return MPM;
1126}
1127
1128ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001129PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1130 bool DebugLogging) {
1131 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001132 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001133 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001134 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001135}
1136
Teresa Johnson28023db2018-07-19 14:51:32 +00001137ModulePassManager
1138PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1139 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001140 ModulePassManager MPM(DebugLogging);
1141
Teresa Johnson867bc392019-04-23 18:56:19 +00001142 if (Level == O0) {
1143 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1144 // metadata and intrinsics.
1145 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1146 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1147 return MPM;
1148 }
1149
Rong Xudb29a3a2019-03-04 20:21:27 +00001150 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001151 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001152 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001153 PGOOpt->ProfileRemappingFile,
1154 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001155 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1156 // RequireAnalysisPass for PSI before subsequent non-module passes.
1157 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001158 }
1159
Davide Italiano089a9122017-01-24 00:57:39 +00001160 // Remove unused virtual tables to improve the quality of code generated by
1161 // whole-program devirtualization and bitset lowering.
1162 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001163
Davide Italiano089a9122017-01-24 00:57:39 +00001164 // Force any function attributes we want the rest of the pipeline to observe.
1165 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001166
Davide Italiano089a9122017-01-24 00:57:39 +00001167 // Do basic inference of function attributes from known properties of system
1168 // libraries and other oracles.
1169 MPM.addPass(InferFunctionAttrsPass());
1170
1171 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001172 FunctionPassManager EarlyFPM(DebugLogging);
1173 EarlyFPM.addPass(CallSiteSplittingPass());
1174 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1175
Davide Italiano089a9122017-01-24 00:57:39 +00001176 // Indirect call promotion. This should promote all the targets that are
1177 // left by the earlier promotion pass that promotes intra-module targets.
1178 // This two-step promotion is to save the compile time. For LTO, it should
1179 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001180 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001181 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001182 // Propagate constants at call sites into the functions they call. This
1183 // opens opportunities for globalopt (and inlining) by substituting function
1184 // pointers passed as arguments to direct uses of functions.
1185 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001186
1187 // Attach metadata to indirect call sites indicating the set of functions
1188 // they may target at run-time. This should follow IPSCCP.
1189 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001190 }
1191
1192 // Now deduce any function attributes based in the current code.
1193 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1194 PostOrderFunctionAttrsPass()));
1195
1196 // Do RPO function attribute inference across the module to forward-propagate
1197 // attributes where applicable.
1198 // FIXME: Is this really an optimization rather than a canonicalization?
1199 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1200
Eric Christopher721eaef2019-02-26 20:33:22 +00001201 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001202 MPM.addPass(GlobalSplitPass());
1203
1204 // Run whole program optimization of virtual call when the list of callees
1205 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001206 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001207
1208 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001209 if (Level == 1) {
1210 // The LowerTypeTestsPass needs to run to lower type metadata and the
1211 // type.test intrinsics. The pass does nothing if CFI is disabled.
1212 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001213 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001214 }
Davide Italiano089a9122017-01-24 00:57:39 +00001215
1216 // Optimize globals to try and fold them into constants.
1217 MPM.addPass(GlobalOptPass());
1218
1219 // Promote any localized globals to SSA registers.
1220 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1221
1222 // Linking modules together can lead to duplicate global constant, only
1223 // keep one copy of each constant.
1224 MPM.addPass(ConstantMergePass());
1225
1226 // Remove unused arguments from functions.
1227 MPM.addPass(DeadArgumentEliminationPass());
1228
1229 // Reduce the code after globalopt and ipsccp. Both can open up significant
1230 // simplification opportunities, and both can propagate functions through
1231 // function pointers. When this happens, we often have to resolve varargs
1232 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001233 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001234 if (Level == O3)
1235 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001236 PeepholeFPM.addPass(InstCombinePass());
1237 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1238
1239 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001240
1241 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1242 // generally clean up exception handling overhead. It isn't clear this is
1243 // valuable as the inliner doesn't currently care whether it is inlining an
1244 // invoke or a call.
1245 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001246 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1247 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001248
1249 // Optimize globals again after we ran the inliner.
1250 MPM.addPass(GlobalOptPass());
1251
1252 // Garbage collect dead functions.
1253 // FIXME: Add ArgumentPromotion pass after once it's ported.
1254 MPM.addPass(GlobalDCEPass());
1255
1256 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001257 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001258 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001259 invokePeepholeEPCallbacks(FPM, Level);
1260
Davide Italiano089a9122017-01-24 00:57:39 +00001261 FPM.addPass(JumpThreadingPass());
1262
Rong Xudb29a3a2019-03-04 20:21:27 +00001263 // Do a post inline PGO instrumentation and use pass. This is a context
1264 // sensitive PGO pass.
1265 if (PGOOpt) {
1266 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1267 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1268 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1269 PGOOpt->ProfileRemappingFile);
1270 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1271 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1272 /* IsCS */ true, PGOOpt->ProfileFile,
1273 PGOOpt->ProfileRemappingFile);
1274 }
1275
Davide Italiano089a9122017-01-24 00:57:39 +00001276 // Break up allocas
1277 FPM.addPass(SROA());
1278
Robert Lougherf2158a82019-03-20 19:08:18 +00001279 // LTO provides additional opportunities for tailcall elimination due to
1280 // link-time inlining, and visibility of nocapture attribute.
1281 FPM.addPass(TailCallElimPass());
1282
Davide Italiano089a9122017-01-24 00:57:39 +00001283 // Run a few AA driver optimizations here and now to cleanup the code.
1284 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1285
1286 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1287 PostOrderFunctionAttrsPass()));
1288 // FIXME: here we run IP alias analysis in the legacy PM.
1289
1290 FunctionPassManager MainFPM;
1291
1292 // FIXME: once we fix LoopPass Manager, add LICM here.
1293 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001294 if (RunNewGVN)
1295 MainFPM.addPass(NewGVNPass());
1296 else
1297 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001298
1299 // Remove dead memcpy()'s.
1300 MainFPM.addPass(MemCpyOptPass());
1301
1302 // Nuke dead stores.
1303 MainFPM.addPass(DSEPass());
1304
1305 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001306 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001307 // loopVectorize. Enable them once the remaining issue with LPM
1308 // are sorted out.
1309
1310 MainFPM.addPass(InstCombinePass());
1311 MainFPM.addPass(SimplifyCFGPass());
1312 MainFPM.addPass(SCCPPass());
1313 MainFPM.addPass(InstCombinePass());
1314 MainFPM.addPass(BDCEPass());
1315
1316 // FIXME: We may want to run SLPVectorizer here.
1317 // After vectorization, assume intrinsics may tell us more
1318 // about pointer alignments.
1319#if 0
1320 MainFPM.add(AlignmentFromAssumptionsPass());
1321#endif
1322
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001323 // FIXME: Conditionally run LoadCombine here, after it's ported
1324 // (in case we still have this pass, given its questionable usefulness).
1325
Davide Italiano089a9122017-01-24 00:57:39 +00001326 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001327 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001328 MainFPM.addPass(JumpThreadingPass());
1329 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1330
1331 // Create a function that performs CFI checks for cross-DSO calls with
1332 // targets in the current module.
1333 MPM.addPass(CrossDSOCFIPass());
1334
1335 // Lower type metadata and the type.test intrinsic. This pass supports
1336 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1337 // to be run at link time if CFI is enabled. This pass does nothing if
1338 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001339 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001340
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001341 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1342 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1343 if (EnableHotColdSplit)
1344 MPM.addPass(HotColdSplittingPass());
1345
Davide Italiano089a9122017-01-24 00:57:39 +00001346 // Add late LTO optimization passes.
1347 // Delete basic blocks, which optimization passes may have killed.
1348 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1349
1350 // Drop bodies of available eternally objects to improve GlobalDCE.
1351 MPM.addPass(EliminateAvailableExternallyPass());
1352
1353 // Now that we have optimized the program, discard unreachable functions.
1354 MPM.addPass(GlobalDCEPass());
1355
Eric Christopher86e2f162019-05-03 00:15:23 +00001356 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001357 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001358}
1359
Chandler Carruth060ad612016-12-23 20:38:19 +00001360AAManager PassBuilder::buildDefaultAAPipeline() {
1361 AAManager AA;
1362
1363 // The order in which these are registered determines their priority when
1364 // being queried.
1365
1366 // First we register the basic alias analysis that provides the majority of
1367 // per-function local AA logic. This is a stateless, on-demand local set of
1368 // AA techniques.
1369 AA.registerFunctionAnalysis<BasicAA>();
1370
1371 // Next we query fast, specialized alias analyses that wrap IR-embedded
1372 // information about aliasing.
1373 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1374 AA.registerFunctionAnalysis<TypeBasedAA>();
1375
1376 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001377 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1378 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001379 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001380 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001381
1382 return AA;
1383}
1384
Chandler Carruth241bf242016-08-03 07:44:48 +00001385static Optional<int> parseRepeatPassName(StringRef Name) {
1386 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1387 return None;
1388 int Count;
1389 if (Name.getAsInteger(0, Count) || Count <= 0)
1390 return None;
1391 return Count;
1392}
1393
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001394static Optional<int> parseDevirtPassName(StringRef Name) {
1395 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1396 return None;
1397 int Count;
1398 if (Name.getAsInteger(0, Count) || Count <= 0)
1399 return None;
1400 return Count;
1401}
1402
Fedor Sergeevb7871402019-01-10 10:01:53 +00001403static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1404 if (!Name.consume_front(PassName))
1405 return false;
1406 // normal pass name w/o parameters == default parameters
1407 if (Name.empty())
1408 return true;
1409 return Name.startswith("<") && Name.endswith(">");
1410}
1411
1412namespace {
1413
1414/// This performs customized parsing of pass name with parameters.
1415///
1416/// We do not need parametrization of passes in textual pipeline very often,
1417/// yet on a rare occasion ability to specify parameters right there can be
1418/// useful.
1419///
1420/// \p Name - parameterized specification of a pass from a textual pipeline
1421/// is a string in a form of :
1422/// PassName '<' parameter-list '>'
1423///
1424/// Parameter list is being parsed by the parser callable argument, \p Parser,
1425/// It takes a string-ref of parameters and returns either StringError or a
1426/// parameter list in a form of a custom parameters type, all wrapped into
1427/// Expected<> template class.
1428///
1429template <typename ParametersParseCallableT>
1430auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1431 StringRef PassName) -> decltype(Parser(StringRef{})) {
1432 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1433
1434 StringRef Params = Name;
1435 if (!Params.consume_front(PassName)) {
1436 assert(false &&
1437 "unable to strip pass name from parametrized pass specification");
1438 }
1439 if (Params.empty())
1440 return ParametersT{};
1441 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1442 assert(false && "invalid format for parametrized pass name");
1443 }
1444
1445 Expected<ParametersT> Result = Parser(Params);
1446 assert((Result || Result.template errorIsA<StringError>()) &&
1447 "Pass parameter parser can only return StringErrors.");
Saleem Abdulrasool418d1ea2019-10-27 18:29:58 -04001448 return Result;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001449}
1450
1451/// Parser of parameters for LoopUnroll pass.
1452Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1453 LoopUnrollOptions UnrollOpts;
1454 while (!Params.empty()) {
1455 StringRef ParamName;
1456 std::tie(ParamName, Params) = Params.split(';');
1457 int OptLevel = StringSwitch<int>(ParamName)
1458 .Case("O0", 0)
1459 .Case("O1", 1)
1460 .Case("O2", 2)
1461 .Case("O3", 3)
1462 .Default(-1);
1463 if (OptLevel >= 0) {
1464 UnrollOpts.setOptLevel(OptLevel);
1465 continue;
1466 }
Serguei Katkova4476882019-09-19 06:57:29 +00001467 if (ParamName.consume_front("full-unroll-max=")) {
1468 int Count;
1469 if (ParamName.getAsInteger(0, Count))
1470 return make_error<StringError>(
1471 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1472 inconvertibleErrorCode());
1473 UnrollOpts.setFullUnrollMaxCount(Count);
1474 continue;
1475 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001476
1477 bool Enable = !ParamName.consume_front("no-");
1478 if (ParamName == "partial") {
1479 UnrollOpts.setPartial(Enable);
1480 } else if (ParamName == "peeling") {
1481 UnrollOpts.setPeeling(Enable);
Serguei Katkovde67aff2019-08-02 09:32:52 +00001482 } else if (ParamName == "profile-peeling") {
1483 UnrollOpts.setProfileBasedPeeling(Enable);
Fedor Sergeevb7871402019-01-10 10:01:53 +00001484 } else if (ParamName == "runtime") {
1485 UnrollOpts.setRuntime(Enable);
1486 } else if (ParamName == "upperbound") {
1487 UnrollOpts.setUpperBound(Enable);
1488 } else {
1489 return make_error<StringError>(
1490 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1491 inconvertibleErrorCode());
1492 }
1493 }
1494 return UnrollOpts;
1495}
1496
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001497Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1498 MemorySanitizerOptions Result;
1499 while (!Params.empty()) {
1500 StringRef ParamName;
1501 std::tie(ParamName, Params) = Params.split(';');
1502
1503 if (ParamName == "recover") {
1504 Result.Recover = true;
1505 } else if (ParamName == "kernel") {
1506 Result.Kernel = true;
1507 } else if (ParamName.consume_front("track-origins=")) {
1508 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1509 return make_error<StringError>(
1510 formatv("invalid argument to MemorySanitizer pass track-origins "
1511 "parameter: '{0}' ",
1512 ParamName)
1513 .str(),
1514 inconvertibleErrorCode());
1515 } else {
1516 return make_error<StringError>(
1517 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1518 .str(),
1519 inconvertibleErrorCode());
1520 }
1521 }
1522 return Result;
1523}
1524
Serguei Katkovf5432832019-04-15 08:57:53 +00001525/// Parser of parameters for SimplifyCFG pass.
1526Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1527 SimplifyCFGOptions Result;
1528 while (!Params.empty()) {
1529 StringRef ParamName;
1530 std::tie(ParamName, Params) = Params.split(';');
1531
1532 bool Enable = !ParamName.consume_front("no-");
1533 if (ParamName == "forward-switch-cond") {
1534 Result.forwardSwitchCondToPhi(Enable);
1535 } else if (ParamName == "switch-to-lookup") {
1536 Result.convertSwitchToLookupTable(Enable);
1537 } else if (ParamName == "keep-loops") {
1538 Result.needCanonicalLoops(Enable);
1539 } else if (ParamName == "sink-common-insts") {
1540 Result.sinkCommonInsts(Enable);
1541 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1542 APInt BonusInstThreshold;
1543 if (ParamName.getAsInteger(0, BonusInstThreshold))
1544 return make_error<StringError>(
1545 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1546 "parameter: '{0}' ",
1547 ParamName).str(),
1548 inconvertibleErrorCode());
1549 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1550 } else {
1551 return make_error<StringError>(
1552 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1553 inconvertibleErrorCode());
1554 }
1555 }
1556 return Result;
1557}
1558
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001559/// Parser of parameters for LoopVectorize pass.
1560Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1561 LoopVectorizeOptions Opts;
1562 while (!Params.empty()) {
1563 StringRef ParamName;
1564 std::tie(ParamName, Params) = Params.split(';');
1565
1566 bool Enable = !ParamName.consume_front("no-");
1567 if (ParamName == "interleave-forced-only") {
1568 Opts.setInterleaveOnlyWhenForced(Enable);
1569 } else if (ParamName == "vectorize-forced-only") {
1570 Opts.setVectorizeOnlyWhenForced(Enable);
1571 } else {
1572 return make_error<StringError>(
1573 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1574 inconvertibleErrorCode());
1575 }
1576 }
1577 return Opts;
1578}
1579
Serguei Katkov40a3b962019-04-22 10:35:07 +00001580Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1581 bool Result = false;
1582 while (!Params.empty()) {
1583 StringRef ParamName;
1584 std::tie(ParamName, Params) = Params.split(';');
1585
1586 bool Enable = !ParamName.consume_front("no-");
1587 if (ParamName == "nontrivial") {
1588 Result = Enable;
1589 } else {
1590 return make_error<StringError>(
1591 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1592 .str(),
1593 inconvertibleErrorCode());
1594 }
1595 }
1596 return Result;
1597}
Denis Bakhvalov58f172f2019-09-05 17:00:32 +00001598
1599Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) {
1600 bool Result = false;
1601 while (!Params.empty()) {
1602 StringRef ParamName;
1603 std::tie(ParamName, Params) = Params.split(';');
1604
1605 bool Enable = !ParamName.consume_front("no-");
1606 if (ParamName == "split-footer-bb") {
1607 Result = Enable;
1608 } else {
1609 return make_error<StringError>(
1610 formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
1611 ParamName)
1612 .str(),
1613 inconvertibleErrorCode());
1614 }
1615 }
1616 return Result;
1617}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001618} // namespace
1619
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001620/// Tests whether a pass name starts with a valid prefix for a default pipeline
1621/// alias.
1622static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1623 return Name.startswith("default") || Name.startswith("thinlto") ||
1624 Name.startswith("lto");
1625}
1626
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001627/// Tests whether registered callbacks will accept a given pass name.
1628///
1629/// When parsing a pipeline text, the type of the outermost pipeline may be
1630/// omitted, in which case the type is automatically determined from the first
1631/// pass name in the text. This may be a name that is handled through one of the
1632/// callbacks. We check this through the oridinary parsing callbacks by setting
1633/// up a dummy PassManager in order to not force the client to also handle this
1634/// type of query.
1635template <typename PassManagerT, typename CallbacksT>
1636static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1637 if (!Callbacks.empty()) {
1638 PassManagerT DummyPM;
1639 for (auto &CB : Callbacks)
1640 if (CB(Name, DummyPM, {}))
1641 return true;
1642 }
1643 return false;
1644}
1645
1646template <typename CallbacksT>
1647static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001648 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001649 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001650 return DefaultAliasRegex.match(Name);
1651
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001652 // Explicitly handle pass manager names.
1653 if (Name == "module")
1654 return true;
1655 if (Name == "cgscc")
1656 return true;
1657 if (Name == "function")
1658 return true;
1659
Chandler Carruth241bf242016-08-03 07:44:48 +00001660 // Explicitly handle custom-parsed pass names.
1661 if (parseRepeatPassName(Name))
1662 return true;
1663
Chandler Carruth74a8a222016-06-17 07:15:29 +00001664#define MODULE_PASS(NAME, CREATE_PASS) \
1665 if (Name == NAME) \
1666 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001667#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001668 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001669 return true;
1670#include "PassRegistry.def"
1671
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001672 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001673}
1674
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001675template <typename CallbacksT>
1676static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001677 // Explicitly handle pass manager names.
1678 if (Name == "cgscc")
1679 return true;
1680 if (Name == "function")
1681 return true;
1682
Chandler Carruth241bf242016-08-03 07:44:48 +00001683 // Explicitly handle custom-parsed pass names.
1684 if (parseRepeatPassName(Name))
1685 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001686 if (parseDevirtPassName(Name))
1687 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001688
Chandler Carruth74a8a222016-06-17 07:15:29 +00001689#define CGSCC_PASS(NAME, CREATE_PASS) \
1690 if (Name == NAME) \
1691 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001692#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001693 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001694 return true;
1695#include "PassRegistry.def"
1696
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001697 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001698}
1699
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001700template <typename CallbacksT>
1701static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001702 // Explicitly handle pass manager names.
1703 if (Name == "function")
1704 return true;
Alina Sbirlea74251792019-08-21 17:00:57 +00001705 if (Name == "loop" || Name == "loop-mssa")
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001706 return true;
1707
Chandler Carruth241bf242016-08-03 07:44:48 +00001708 // Explicitly handle custom-parsed pass names.
1709 if (parseRepeatPassName(Name))
1710 return true;
1711
Chandler Carruth74a8a222016-06-17 07:15:29 +00001712#define FUNCTION_PASS(NAME, CREATE_PASS) \
1713 if (Name == NAME) \
1714 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001715#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1716 if (checkParametrizedPassName(Name, NAME)) \
1717 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001718#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001719 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001720 return true;
1721#include "PassRegistry.def"
1722
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001723 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001724}
1725
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001726template <typename CallbacksT>
1727static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001728 // Explicitly handle pass manager names.
Alina Sbirlea74251792019-08-21 17:00:57 +00001729 if (Name == "loop" || Name == "loop-mssa")
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001730 return true;
1731
Chandler Carruth241bf242016-08-03 07:44:48 +00001732 // Explicitly handle custom-parsed pass names.
1733 if (parseRepeatPassName(Name))
1734 return true;
1735
Chandler Carruth74a8a222016-06-17 07:15:29 +00001736#define LOOP_PASS(NAME, CREATE_PASS) \
1737 if (Name == NAME) \
1738 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001739#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1740 if (checkParametrizedPassName(Name, NAME)) \
1741 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001742#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1743 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1744 return true;
1745#include "PassRegistry.def"
1746
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001747 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001748}
1749
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001750Optional<std::vector<PassBuilder::PipelineElement>>
1751PassBuilder::parsePipelineText(StringRef Text) {
1752 std::vector<PipelineElement> ResultPipeline;
1753
1754 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1755 &ResultPipeline};
1756 for (;;) {
1757 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1758 size_t Pos = Text.find_first_of(",()");
1759 Pipeline.push_back({Text.substr(0, Pos), {}});
1760
1761 // If we have a single terminating name, we're done.
1762 if (Pos == Text.npos)
1763 break;
1764
1765 char Sep = Text[Pos];
1766 Text = Text.substr(Pos + 1);
1767 if (Sep == ',')
1768 // Just a name ending in a comma, continue.
1769 continue;
1770
1771 if (Sep == '(') {
1772 // Push the inner pipeline onto the stack to continue processing.
1773 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1774 continue;
1775 }
1776
1777 assert(Sep == ')' && "Bogus separator!");
1778 // When handling the close parenthesis, we greedily consume them to avoid
1779 // empty strings in the pipeline.
1780 do {
1781 // If we try to pop the outer pipeline we have unbalanced parentheses.
1782 if (PipelineStack.size() == 1)
1783 return None;
1784
1785 PipelineStack.pop_back();
1786 } while (Text.consume_front(")"));
1787
1788 // Check if we've finished parsing.
1789 if (Text.empty())
1790 break;
1791
1792 // Otherwise, the end of an inner pipeline always has to be followed by
1793 // a comma, and then we can continue.
1794 if (!Text.consume_front(","))
1795 return None;
1796 }
1797
1798 if (PipelineStack.size() > 1)
1799 // Unbalanced paretheses.
1800 return None;
1801
1802 assert(PipelineStack.back() == &ResultPipeline &&
1803 "Wrong pipeline at the bottom of the stack!");
1804 return {std::move(ResultPipeline)};
1805}
1806
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001807Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1808 const PipelineElement &E,
1809 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001810 auto &Name = E.Name;
1811 auto &InnerPipeline = E.InnerPipeline;
1812
1813 // First handle complex passes like the pass managers which carry pipelines.
1814 if (!InnerPipeline.empty()) {
1815 if (Name == "module") {
1816 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001817 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1818 VerifyEachPass, DebugLogging))
1819 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001820 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001821 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001822 }
1823 if (Name == "cgscc") {
1824 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001825 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1826 DebugLogging))
1827 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001828 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001829 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001830 }
1831 if (Name == "function") {
1832 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001833 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1834 VerifyEachPass, DebugLogging))
1835 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001836 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001837 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001838 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001839 if (auto Count = parseRepeatPassName(Name)) {
1840 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001841 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1842 VerifyEachPass, DebugLogging))
1843 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001844 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001845 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001846 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001847
1848 for (auto &C : ModulePipelineParsingCallbacks)
1849 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001850 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001851
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001852 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001853 return make_error<StringError>(
1854 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1855 inconvertibleErrorCode());
1856 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001857 }
1858
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001859 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001860 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001861 SmallVector<StringRef, 3> Matches;
1862 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001863 return make_error<StringError>(
1864 formatv("unknown default pipeline alias '{0}'", Name).str(),
1865 inconvertibleErrorCode());
1866
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001867 assert(Matches.size() == 3 && "Must capture two matched strings!");
1868
Jordan Rosef85a95f2016-07-25 18:34:51 +00001869 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001870 .Case("O0", O0)
1871 .Case("O1", O1)
1872 .Case("O2", O2)
1873 .Case("O3", O3)
1874 .Case("Os", Os)
1875 .Case("Oz", Oz);
Rong Xuca161fa2019-08-01 22:36:34 +00001876 if (L == O0) {
1877 // Add instrumentation PGO passes -- at O0 we can still do PGO.
1878 if (PGOOpt && Matches[1] != "thinlto" &&
1879 (PGOOpt->Action == PGOOptions::IRInstr ||
1880 PGOOpt->Action == PGOOptions::IRUse))
1881 addPGOInstrPassesForO0(
1882 MPM, DebugLogging,
1883 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1884 /* IsCS */ false, PGOOpt->ProfileFile,
1885 PGOOpt->ProfileRemappingFile);
1886 // Do nothing else at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001887 return Error::success();
Rong Xuca161fa2019-08-01 22:36:34 +00001888 }
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001889
1890 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001891 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001892 } else if (Matches[1] == "thinlto-pre-link") {
1893 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1894 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001895 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001896 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001897 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001898 } else {
1899 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001900 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001901 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001902 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001903 }
1904
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001905 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001906#define MODULE_PASS(NAME, CREATE_PASS) \
1907 if (Name == NAME) { \
1908 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001909 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001910 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001911#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1912 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001913 MPM.addPass( \
1914 RequireAnalysisPass< \
1915 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001916 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001917 } \
1918 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001919 MPM.addPass(InvalidateAnalysisPass< \
1920 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001921 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001922 }
1923#include "PassRegistry.def"
1924
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001925 for (auto &C : ModulePipelineParsingCallbacks)
1926 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001927 return Error::success();
1928 return make_error<StringError>(
1929 formatv("unknown module pass '{0}'", Name).str(),
1930 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001931}
1932
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001933Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1934 const PipelineElement &E, bool VerifyEachPass,
1935 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001936 auto &Name = E.Name;
1937 auto &InnerPipeline = E.InnerPipeline;
1938
1939 // First handle complex passes like the pass managers which carry pipelines.
1940 if (!InnerPipeline.empty()) {
1941 if (Name == "cgscc") {
1942 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001943 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1944 VerifyEachPass, DebugLogging))
1945 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001946 // Add the nested pass manager with the appropriate adaptor.
1947 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001948 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001949 }
1950 if (Name == "function") {
1951 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001952 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1953 VerifyEachPass, DebugLogging))
1954 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001955 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001956 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001957 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001958 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001959 if (auto Count = parseRepeatPassName(Name)) {
1960 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001961 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1962 VerifyEachPass, DebugLogging))
1963 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001964 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001965 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001966 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001967 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1968 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001969 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1970 VerifyEachPass, DebugLogging))
1971 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001972 CGPM.addPass(
1973 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001974 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001975 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001976
1977 for (auto &C : CGSCCPipelineParsingCallbacks)
1978 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001979 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001980
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001981 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001982 return make_error<StringError>(
1983 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1984 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001985 }
1986
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001987// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001988#define CGSCC_PASS(NAME, CREATE_PASS) \
1989 if (Name == NAME) { \
1990 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001991 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001992 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001993#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1994 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001995 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001996 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001997 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1998 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001999 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00002000 } \
2001 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00002002 CGPM.addPass(InvalidateAnalysisPass< \
2003 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002004 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002005 }
2006#include "PassRegistry.def"
2007
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002008 for (auto &C : CGSCCPipelineParsingCallbacks)
2009 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002010 return Error::success();
2011 return make_error<StringError>(
2012 formatv("unknown cgscc pass '{0}'", Name).str(),
2013 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00002014}
2015
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002016Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
2017 const PipelineElement &E,
2018 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002019 auto &Name = E.Name;
2020 auto &InnerPipeline = E.InnerPipeline;
2021
2022 // First handle complex passes like the pass managers which carry pipelines.
2023 if (!InnerPipeline.empty()) {
2024 if (Name == "function") {
2025 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002026 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2027 VerifyEachPass, DebugLogging))
2028 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002029 // Add the nested pass manager with the appropriate adaptor.
2030 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002031 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002032 }
Alina Sbirlea74251792019-08-21 17:00:57 +00002033 if (Name == "loop" || Name == "loop-mssa") {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002034 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002035 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
2036 DebugLogging))
2037 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002038 // Add the nested pass manager with the appropriate adaptor.
Alina Sbirlea74251792019-08-21 17:00:57 +00002039 bool UseMemorySSA = (Name == "loop-mssa");
2040 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
2041 DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002042 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002043 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002044 if (auto Count = parseRepeatPassName(Name)) {
2045 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002046 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2047 VerifyEachPass, DebugLogging))
2048 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002049 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002050 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002051 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002052
2053 for (auto &C : FunctionPipelineParsingCallbacks)
2054 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002055 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002056
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002057 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002058 return make_error<StringError>(
2059 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
2060 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002061 }
2062
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002063// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00002064#define FUNCTION_PASS(NAME, CREATE_PASS) \
2065 if (Name == NAME) { \
2066 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002067 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00002068 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00002069#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2070 if (checkParametrizedPassName(Name, NAME)) { \
2071 auto Params = parsePassParameters(PARSER, Name, NAME); \
2072 if (!Params) \
2073 return Params.takeError(); \
2074 FPM.addPass(CREATE_PASS(Params.get())); \
2075 return Error::success(); \
2076 }
Chandler Carruth628503e2015-01-06 02:10:51 +00002077#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
2078 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00002079 FPM.addPass( \
2080 RequireAnalysisPass< \
2081 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002082 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00002083 } \
2084 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00002085 FPM.addPass(InvalidateAnalysisPass< \
2086 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002087 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002088 }
2089#include "PassRegistry.def"
2090
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002091 for (auto &C : FunctionPipelineParsingCallbacks)
2092 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002093 return Error::success();
2094 return make_error<StringError>(
2095 formatv("unknown function pass '{0}'", Name).str(),
2096 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002097}
2098
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002099Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2100 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002101 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002102 auto &InnerPipeline = E.InnerPipeline;
2103
2104 // First handle complex passes like the pass managers which carry pipelines.
2105 if (!InnerPipeline.empty()) {
2106 if (Name == "loop") {
2107 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002108 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2109 VerifyEachPass, DebugLogging))
2110 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002111 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002112 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002113 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002114 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002115 if (auto Count = parseRepeatPassName(Name)) {
2116 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002117 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2118 VerifyEachPass, DebugLogging))
2119 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002120 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002121 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002122 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002123
2124 for (auto &C : LoopPipelineParsingCallbacks)
2125 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002126 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002127
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002128 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002129 return make_error<StringError>(
2130 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2131 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002132 }
2133
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002134// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002135#define LOOP_PASS(NAME, CREATE_PASS) \
2136 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002137 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002138 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002139 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002140#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2141 if (checkParametrizedPassName(Name, NAME)) { \
2142 auto Params = parsePassParameters(PARSER, Name, NAME); \
2143 if (!Params) \
2144 return Params.takeError(); \
2145 LPM.addPass(CREATE_PASS(Params.get())); \
2146 return Error::success(); \
2147 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002148#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2149 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002150 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002151 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2152 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2153 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002154 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002155 } \
2156 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002157 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002158 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002159 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002160 }
2161#include "PassRegistry.def"
2162
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002163 for (auto &C : LoopPipelineParsingCallbacks)
2164 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002165 return Error::success();
2166 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2167 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002168}
2169
Chandler Carruthedf59962016-02-18 09:45:17 +00002170bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002171#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2172 if (Name == NAME) { \
2173 AA.registerModuleAnalysis< \
2174 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2175 return true; \
2176 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002177#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2178 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002179 AA.registerFunctionAnalysis< \
2180 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002181 return true; \
2182 }
2183#include "PassRegistry.def"
2184
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002185 for (auto &C : AAParsingCallbacks)
2186 if (C(Name, AA))
2187 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002188 return false;
2189}
2190
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002191Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002192 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002193 bool VerifyEachPass,
2194 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002195 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002196 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2197 return Err;
2198 // FIXME: No verifier support for Loop passes!
2199 }
2200 return Error::success();
2201}
2202
2203Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2204 ArrayRef<PipelineElement> Pipeline,
2205 bool VerifyEachPass,
2206 bool DebugLogging) {
2207 for (const auto &Element : Pipeline) {
2208 if (auto Err =
2209 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2210 return Err;
2211 if (VerifyEachPass)
2212 FPM.addPass(VerifierPass());
2213 }
2214 return Error::success();
2215}
2216
2217Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2218 ArrayRef<PipelineElement> Pipeline,
2219 bool VerifyEachPass,
2220 bool DebugLogging) {
2221 for (const auto &Element : Pipeline) {
2222 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2223 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002224 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002225 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002226 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002227}
2228
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002229void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2230 FunctionAnalysisManager &FAM,
2231 CGSCCAnalysisManager &CGAM,
2232 ModuleAnalysisManager &MAM) {
2233 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2234 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002235 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2236 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2237 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2238 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2239 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2240}
2241
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002242Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2243 ArrayRef<PipelineElement> Pipeline,
2244 bool VerifyEachPass,
2245 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002246 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002247 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2248 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002249 if (VerifyEachPass)
2250 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002251 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002252 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002253}
2254
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002255// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002256// FIXME: Should this routine accept a TargetMachine or require the caller to
2257// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002258Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2259 StringRef PipelineText,
2260 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002261 auto Pipeline = parsePipelineText(PipelineText);
2262 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002263 return make_error<StringError>(
2264 formatv("invalid pipeline '{0}'", PipelineText).str(),
2265 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002266
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002267 // If the first name isn't at the module layer, wrap the pipeline up
2268 // automatically.
2269 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002270
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002271 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2272 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002273 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002274 } else if (isFunctionPassName(FirstName,
2275 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002276 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002277 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002278 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002279 } else {
2280 for (auto &C : TopLevelPipelineParsingCallbacks)
2281 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002282 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002283
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002284 // Unknown pass or pipeline name!
2285 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2286 return make_error<StringError>(
2287 formatv("unknown {0} name '{1}'",
2288 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2289 .str(),
2290 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002291 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002292 }
2293
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002294 if (auto Err =
2295 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2296 return Err;
2297 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002298}
Chandler Carruthedf59962016-02-18 09:45:17 +00002299
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002300// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002301Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2302 StringRef PipelineText,
2303 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002304 auto Pipeline = parsePipelineText(PipelineText);
2305 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002306 return make_error<StringError>(
2307 formatv("invalid pipeline '{0}'", PipelineText).str(),
2308 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002309
2310 StringRef FirstName = Pipeline->front().Name;
2311 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002312 return make_error<StringError>(
2313 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2314 PipelineText)
2315 .str(),
2316 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002317
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002318 if (auto Err =
2319 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2320 return Err;
2321 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002322}
2323
2324// Primary pass pipeline description parsing routine for a \c
2325// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002326Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2327 StringRef PipelineText,
2328 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002329 auto Pipeline = parsePipelineText(PipelineText);
2330 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002331 return make_error<StringError>(
2332 formatv("invalid pipeline '{0}'", PipelineText).str(),
2333 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002334
2335 StringRef FirstName = Pipeline->front().Name;
2336 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002337 return make_error<StringError>(
2338 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2339 PipelineText)
2340 .str(),
2341 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002342
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002343 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2344 DebugLogging))
2345 return Err;
2346 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002347}
2348
2349// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002350Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2351 StringRef PipelineText,
2352 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002353 auto Pipeline = parsePipelineText(PipelineText);
2354 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002355 return make_error<StringError>(
2356 formatv("invalid pipeline '{0}'", PipelineText).str(),
2357 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002358
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002359 if (auto Err =
2360 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2361 return Err;
2362
2363 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002364}
2365
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002366Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002367 // If the pipeline just consists of the word 'default' just replace the AA
2368 // manager with our default one.
2369 if (PipelineText == "default") {
2370 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002371 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002372 }
2373
Chandler Carruthedf59962016-02-18 09:45:17 +00002374 while (!PipelineText.empty()) {
2375 StringRef Name;
2376 std::tie(Name, PipelineText) = PipelineText.split(',');
2377 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002378 return make_error<StringError>(
2379 formatv("unknown alias analysis name '{0}'", Name).str(),
2380 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002381 }
2382
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002383 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002384}