blob: 25c5a422e5a4f81c5f7543b436b7b253cd6bb553 [file] [log] [blame]
Chandler Carruth1ff77242015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth66445382014-01-11 08:16:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth66445382014-01-11 08:16:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9///
Chandler Carruth1ff77242015-03-07 09:02:36 +000010/// This file provides the implementation of the PassBuilder based on our
11/// static pass registry as well as related functionality. It also provides
12/// helpers to aid in analyzing, debugging, and testing passes and pass
13/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000014///
15//===----------------------------------------------------------------------===//
16
Chandler Carruth1ff77242015-03-07 09:02:36 +000017#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000018#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000019#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000020#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000021#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000022#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000024#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000025#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000026#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000028#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000029#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000030#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000031#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000032#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000033#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000034#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000035#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000036#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000037#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000038#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000039#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000040#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000041#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000042#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000043#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000044#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000045#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000046#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000049#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000050#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000051#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000052#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000053#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000054#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000055#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000057#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000058#include "llvm/IR/PassManager.h"
Fedor Sergeeva2ed4482019-03-31 10:15:39 +000059#include "llvm/IR/SafepointIRVerifier.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000091#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000092#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000093#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000094#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000095#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000096#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Manman Ren18295122019-02-28 20:13:38 +000097#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000098#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000099#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000100#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000101#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000102#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000103#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000104#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000105#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000106#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000107#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000108#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000109#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000110#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000111#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000112#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000113#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000114#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000115#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000116#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000117#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000118#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000119#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000120#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000121#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000122#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000123#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000124#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000125#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000126#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000127#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000128#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000129#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000130#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000131#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000132#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000133#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000134#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000135#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000136#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000137#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000138#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000139#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000140#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000141#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000142#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000143#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000144#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000145#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000146#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000147#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000148#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000149#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000150#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000151#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000152#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000153#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000154#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000155#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000156#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000157#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000158#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000159#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000160#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000161#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000162#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000163#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000164#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000165#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000166#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000167#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000168#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000169#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000170#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000171#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000172#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000173
Chandler Carruth66445382014-01-11 08:16:35 +0000174using namespace llvm;
175
Chandler Carruth719ffe12017-02-12 05:38:04 +0000176static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
177 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000178static cl::opt<bool>
179 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
180 cl::Hidden, cl::ZeroOrMore,
181 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000182
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000183static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000184 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000185 cl::Hidden, cl::ZeroOrMore,
186 cl::desc("Run NewGVN instead of GVN"));
187
Geoff Berry3cca1da2017-06-10 15:20:03 +0000188static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000189 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
190 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000191
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000192static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000193 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
194 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000195
Davide Italianobe1b6a92017-06-03 23:18:29 +0000196static cl::opt<bool> EnableGVNSink(
197 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
198 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
199
David Green963401d2018-07-01 12:47:30 +0000200static cl::opt<bool> EnableUnrollAndJam(
201 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
202 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
203
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000204static cl::opt<bool> EnableSyntheticCounts(
205 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
206 cl::desc("Run synthetic function entry count generation "
207 "pass"));
208
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000209static Regex DefaultAliasRegex(
210 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000211
Eric Christophereff3b6f2019-04-18 06:17:40 +0000212// This option is used in simplifying testing SampleFDO optimizations for
213// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000214static cl::opt<bool>
215 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
216 cl::desc("Enable control height reduction optimization (CHR)"));
217
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000218PipelineTuningOptions::PipelineTuningOptions() {
219 LoopInterleaving = EnableLoopInterleaving;
220 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000221 LicmMssaOptCap = SetLicmMssaOptCap;
222 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000223}
224
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000225extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000226extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000227
Wei Mi3bcccdf2019-01-17 20:48:34 +0000228extern cl::opt<bool> FlattenedProfileUsed;
229
Chandler Carruthe3f50642016-12-22 06:59:15 +0000230static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
231 switch (Level) {
232 case PassBuilder::O0:
233 case PassBuilder::O1:
234 case PassBuilder::O2:
235 case PassBuilder::O3:
236 return false;
237
238 case PassBuilder::Os:
239 case PassBuilder::Oz:
240 return true;
241 }
242 llvm_unreachable("Invalid optimization level!");
243}
244
Chandler Carruth66445382014-01-11 08:16:35 +0000245namespace {
246
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000247/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000248struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000249 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000250 return PreservedAnalyses::all();
251 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000252 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000253};
254
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000255/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000256class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
257 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000258 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000259
260public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000261 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000262 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000263 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000264};
265
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000266/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000267struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000268 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
269 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000270 return PreservedAnalyses::all();
271 }
272 static StringRef name() { return "NoOpCGSCCPass"; }
273};
274
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000275/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000276class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
277 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000278 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000279
280public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000281 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000282 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000283 return Result();
284 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000285 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000286};
287
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000288/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000289struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000290 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000291 return PreservedAnalyses::all();
292 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000293 static StringRef name() { return "NoOpFunctionPass"; }
294};
295
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000296/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000297class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
298 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000299 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000300
301public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000302 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000303 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000304 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000305};
306
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000307/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000308struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000309 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
310 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000311 return PreservedAnalyses::all();
312 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000313 static StringRef name() { return "NoOpLoopPass"; }
314};
315
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000316/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000317class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
318 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000319 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000320
321public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000322 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000323 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
324 return Result();
325 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000326 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000327};
328
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000329AnalysisKey NoOpModuleAnalysis::Key;
330AnalysisKey NoOpCGSCCAnalysis::Key;
331AnalysisKey NoOpFunctionAnalysis::Key;
332AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000333
Chandler Carruth66445382014-01-11 08:16:35 +0000334} // End anonymous namespace.
335
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000336void PassBuilder::invokePeepholeEPCallbacks(
337 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
338 for (auto &C : PeepholeEPCallbacks)
339 C(FPM, Level);
340}
341
Chandler Carruth1ff77242015-03-07 09:02:36 +0000342void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000343#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000344 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000345#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000346
347 for (auto &C : ModuleAnalysisRegistrationCallbacks)
348 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000349}
350
Chandler Carruth1ff77242015-03-07 09:02:36 +0000351void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000352#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000353 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000354#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000355
356 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
357 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000358}
359
Chandler Carruth1ff77242015-03-07 09:02:36 +0000360void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000361#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000362 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000363#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000364
365 for (auto &C : FunctionAnalysisRegistrationCallbacks)
366 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000367}
368
Justin Bognereecc3c82016-02-25 07:23:08 +0000369void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000370#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000371 LAM.registerPass([&] { return CREATE_PASS; });
372#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000373
374 for (auto &C : LoopAnalysisRegistrationCallbacks)
375 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000376}
377
Chandler Carruthe3f50642016-12-22 06:59:15 +0000378FunctionPassManager
379PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000380 ThinLTOPhase Phase,
381 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000382 assert(Level != O0 && "Must request optimizations!");
383 FunctionPassManager FPM(DebugLogging);
384
385 // Form SSA out of local memory accesses after breaking apart aggregates into
386 // scalars.
387 FPM.addPass(SROA());
388
389 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000390 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000391
Davide Italianoc3688312017-06-01 23:08:14 +0000392 // Hoisting of scalars and load expressions.
393 if (EnableGVNHoist)
394 FPM.addPass(GVNHoistPass());
395
Davide Italianobe1b6a92017-06-03 23:18:29 +0000396 // Global value numbering based sinking.
397 if (EnableGVNSink) {
398 FPM.addPass(GVNSinkPass());
399 FPM.addPass(SimplifyCFGPass());
400 }
401
Chandler Carruthe3f50642016-12-22 06:59:15 +0000402 // Speculative execution if the target has divergent branches; otherwise nop.
403 FPM.addPass(SpeculativeExecutionPass());
404
405 // Optimize based on known information about branches, and cleanup afterward.
406 FPM.addPass(JumpThreadingPass());
407 FPM.addPass(CorrelatedValuePropagationPass());
408 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000409 if (Level == O3)
410 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000411 FPM.addPass(InstCombinePass());
412
413 if (!isOptimizingForSize(Level))
414 FPM.addPass(LibCallsShrinkWrapPass());
415
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000416 invokePeepholeEPCallbacks(FPM, Level);
417
Rong Xue1f42452017-10-23 22:21:29 +0000418 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
419 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000420 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000421 !isOptimizingForSize(Level))
422 FPM.addPass(PGOMemOPSizeOpt());
423
Chandler Carruthe3f50642016-12-22 06:59:15 +0000424 FPM.addPass(TailCallElimPass());
425 FPM.addPass(SimplifyCFGPass());
426
427 // Form canonically associated expression trees, and simplify the trees using
428 // basic mathematical properties. For example, this will form (nearly)
429 // minimal multiplication trees.
430 FPM.addPass(ReassociatePass());
431
432 // Add the primary loop simplification pipeline.
433 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000434 // some function passes in between them. These can and should be removed
435 // and/or replaced by scheduling the loop pass equivalents in the correct
436 // positions. But those equivalent passes aren't powerful enough yet.
437 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
438 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
439 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
440 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000441 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
442
Chandler Carruth71fd2702018-05-30 02:46:45 +0000443 // Simplify the loop body. We do this initially to clean up after other loop
444 // passes run, either when iterating on a loop or on inner loops with
445 // implications on the outer loop.
446 LPM1.addPass(LoopInstSimplifyPass());
447 LPM1.addPass(LoopSimplifyCFGPass());
448
Chandler Carruthe3f50642016-12-22 06:59:15 +0000449 // Rotate Loop - disable header duplication at -Oz
450 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000451 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000452 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000453 LPM2.addPass(IndVarSimplifyPass());
454 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000455
456 for (auto &C : LateLoopOptimizationsEPCallbacks)
457 C(LPM2, Level);
458
Chandler Carruth79b733b2017-01-26 23:21:17 +0000459 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000460 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000461 // because it changes IR to makes profile annotation in back compile
462 // inaccurate.
Rong Xudb29a3a2019-03-04 20:21:27 +0000463 if (Phase != ThinLTOPhase::PreLink || !PGOOpt ||
464 PGOOpt->Action != PGOOptions::SampleUse)
Teresa Johnsonecd90132017-08-02 20:35:29 +0000465 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000466
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000467 for (auto &C : LoopOptimizerEndEPCallbacks)
468 C(LPM2, Level);
469
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000470 // We provide the opt remark emitter pass for LICM to use. We only need to do
471 // this once as it is immutable.
472 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000473 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000474 FPM.addPass(SimplifyCFGPass());
475 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000476 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000477
478 // Eliminate redundancies.
479 if (Level != O1) {
480 // These passes add substantial compile time so skip them at O1.
481 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000482 if (RunNewGVN)
483 FPM.addPass(NewGVNPass());
484 else
485 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000486 }
487
488 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
489 FPM.addPass(MemCpyOptPass());
490
491 // Sparse conditional constant propagation.
492 // FIXME: It isn't clear why we do this *after* loop passes rather than
493 // before...
494 FPM.addPass(SCCPPass());
495
496 // Delete dead bit computations (instcombine runs after to fold away the dead
497 // computations, and then ADCE will run later to exploit any new DCE
498 // opportunities that creates).
499 FPM.addPass(BDCEPass());
500
501 // Run instcombine after redundancy and dead bit elimination to exploit
502 // opportunities opened up by them.
503 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000504 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000505
506 // Re-consider control flow based optimizations after redundancy elimination,
507 // redo DCE, etc.
508 FPM.addPass(JumpThreadingPass());
509 FPM.addPass(CorrelatedValuePropagationPass());
510 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000511 FPM.addPass(createFunctionToLoopPassAdaptor(
512 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
513 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000514
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000515 for (auto &C : ScalarOptimizerLateEPCallbacks)
516 C(FPM, Level);
517
Chandler Carruthe3f50642016-12-22 06:59:15 +0000518 // Finally, do an expensive DCE pass to catch all the dead code exposed by
519 // the simplifications and basic cleanup after all the simplifications.
520 FPM.addPass(ADCEPass());
521 FPM.addPass(SimplifyCFGPass());
522 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000523 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000524
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000525 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000526 (PGOOpt->Action == PGOOptions::IRUse ||
527 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000528 FPM.addPass(ControlHeightReductionPass());
529
Chandler Carruthe3f50642016-12-22 06:59:15 +0000530 return FPM;
531}
532
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000533void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
534 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000535 bool RunProfileGen, bool IsCS,
536 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000537 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000538 // Generally running simplification passes and the inliner with an high
539 // threshold results in smaller executables, but there may be cases where
540 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000541 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
542 // IsCS is true).
543 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000544 InlineParams IP;
545
546 // In the old pass manager, this is a cl::opt. Should still this be one?
547 IP.DefaultThreshold = 75;
548
549 // FIXME: The hint threshold has the same value used by the regular inliner.
550 // This should probably be lowered after performance testing.
551 // FIXME: this comment is cargo culted from the old pass manager, revisit).
552 IP.HintThreshold = 325;
553
554 CGSCCPassManager CGPipeline(DebugLogging);
555
556 CGPipeline.addPass(InlinerPass(IP));
557
558 FunctionPassManager FPM;
559 FPM.addPass(SROA());
560 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
561 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
562 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000563 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000564
Davide Italiano513dfaa2017-02-13 15:26:22 +0000565 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
566
567 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
568 }
569
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000570 // Delete anything that is now dead to make sure that we don't instrument
571 // dead code. Instrumentation can end up keeping dead code around and
572 // dramatically increase code size.
573 MPM.addPass(GlobalDCEPass());
574
Davide Italiano513dfaa2017-02-13 15:26:22 +0000575 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000576 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000577
Xinliang David Lib67530e2017-06-25 00:26:43 +0000578 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000579 FPM.addPass(
580 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000581 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
582
Davide Italiano513dfaa2017-02-13 15:26:22 +0000583 // Add the profile lowering pass.
584 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000585 if (!ProfileFile.empty())
586 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000587 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000588 Options.UseBFIInPromotion = IsCS;
589 MPM.addPass(InstrProfiling(Options, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000590 } else if (!ProfileFile.empty()) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000591 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000592 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
593 // RequireAnalysisPass for PSI before subsequent non-module passes.
594 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
595 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000596}
597
Easwaran Raman8249fac2017-06-28 13:33:49 +0000598static InlineParams
599getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
600 auto O3 = PassBuilder::O3;
601 unsigned OptLevel = Level > O3 ? 2 : Level;
602 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
603 return getInlineParams(OptLevel, SizeLevel);
604}
605
Chandler Carruthe3f50642016-12-22 06:59:15 +0000606ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000607PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000608 ThinLTOPhase Phase,
609 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000610 ModulePassManager MPM(DebugLogging);
611
Rong Xudb29a3a2019-03-04 20:21:27 +0000612 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000613
614 // In ThinLTO mode, when flattened profile is used, all the available
615 // profile information will be annotated in PreLink phase so there is
616 // no need to load the profile again in PostLink.
617 bool LoadSampleProfile =
618 HasSampleProfile &&
619 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
620
621 // During the ThinLTO backend phase we perform early indirect call promotion
622 // here, before globalopt. Otherwise imported available_externally functions
623 // look unreferenced and are removed. If we are going to load the sample
624 // profile then defer until later.
625 // TODO: See if we can move later and consolidate with the location where
626 // we perform ICP when we are loading a sample profile.
627 // TODO: We pass HasSampleProfile (whether there was a sample profile file
628 // passed to the compile) to the SamplePGO flag of ICP. This is used to
629 // determine whether the new direct calls are annotated with prof metadata.
630 // Ideally this should be determined from whether the IR is annotated with
631 // sample profile, and not whether the a sample profile was provided on the
632 // command line. E.g. for flattened profiles where we will not be reloading
633 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
634 // provide the sample profile file.
635 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
636 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
637
Chandler Carruthe3f50642016-12-22 06:59:15 +0000638 // Do basic inference of function attributes from known properties of system
639 // libraries and other oracles.
640 MPM.addPass(InferFunctionAttrsPass());
641
642 // Create an early function pass manager to cleanup the output of the
643 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000644 FunctionPassManager EarlyFPM(DebugLogging);
645 EarlyFPM.addPass(SimplifyCFGPass());
646 EarlyFPM.addPass(SROA());
647 EarlyFPM.addPass(EarlyCSEPass());
648 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000649 if (Level == O3)
650 EarlyFPM.addPass(CallSiteSplittingPass());
651
Dehao Chen08f88312017-08-07 20:23:20 +0000652 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
653 // to convert bitcast to direct calls so that they can be inlined during the
654 // profile annotation prepration step.
655 // More details about SamplePGO design can be found in:
656 // https://research.google.com/pubs/pub45290.html
657 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000658 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000659 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000660 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000661
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000662 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000663 // Annotate sample profile right after early FPM to ensure freshness of
664 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000665 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000666 PGOOpt->ProfileRemappingFile,
667 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000668 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
669 // RequireAnalysisPass for PSI before subsequent non-module passes.
670 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000671 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
672 // for the profile annotation to be accurate in the ThinLTO backend.
673 if (Phase != ThinLTOPhase::PreLink)
674 // We perform early indirect call promotion here, before globalopt.
675 // This is important for the ThinLTO backend phase because otherwise
676 // imported available_externally functions look unreferenced and are
677 // removed.
678 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000679 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000680 }
681
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000682 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000683 // and prior to optimizing globals.
684 // FIXME: This position in the pipeline hasn't been carefully considered in
685 // years, it should be re-analyzed.
686 MPM.addPass(IPSCCPPass());
687
Matthew Simpsoncb585582017-10-25 13:40:08 +0000688 // Attach metadata to indirect call sites indicating the set of functions
689 // they may target at run-time. This should follow IPSCCP.
690 MPM.addPass(CalledValuePropagationPass());
691
Chandler Carruthe3f50642016-12-22 06:59:15 +0000692 // Optimize globals to try and fold them into constants.
693 MPM.addPass(GlobalOptPass());
694
695 // Promote any localized globals to SSA registers.
696 // FIXME: Should this instead by a run of SROA?
697 // FIXME: We should probably run instcombine and simplify-cfg afterward to
698 // delete control flows that are dead once globals have been folded to
699 // constants.
700 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
701
702 // Remove any dead arguments exposed by cleanups and constand folding
703 // globals.
704 MPM.addPass(DeadArgumentEliminationPass());
705
706 // Create a small function pass pipeline to cleanup after all the global
707 // optimizations.
708 FunctionPassManager GlobalCleanupPM(DebugLogging);
709 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000710 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
711
Chandler Carruthe3f50642016-12-22 06:59:15 +0000712 GlobalCleanupPM.addPass(SimplifyCFGPass());
713 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
714
Dehao Chen89d32262017-08-02 01:28:31 +0000715 // Add all the requested passes for instrumentation PGO, if requested.
716 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000717 (PGOOpt->Action == PGOOptions::IRInstr ||
718 PGOOpt->Action == PGOOptions::IRUse)) {
719 addPGOInstrPasses(MPM, DebugLogging, Level,
720 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
721 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000722 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000723 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000724 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000725 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
726 PGOOpt->CSAction == PGOOptions::CSIRInstr)
727 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000728
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000729 // Synthesize function entry counts for non-PGO compilation.
730 if (EnableSyntheticCounts && !PGOOpt)
731 MPM.addPass(SyntheticCountsPropagation());
732
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000733 // Require the GlobalsAA analysis for the module so we can query it within
734 // the CGSCC pipeline.
735 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000736
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000737 // Require the ProfileSummaryAnalysis for the module so we can query it within
738 // the inliner pass.
739 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
740
Chandler Carruthe3f50642016-12-22 06:59:15 +0000741 // Now begin the main postorder CGSCC pipeline.
742 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
743 // manager and trying to emulate its precise behavior. Much of this doesn't
744 // make a lot of sense and we should revisit the core CGSCC structure.
745 CGSCCPassManager MainCGPipeline(DebugLogging);
746
747 // Note: historically, the PruneEH pass was run first to deduce nounwind and
748 // generally clean up exception handling overhead. It isn't clear this is
749 // valuable as the inliner doesn't currently care whether it is inlining an
750 // invoke or a call.
751
752 // Run the inliner first. The theory is that we are walking bottom-up and so
753 // the callees have already been fully optimized, and we want to inline them
754 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000755 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000756 // because it makes profile annotation in the backend inaccurate.
757 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000758 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
759 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000760 IP.HotCallSiteThreshold = 0;
761 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000762
763 // Now deduce any function attributes based in the current code.
764 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
765
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000766 // When at O3 add argument promotion to the pass pipeline.
767 // FIXME: It isn't at all clear why this should be limited to O3.
768 if (Level == O3)
769 MainCGPipeline.addPass(ArgumentPromotionPass());
770
Chandler Carruthe3f50642016-12-22 06:59:15 +0000771 // Lastly, add the core function simplification pipeline nested inside the
772 // CGSCC walk.
773 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000774 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000775
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000776 for (auto &C : CGSCCOptimizerLateEPCallbacks)
777 C(MainCGPipeline, Level);
778
Chandler Carruth719ffe12017-02-12 05:38:04 +0000779 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
780 // to detect when we devirtualize indirect calls and iterate the SCC passes
781 // in that case to try and catch knock-on inlining or function attrs
782 // opportunities. Then we add it to the module pipeline by walking the SCCs
783 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000784 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000785 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000786 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000787
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000788 return MPM;
789}
790
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000791ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
792 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000793 ModulePassManager MPM(DebugLogging);
794
795 // Optimize globals now that the module is fully simplified.
796 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000797 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000798
Xinliang David Li126157c2017-05-22 16:41:57 +0000799 // Run partial inlining pass to partially inline functions that have
800 // large bodies.
801 if (RunPartialInlining)
802 MPM.addPass(PartialInlinerPass());
803
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000804 // Remove avail extern fns and globals definitions since we aren't compiling
805 // an object file for later LTO. For LTO we want to preserve these so they
806 // are eligible for inlining at link-time. Note if they are unreferenced they
807 // will be removed by GlobalDCE later, so this only impacts referenced
808 // available externally globals. Eventually they will be suppressed during
809 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
810 // may make globals referenced by available external functions dead and saves
811 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000812 MPM.addPass(EliminateAvailableExternallyPass());
813
Manman Ren18295122019-02-28 20:13:38 +0000814 if (EnableOrderFileInstrumentation)
815 MPM.addPass(InstrOrderFilePass());
816
Chandler Carruthe3f50642016-12-22 06:59:15 +0000817 // Do RPO function attribute inference across the module to forward-propagate
818 // attributes where applicable.
819 // FIXME: Is this really an optimization rather than a canonicalization?
820 MPM.addPass(ReversePostOrderFunctionAttrsPass());
821
Rong Xudb29a3a2019-03-04 20:21:27 +0000822 // Do a post inline PGO instrumentation and use pass. This is a context
823 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
824 // cross-module inline has not been done yet. The context sensitive
825 // instrumentation is after all the inlines are done.
826 if (!LTOPreLink && PGOOpt) {
827 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
828 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
829 /* IsCS */ true, PGOOpt->CSProfileGenFile,
830 PGOOpt->ProfileRemappingFile);
831 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
832 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
833 /* IsCS */ true, PGOOpt->ProfileFile,
834 PGOOpt->ProfileRemappingFile);
835 }
836
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000837 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000838 // useful as the above will have inlined, DCE'ed, and function-attr
839 // propagated everything. We should at this point have a reasonably minimal
840 // and richly annotated call graph. By computing aliasing and mod/ref
841 // information for all local globals here, the late loop passes and notably
842 // the vectorizer will be able to use them to help recognize vectorizable
843 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000844 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000845
846 FunctionPassManager OptimizePM(DebugLogging);
847 OptimizePM.addPass(Float2IntPass());
848 // FIXME: We need to run some loop optimizations to re-rotate loops after
849 // simplify-cfg and others undo their rotation.
850
851 // Optimize the loop execution. These passes operate on entire loop nests
852 // rather than on each loop in an inside-out manner, and so they are actually
853 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000854
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000855 for (auto &C : VectorizerStartEPCallbacks)
856 C(OptimizePM, Level);
857
Chandler Carrutha95ff382017-01-27 00:50:21 +0000858 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000859 OptimizePM.addPass(
860 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000861
862 // Distribute loops to allow partial vectorization. I.e. isolate dependences
863 // into separate loop that would otherwise inhibit vectorization. This is
864 // currently only performed for loops marked with the metadata
865 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000866 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000867
868 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000869 OptimizePM.addPass(LoopVectorizePass(
870 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000871
Chandler Carruthbaabda92017-01-27 01:32:26 +0000872 // Eliminate loads by forwarding stores from the previous iteration to loads
873 // of the current iteration.
874 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000875
876 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000877 OptimizePM.addPass(InstCombinePass());
878
Chandler Carrutha95ff382017-01-27 00:50:21 +0000879 // Now that we've formed fast to execute loop structures, we do further
880 // optimizations. These are run afterward as they might block doing complex
881 // analyses and transforms such as what are needed for loop vectorization.
882
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000883 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
884 // GVN, loop transforms, and others have already run, so it's now better to
885 // convert to more optimized IR using more aggressive simplify CFG options.
886 // The extra sinking transform can create larger basic blocks, so do this
887 // before SLP vectorization.
888 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
889 forwardSwitchCondToPhi(true).
890 convertSwitchToLookupTable(true).
891 needCanonicalLoops(false).
892 sinkCommonInsts(true)));
893
Chandler Carruthe3f50642016-12-22 06:59:15 +0000894 // Optimize parallel scalar instruction chains into SIMD instructions.
895 OptimizePM.addPass(SLPVectorizerPass());
896
Chandler Carruthe3f50642016-12-22 06:59:15 +0000897 OptimizePM.addPass(InstCombinePass());
898
899 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000900 // execution resources of an out-of-order processor. We also then need to
901 // clean up redundancies and loop invariant code.
902 // FIXME: It would be really good to use a loop-integrated instruction
903 // combiner for cleanup here so that the unrolling and LICM can be pipelined
904 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000905 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
906 if (EnableUnrollAndJam) {
907 OptimizePM.addPass(
908 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
909 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000910 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000911 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000912 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000913 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000914 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
915 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
916 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000917
918 // Now that we've vectorized and unrolled loops, we may have more refined
919 // alignment information, try to re-derive it here.
920 OptimizePM.addPass(AlignmentFromAssumptionsPass());
921
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000922 // Split out cold code. Splitting is done late to avoid hiding context from
923 // other optimizations and inadvertently regressing performance. The tradeoff
924 // is that this has a higher code size cost than splitting early.
925 if (EnableHotColdSplit && !LTOPreLink)
926 MPM.addPass(HotColdSplittingPass());
927
Chandler Carrutha95ff382017-01-27 00:50:21 +0000928 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
929 // canonicalization pass that enables other optimizations. As a result,
930 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
931 // result too early.
932 OptimizePM.addPass(LoopSinkPass());
933
934 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000935 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000936
Sanjay Patel6fd43912017-09-09 13:38:18 +0000937 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
938 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
939 // flattening of blocks.
940 OptimizePM.addPass(DivRemPairsPass());
941
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000942 // LoopSink (and other loop passes since the last simplifyCFG) might have
943 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
944 OptimizePM.addPass(SimplifyCFGPass());
945
Chandler Carruthc34f7892017-11-28 11:32:31 +0000946 // Optimize PHIs by speculating around them when profitable. Note that this
947 // pass needs to be run after any PRE or similar pass as it is essentially
948 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
949 OptimizePM.addPass(SpeculateAroundPHIsPass());
950
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000951 for (auto &C : OptimizerLastEPCallbacks)
952 C(OptimizePM, Level);
953
Chandler Carrutha95ff382017-01-27 00:50:21 +0000954 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000955 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
956
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000957 MPM.addPass(CGProfilePass());
958
Chandler Carruthe3f50642016-12-22 06:59:15 +0000959 // Now we need to do some global optimization transforms.
960 // FIXME: It would seem like these should come first in the optimization
961 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
962 // ordering here.
963 MPM.addPass(GlobalDCEPass());
964 MPM.addPass(ConstantMergePass());
965
966 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000967}
968
Chandler Carruthe3f50642016-12-22 06:59:15 +0000969ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000970PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000971 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000972 assert(Level != O0 && "Must request optimizations for the default pipeline!");
973
974 ModulePassManager MPM(DebugLogging);
975
976 // Force any function attributes we want the rest of the pipeline to observe.
977 MPM.addPass(ForceFunctionAttrsPass());
978
David Blaikie0c64f5a2018-01-23 01:25:20 +0000979 // Apply module pipeline start EP callback.
980 for (auto &C : PipelineStartEPCallbacks)
981 C(MPM);
982
Dehao Chen08f88312017-08-07 20:23:20 +0000983 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000984 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
985
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000986 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000987 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
988 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000989
990 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000991 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000992
993 return MPM;
994}
995
996ModulePassManager
997PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
998 bool DebugLogging) {
999 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1000
1001 ModulePassManager MPM(DebugLogging);
1002
1003 // Force any function attributes we want the rest of the pipeline to observe.
1004 MPM.addPass(ForceFunctionAttrsPass());
1005
Dehao Chen08f88312017-08-07 20:23:20 +00001006 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001007 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1008
David Blaikie0c64f5a2018-01-23 01:25:20 +00001009 // Apply module pipeline start EP callback.
1010 for (auto &C : PipelineStartEPCallbacks)
1011 C(MPM);
1012
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001013 // If we are planning to perform ThinLTO later, we don't bloat the code with
1014 // unrolling/vectorization/... now. Just simplify the module as much as we
1015 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001016 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1017 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001018
1019 // Run partial inlining pass to partially inline functions that have
1020 // large bodies.
1021 // FIXME: It isn't clear whether this is really the right place to run this
1022 // in ThinLTO. Because there is another canonicalization and simplification
1023 // phase that will run after the thin link, running this here ends up with
1024 // less information than will be available later and it may grow functions in
1025 // ways that aren't beneficial.
1026 if (RunPartialInlining)
1027 MPM.addPass(PartialInlinerPass());
1028
1029 // Reduce the size of the IR as much as possible.
1030 MPM.addPass(GlobalOptPass());
1031
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001032 return MPM;
1033}
1034
Teresa Johnson28023db2018-07-19 14:51:32 +00001035ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1036 OptimizationLevel Level, bool DebugLogging,
1037 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001038 ModulePassManager MPM(DebugLogging);
1039
Teresa Johnson28023db2018-07-19 14:51:32 +00001040 if (ImportSummary) {
1041 // These passes import type identifier resolutions for whole-program
1042 // devirtualization and CFI. They must run early because other passes may
1043 // disturb the specific instruction patterns that these passes look for,
1044 // creating dependencies on resolutions that may not appear in the summary.
1045 //
1046 // For example, GVN may transform the pattern assume(type.test) appearing in
1047 // two basic blocks into assume(phi(type.test, type.test)), which would
1048 // transform a dependency on a WPD resolution into a dependency on a type
1049 // identifier resolution for CFI.
1050 //
1051 // Also, WPD has access to more precise information than ICP and can
1052 // devirtualize more effectively, so it should operate on the IR first.
1053 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1054 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1055 }
1056
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001057 // Force any function attributes we want the rest of the pipeline to observe.
1058 MPM.addPass(ForceFunctionAttrsPass());
1059
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001060 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001061 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1062 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001063
1064 // Now add the optimization pipeline.
1065 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1066
1067 return MPM;
1068}
1069
1070ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001071PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1072 bool DebugLogging) {
1073 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001074 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001075 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001076 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001077}
1078
Teresa Johnson28023db2018-07-19 14:51:32 +00001079ModulePassManager
1080PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1081 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001082 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1083 ModulePassManager MPM(DebugLogging);
1084
Rong Xudb29a3a2019-03-04 20:21:27 +00001085 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001086 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001087 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001088 PGOOpt->ProfileRemappingFile,
1089 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001090 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1091 // RequireAnalysisPass for PSI before subsequent non-module passes.
1092 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001093 }
1094
Davide Italiano089a9122017-01-24 00:57:39 +00001095 // Remove unused virtual tables to improve the quality of code generated by
1096 // whole-program devirtualization and bitset lowering.
1097 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001098
Davide Italiano089a9122017-01-24 00:57:39 +00001099 // Force any function attributes we want the rest of the pipeline to observe.
1100 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001101
Davide Italiano089a9122017-01-24 00:57:39 +00001102 // Do basic inference of function attributes from known properties of system
1103 // libraries and other oracles.
1104 MPM.addPass(InferFunctionAttrsPass());
1105
1106 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001107 FunctionPassManager EarlyFPM(DebugLogging);
1108 EarlyFPM.addPass(CallSiteSplittingPass());
1109 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1110
Davide Italiano089a9122017-01-24 00:57:39 +00001111 // Indirect call promotion. This should promote all the targets that are
1112 // left by the earlier promotion pass that promotes intra-module targets.
1113 // This two-step promotion is to save the compile time. For LTO, it should
1114 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001115 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001116 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001117 // Propagate constants at call sites into the functions they call. This
1118 // opens opportunities for globalopt (and inlining) by substituting function
1119 // pointers passed as arguments to direct uses of functions.
1120 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001121
1122 // Attach metadata to indirect call sites indicating the set of functions
1123 // they may target at run-time. This should follow IPSCCP.
1124 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001125 }
1126
1127 // Now deduce any function attributes based in the current code.
1128 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1129 PostOrderFunctionAttrsPass()));
1130
1131 // Do RPO function attribute inference across the module to forward-propagate
1132 // attributes where applicable.
1133 // FIXME: Is this really an optimization rather than a canonicalization?
1134 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1135
Eric Christopher721eaef2019-02-26 20:33:22 +00001136 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001137 MPM.addPass(GlobalSplitPass());
1138
1139 // Run whole program optimization of virtual call when the list of callees
1140 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001141 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001142
1143 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001144 if (Level == 1) {
1145 // The LowerTypeTestsPass needs to run to lower type metadata and the
1146 // type.test intrinsics. The pass does nothing if CFI is disabled.
1147 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001148 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001149 }
Davide Italiano089a9122017-01-24 00:57:39 +00001150
1151 // Optimize globals to try and fold them into constants.
1152 MPM.addPass(GlobalOptPass());
1153
1154 // Promote any localized globals to SSA registers.
1155 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1156
1157 // Linking modules together can lead to duplicate global constant, only
1158 // keep one copy of each constant.
1159 MPM.addPass(ConstantMergePass());
1160
1161 // Remove unused arguments from functions.
1162 MPM.addPass(DeadArgumentEliminationPass());
1163
1164 // Reduce the code after globalopt and ipsccp. Both can open up significant
1165 // simplification opportunities, and both can propagate functions through
1166 // function pointers. When this happens, we often have to resolve varargs
1167 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001168 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001169 if (Level == O3)
1170 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001171 PeepholeFPM.addPass(InstCombinePass());
1172 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1173
1174 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001175
1176 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1177 // generally clean up exception handling overhead. It isn't clear this is
1178 // valuable as the inliner doesn't currently care whether it is inlining an
1179 // invoke or a call.
1180 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001181 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1182 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001183
1184 // Optimize globals again after we ran the inliner.
1185 MPM.addPass(GlobalOptPass());
1186
1187 // Garbage collect dead functions.
1188 // FIXME: Add ArgumentPromotion pass after once it's ported.
1189 MPM.addPass(GlobalDCEPass());
1190
1191 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001192 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001193 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001194 invokePeepholeEPCallbacks(FPM, Level);
1195
Davide Italiano089a9122017-01-24 00:57:39 +00001196 FPM.addPass(JumpThreadingPass());
1197
Rong Xudb29a3a2019-03-04 20:21:27 +00001198 // Do a post inline PGO instrumentation and use pass. This is a context
1199 // sensitive PGO pass.
1200 if (PGOOpt) {
1201 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1202 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1203 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1204 PGOOpt->ProfileRemappingFile);
1205 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1206 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1207 /* IsCS */ true, PGOOpt->ProfileFile,
1208 PGOOpt->ProfileRemappingFile);
1209 }
1210
Davide Italiano089a9122017-01-24 00:57:39 +00001211 // Break up allocas
1212 FPM.addPass(SROA());
1213
Robert Lougherf2158a82019-03-20 19:08:18 +00001214 // LTO provides additional opportunities for tailcall elimination due to
1215 // link-time inlining, and visibility of nocapture attribute.
1216 FPM.addPass(TailCallElimPass());
1217
Davide Italiano089a9122017-01-24 00:57:39 +00001218 // Run a few AA driver optimizations here and now to cleanup the code.
1219 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1220
1221 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1222 PostOrderFunctionAttrsPass()));
1223 // FIXME: here we run IP alias analysis in the legacy PM.
1224
1225 FunctionPassManager MainFPM;
1226
1227 // FIXME: once we fix LoopPass Manager, add LICM here.
1228 // FIXME: once we provide support for enabling MLSM, add it here.
1229 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001230 if (RunNewGVN)
1231 MainFPM.addPass(NewGVNPass());
1232 else
1233 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001234
1235 // Remove dead memcpy()'s.
1236 MainFPM.addPass(MemCpyOptPass());
1237
1238 // Nuke dead stores.
1239 MainFPM.addPass(DSEPass());
1240
1241 // FIXME: at this point, we run a bunch of loop passes:
1242 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1243 // loopVectorize. Enable them once the remaining issue with LPM
1244 // are sorted out.
1245
1246 MainFPM.addPass(InstCombinePass());
1247 MainFPM.addPass(SimplifyCFGPass());
1248 MainFPM.addPass(SCCPPass());
1249 MainFPM.addPass(InstCombinePass());
1250 MainFPM.addPass(BDCEPass());
1251
1252 // FIXME: We may want to run SLPVectorizer here.
1253 // After vectorization, assume intrinsics may tell us more
1254 // about pointer alignments.
1255#if 0
1256 MainFPM.add(AlignmentFromAssumptionsPass());
1257#endif
1258
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001259 // FIXME: Conditionally run LoadCombine here, after it's ported
1260 // (in case we still have this pass, given its questionable usefulness).
1261
Davide Italiano089a9122017-01-24 00:57:39 +00001262 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001263 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001264 MainFPM.addPass(JumpThreadingPass());
1265 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1266
1267 // Create a function that performs CFI checks for cross-DSO calls with
1268 // targets in the current module.
1269 MPM.addPass(CrossDSOCFIPass());
1270
1271 // Lower type metadata and the type.test intrinsic. This pass supports
1272 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1273 // to be run at link time if CFI is enabled. This pass does nothing if
1274 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001275 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001276
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001277 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1278 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1279 if (EnableHotColdSplit)
1280 MPM.addPass(HotColdSplittingPass());
1281
Davide Italiano089a9122017-01-24 00:57:39 +00001282 // Add late LTO optimization passes.
1283 // Delete basic blocks, which optimization passes may have killed.
1284 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1285
1286 // Drop bodies of available eternally objects to improve GlobalDCE.
1287 MPM.addPass(EliminateAvailableExternallyPass());
1288
1289 // Now that we have optimized the program, discard unreachable functions.
1290 MPM.addPass(GlobalDCEPass());
1291
1292 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001293 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001294}
1295
Chandler Carruth060ad612016-12-23 20:38:19 +00001296AAManager PassBuilder::buildDefaultAAPipeline() {
1297 AAManager AA;
1298
1299 // The order in which these are registered determines their priority when
1300 // being queried.
1301
1302 // First we register the basic alias analysis that provides the majority of
1303 // per-function local AA logic. This is a stateless, on-demand local set of
1304 // AA techniques.
1305 AA.registerFunctionAnalysis<BasicAA>();
1306
1307 // Next we query fast, specialized alias analyses that wrap IR-embedded
1308 // information about aliasing.
1309 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1310 AA.registerFunctionAnalysis<TypeBasedAA>();
1311
1312 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001313 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1314 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001315 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001316 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001317
1318 return AA;
1319}
1320
Chandler Carruth241bf242016-08-03 07:44:48 +00001321static Optional<int> parseRepeatPassName(StringRef Name) {
1322 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1323 return None;
1324 int Count;
1325 if (Name.getAsInteger(0, Count) || Count <= 0)
1326 return None;
1327 return Count;
1328}
1329
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001330static Optional<int> parseDevirtPassName(StringRef Name) {
1331 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1332 return None;
1333 int Count;
1334 if (Name.getAsInteger(0, Count) || Count <= 0)
1335 return None;
1336 return Count;
1337}
1338
Fedor Sergeevb7871402019-01-10 10:01:53 +00001339static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1340 if (!Name.consume_front(PassName))
1341 return false;
1342 // normal pass name w/o parameters == default parameters
1343 if (Name.empty())
1344 return true;
1345 return Name.startswith("<") && Name.endswith(">");
1346}
1347
1348namespace {
1349
1350/// This performs customized parsing of pass name with parameters.
1351///
1352/// We do not need parametrization of passes in textual pipeline very often,
1353/// yet on a rare occasion ability to specify parameters right there can be
1354/// useful.
1355///
1356/// \p Name - parameterized specification of a pass from a textual pipeline
1357/// is a string in a form of :
1358/// PassName '<' parameter-list '>'
1359///
1360/// Parameter list is being parsed by the parser callable argument, \p Parser,
1361/// It takes a string-ref of parameters and returns either StringError or a
1362/// parameter list in a form of a custom parameters type, all wrapped into
1363/// Expected<> template class.
1364///
1365template <typename ParametersParseCallableT>
1366auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1367 StringRef PassName) -> decltype(Parser(StringRef{})) {
1368 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1369
1370 StringRef Params = Name;
1371 if (!Params.consume_front(PassName)) {
1372 assert(false &&
1373 "unable to strip pass name from parametrized pass specification");
1374 }
1375 if (Params.empty())
1376 return ParametersT{};
1377 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1378 assert(false && "invalid format for parametrized pass name");
1379 }
1380
1381 Expected<ParametersT> Result = Parser(Params);
1382 assert((Result || Result.template errorIsA<StringError>()) &&
1383 "Pass parameter parser can only return StringErrors.");
1384 return std::move(Result);
1385}
1386
1387/// Parser of parameters for LoopUnroll pass.
1388Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1389 LoopUnrollOptions UnrollOpts;
1390 while (!Params.empty()) {
1391 StringRef ParamName;
1392 std::tie(ParamName, Params) = Params.split(';');
1393 int OptLevel = StringSwitch<int>(ParamName)
1394 .Case("O0", 0)
1395 .Case("O1", 1)
1396 .Case("O2", 2)
1397 .Case("O3", 3)
1398 .Default(-1);
1399 if (OptLevel >= 0) {
1400 UnrollOpts.setOptLevel(OptLevel);
1401 continue;
1402 }
1403
1404 bool Enable = !ParamName.consume_front("no-");
1405 if (ParamName == "partial") {
1406 UnrollOpts.setPartial(Enable);
1407 } else if (ParamName == "peeling") {
1408 UnrollOpts.setPeeling(Enable);
1409 } else if (ParamName == "runtime") {
1410 UnrollOpts.setRuntime(Enable);
1411 } else if (ParamName == "upperbound") {
1412 UnrollOpts.setUpperBound(Enable);
1413 } else {
1414 return make_error<StringError>(
1415 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1416 inconvertibleErrorCode());
1417 }
1418 }
1419 return UnrollOpts;
1420}
1421
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001422Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1423 MemorySanitizerOptions Result;
1424 while (!Params.empty()) {
1425 StringRef ParamName;
1426 std::tie(ParamName, Params) = Params.split(';');
1427
1428 if (ParamName == "recover") {
1429 Result.Recover = true;
1430 } else if (ParamName == "kernel") {
1431 Result.Kernel = true;
1432 } else if (ParamName.consume_front("track-origins=")) {
1433 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1434 return make_error<StringError>(
1435 formatv("invalid argument to MemorySanitizer pass track-origins "
1436 "parameter: '{0}' ",
1437 ParamName)
1438 .str(),
1439 inconvertibleErrorCode());
1440 } else {
1441 return make_error<StringError>(
1442 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1443 .str(),
1444 inconvertibleErrorCode());
1445 }
1446 }
1447 return Result;
1448}
1449
Serguei Katkovf5432832019-04-15 08:57:53 +00001450/// Parser of parameters for SimplifyCFG pass.
1451Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1452 SimplifyCFGOptions Result;
1453 while (!Params.empty()) {
1454 StringRef ParamName;
1455 std::tie(ParamName, Params) = Params.split(';');
1456
1457 bool Enable = !ParamName.consume_front("no-");
1458 if (ParamName == "forward-switch-cond") {
1459 Result.forwardSwitchCondToPhi(Enable);
1460 } else if (ParamName == "switch-to-lookup") {
1461 Result.convertSwitchToLookupTable(Enable);
1462 } else if (ParamName == "keep-loops") {
1463 Result.needCanonicalLoops(Enable);
1464 } else if (ParamName == "sink-common-insts") {
1465 Result.sinkCommonInsts(Enable);
1466 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1467 APInt BonusInstThreshold;
1468 if (ParamName.getAsInteger(0, BonusInstThreshold))
1469 return make_error<StringError>(
1470 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1471 "parameter: '{0}' ",
1472 ParamName).str(),
1473 inconvertibleErrorCode());
1474 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1475 } else {
1476 return make_error<StringError>(
1477 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1478 inconvertibleErrorCode());
1479 }
1480 }
1481 return Result;
1482}
1483
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001484/// Parser of parameters for LoopVectorize pass.
1485Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1486 LoopVectorizeOptions Opts;
1487 while (!Params.empty()) {
1488 StringRef ParamName;
1489 std::tie(ParamName, Params) = Params.split(';');
1490
1491 bool Enable = !ParamName.consume_front("no-");
1492 if (ParamName == "interleave-forced-only") {
1493 Opts.setInterleaveOnlyWhenForced(Enable);
1494 } else if (ParamName == "vectorize-forced-only") {
1495 Opts.setVectorizeOnlyWhenForced(Enable);
1496 } else {
1497 return make_error<StringError>(
1498 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1499 inconvertibleErrorCode());
1500 }
1501 }
1502 return Opts;
1503}
1504
Fedor Sergeevb7871402019-01-10 10:01:53 +00001505} // namespace
1506
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001507/// Tests whether a pass name starts with a valid prefix for a default pipeline
1508/// alias.
1509static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1510 return Name.startswith("default") || Name.startswith("thinlto") ||
1511 Name.startswith("lto");
1512}
1513
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001514/// Tests whether registered callbacks will accept a given pass name.
1515///
1516/// When parsing a pipeline text, the type of the outermost pipeline may be
1517/// omitted, in which case the type is automatically determined from the first
1518/// pass name in the text. This may be a name that is handled through one of the
1519/// callbacks. We check this through the oridinary parsing callbacks by setting
1520/// up a dummy PassManager in order to not force the client to also handle this
1521/// type of query.
1522template <typename PassManagerT, typename CallbacksT>
1523static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1524 if (!Callbacks.empty()) {
1525 PassManagerT DummyPM;
1526 for (auto &CB : Callbacks)
1527 if (CB(Name, DummyPM, {}))
1528 return true;
1529 }
1530 return false;
1531}
1532
1533template <typename CallbacksT>
1534static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001535 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001536 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001537 return DefaultAliasRegex.match(Name);
1538
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001539 // Explicitly handle pass manager names.
1540 if (Name == "module")
1541 return true;
1542 if (Name == "cgscc")
1543 return true;
1544 if (Name == "function")
1545 return true;
1546
Chandler Carruth241bf242016-08-03 07:44:48 +00001547 // Explicitly handle custom-parsed pass names.
1548 if (parseRepeatPassName(Name))
1549 return true;
1550
Chandler Carruth74a8a222016-06-17 07:15:29 +00001551#define MODULE_PASS(NAME, CREATE_PASS) \
1552 if (Name == NAME) \
1553 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001554#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001555 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001556 return true;
1557#include "PassRegistry.def"
1558
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001559 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001560}
1561
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001562template <typename CallbacksT>
1563static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001564 // Explicitly handle pass manager names.
1565 if (Name == "cgscc")
1566 return true;
1567 if (Name == "function")
1568 return true;
1569
Chandler Carruth241bf242016-08-03 07:44:48 +00001570 // Explicitly handle custom-parsed pass names.
1571 if (parseRepeatPassName(Name))
1572 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001573 if (parseDevirtPassName(Name))
1574 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001575
Chandler Carruth74a8a222016-06-17 07:15:29 +00001576#define CGSCC_PASS(NAME, CREATE_PASS) \
1577 if (Name == NAME) \
1578 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001579#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001580 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001581 return true;
1582#include "PassRegistry.def"
1583
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001584 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001585}
1586
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001587template <typename CallbacksT>
1588static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001589 // Explicitly handle pass manager names.
1590 if (Name == "function")
1591 return true;
1592 if (Name == "loop")
1593 return true;
1594
Chandler Carruth241bf242016-08-03 07:44:48 +00001595 // Explicitly handle custom-parsed pass names.
1596 if (parseRepeatPassName(Name))
1597 return true;
1598
Chandler Carruth74a8a222016-06-17 07:15:29 +00001599#define FUNCTION_PASS(NAME, CREATE_PASS) \
1600 if (Name == NAME) \
1601 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001602#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1603 if (checkParametrizedPassName(Name, NAME)) \
1604 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001605#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001606 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001607 return true;
1608#include "PassRegistry.def"
1609
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001610 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001611}
1612
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001613template <typename CallbacksT>
1614static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001615 // Explicitly handle pass manager names.
1616 if (Name == "loop")
1617 return true;
1618
Chandler Carruth241bf242016-08-03 07:44:48 +00001619 // Explicitly handle custom-parsed pass names.
1620 if (parseRepeatPassName(Name))
1621 return true;
1622
Chandler Carruth74a8a222016-06-17 07:15:29 +00001623#define LOOP_PASS(NAME, CREATE_PASS) \
1624 if (Name == NAME) \
1625 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001626#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1627 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1628 return true;
1629#include "PassRegistry.def"
1630
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001631 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001632}
1633
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001634Optional<std::vector<PassBuilder::PipelineElement>>
1635PassBuilder::parsePipelineText(StringRef Text) {
1636 std::vector<PipelineElement> ResultPipeline;
1637
1638 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1639 &ResultPipeline};
1640 for (;;) {
1641 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1642 size_t Pos = Text.find_first_of(",()");
1643 Pipeline.push_back({Text.substr(0, Pos), {}});
1644
1645 // If we have a single terminating name, we're done.
1646 if (Pos == Text.npos)
1647 break;
1648
1649 char Sep = Text[Pos];
1650 Text = Text.substr(Pos + 1);
1651 if (Sep == ',')
1652 // Just a name ending in a comma, continue.
1653 continue;
1654
1655 if (Sep == '(') {
1656 // Push the inner pipeline onto the stack to continue processing.
1657 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1658 continue;
1659 }
1660
1661 assert(Sep == ')' && "Bogus separator!");
1662 // When handling the close parenthesis, we greedily consume them to avoid
1663 // empty strings in the pipeline.
1664 do {
1665 // If we try to pop the outer pipeline we have unbalanced parentheses.
1666 if (PipelineStack.size() == 1)
1667 return None;
1668
1669 PipelineStack.pop_back();
1670 } while (Text.consume_front(")"));
1671
1672 // Check if we've finished parsing.
1673 if (Text.empty())
1674 break;
1675
1676 // Otherwise, the end of an inner pipeline always has to be followed by
1677 // a comma, and then we can continue.
1678 if (!Text.consume_front(","))
1679 return None;
1680 }
1681
1682 if (PipelineStack.size() > 1)
1683 // Unbalanced paretheses.
1684 return None;
1685
1686 assert(PipelineStack.back() == &ResultPipeline &&
1687 "Wrong pipeline at the bottom of the stack!");
1688 return {std::move(ResultPipeline)};
1689}
1690
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001691Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1692 const PipelineElement &E,
1693 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001694 auto &Name = E.Name;
1695 auto &InnerPipeline = E.InnerPipeline;
1696
1697 // First handle complex passes like the pass managers which carry pipelines.
1698 if (!InnerPipeline.empty()) {
1699 if (Name == "module") {
1700 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001701 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1702 VerifyEachPass, DebugLogging))
1703 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001704 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001705 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001706 }
1707 if (Name == "cgscc") {
1708 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001709 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1710 DebugLogging))
1711 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001712 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001713 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001714 }
1715 if (Name == "function") {
1716 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001717 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1718 VerifyEachPass, DebugLogging))
1719 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001720 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001721 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001722 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001723 if (auto Count = parseRepeatPassName(Name)) {
1724 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001725 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1726 VerifyEachPass, DebugLogging))
1727 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001728 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001729 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001730 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001731
1732 for (auto &C : ModulePipelineParsingCallbacks)
1733 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001734 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001735
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001736 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001737 return make_error<StringError>(
1738 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1739 inconvertibleErrorCode());
1740 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001741 }
1742
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001743 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001744 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001745 SmallVector<StringRef, 3> Matches;
1746 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001747 return make_error<StringError>(
1748 formatv("unknown default pipeline alias '{0}'", Name).str(),
1749 inconvertibleErrorCode());
1750
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001751 assert(Matches.size() == 3 && "Must capture two matched strings!");
1752
Jordan Rosef85a95f2016-07-25 18:34:51 +00001753 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001754 .Case("O0", O0)
1755 .Case("O1", O1)
1756 .Case("O2", O2)
1757 .Case("O3", O3)
1758 .Case("Os", Os)
1759 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001760 if (L == O0)
1761 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001762 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001763
1764 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001765 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001766 } else if (Matches[1] == "thinlto-pre-link") {
1767 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1768 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001769 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001770 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001771 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001772 } else {
1773 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001774 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001775 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001776 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001777 }
1778
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001779 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001780#define MODULE_PASS(NAME, CREATE_PASS) \
1781 if (Name == NAME) { \
1782 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001783 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001784 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001785#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1786 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001787 MPM.addPass( \
1788 RequireAnalysisPass< \
1789 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001790 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001791 } \
1792 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001793 MPM.addPass(InvalidateAnalysisPass< \
1794 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001795 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001796 }
1797#include "PassRegistry.def"
1798
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001799 for (auto &C : ModulePipelineParsingCallbacks)
1800 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001801 return Error::success();
1802 return make_error<StringError>(
1803 formatv("unknown module pass '{0}'", Name).str(),
1804 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001805}
1806
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001807Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1808 const PipelineElement &E, bool VerifyEachPass,
1809 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 == "cgscc") {
1816 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001817 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1818 VerifyEachPass, DebugLogging))
1819 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001820 // Add the nested pass manager with the appropriate adaptor.
1821 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001822 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001823 }
1824 if (Name == "function") {
1825 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001826 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1827 VerifyEachPass, DebugLogging))
1828 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001829 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001830 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001831 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001832 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001833 if (auto Count = parseRepeatPassName(Name)) {
1834 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001835 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1836 VerifyEachPass, DebugLogging))
1837 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001838 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001839 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001840 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001841 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1842 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001843 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1844 VerifyEachPass, DebugLogging))
1845 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001846 CGPM.addPass(
1847 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001848 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001849 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001850
1851 for (auto &C : CGSCCPipelineParsingCallbacks)
1852 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001853 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001854
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001855 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001856 return make_error<StringError>(
1857 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1858 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001859 }
1860
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001861// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001862#define CGSCC_PASS(NAME, CREATE_PASS) \
1863 if (Name == NAME) { \
1864 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001865 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001866 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001867#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1868 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001869 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001870 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001871 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1872 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001873 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001874 } \
1875 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001876 CGPM.addPass(InvalidateAnalysisPass< \
1877 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001878 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001879 }
1880#include "PassRegistry.def"
1881
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001882 for (auto &C : CGSCCPipelineParsingCallbacks)
1883 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001884 return Error::success();
1885 return make_error<StringError>(
1886 formatv("unknown cgscc pass '{0}'", Name).str(),
1887 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001888}
1889
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001890Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1891 const PipelineElement &E,
1892 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001893 auto &Name = E.Name;
1894 auto &InnerPipeline = E.InnerPipeline;
1895
1896 // First handle complex passes like the pass managers which carry pipelines.
1897 if (!InnerPipeline.empty()) {
1898 if (Name == "function") {
1899 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001900 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1901 VerifyEachPass, DebugLogging))
1902 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001903 // Add the nested pass manager with the appropriate adaptor.
1904 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001905 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001906 }
1907 if (Name == "loop") {
1908 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001909 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1910 DebugLogging))
1911 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001912 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001913 FPM.addPass(
1914 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001915 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001916 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001917 if (auto Count = parseRepeatPassName(Name)) {
1918 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001919 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1920 VerifyEachPass, DebugLogging))
1921 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001922 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001923 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001924 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001925
1926 for (auto &C : FunctionPipelineParsingCallbacks)
1927 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001928 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001929
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001930 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001931 return make_error<StringError>(
1932 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1933 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001934 }
1935
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001936// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001937#define FUNCTION_PASS(NAME, CREATE_PASS) \
1938 if (Name == NAME) { \
1939 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001940 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001941 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001942#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1943 if (checkParametrizedPassName(Name, NAME)) { \
1944 auto Params = parsePassParameters(PARSER, Name, NAME); \
1945 if (!Params) \
1946 return Params.takeError(); \
1947 FPM.addPass(CREATE_PASS(Params.get())); \
1948 return Error::success(); \
1949 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001950#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1951 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001952 FPM.addPass( \
1953 RequireAnalysisPass< \
1954 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001955 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001956 } \
1957 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001958 FPM.addPass(InvalidateAnalysisPass< \
1959 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001960 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001961 }
1962#include "PassRegistry.def"
1963
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001964 for (auto &C : FunctionPipelineParsingCallbacks)
1965 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001966 return Error::success();
1967 return make_error<StringError>(
1968 formatv("unknown function pass '{0}'", Name).str(),
1969 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001970}
1971
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001972Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1973 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001974 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001975 auto &InnerPipeline = E.InnerPipeline;
1976
1977 // First handle complex passes like the pass managers which carry pipelines.
1978 if (!InnerPipeline.empty()) {
1979 if (Name == "loop") {
1980 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001981 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1982 VerifyEachPass, DebugLogging))
1983 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001984 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001985 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001986 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001987 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001988 if (auto Count = parseRepeatPassName(Name)) {
1989 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001990 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1991 VerifyEachPass, DebugLogging))
1992 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001993 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001994 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001995 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001996
1997 for (auto &C : LoopPipelineParsingCallbacks)
1998 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001999 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002000
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002001 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002002 return make_error<StringError>(
2003 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2004 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002005 }
2006
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002007// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002008#define LOOP_PASS(NAME, CREATE_PASS) \
2009 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002010 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002011 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002012 }
2013#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2014 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002015 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002016 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2017 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2018 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002019 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002020 } \
2021 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002022 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002023 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002024 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002025 }
2026#include "PassRegistry.def"
2027
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002028 for (auto &C : LoopPipelineParsingCallbacks)
2029 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002030 return Error::success();
2031 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2032 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002033}
2034
Chandler Carruthedf59962016-02-18 09:45:17 +00002035bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002036#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2037 if (Name == NAME) { \
2038 AA.registerModuleAnalysis< \
2039 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2040 return true; \
2041 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002042#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2043 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002044 AA.registerFunctionAnalysis< \
2045 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002046 return true; \
2047 }
2048#include "PassRegistry.def"
2049
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002050 for (auto &C : AAParsingCallbacks)
2051 if (C(Name, AA))
2052 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002053 return false;
2054}
2055
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002056Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002057 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002058 bool VerifyEachPass,
2059 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002060 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002061 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2062 return Err;
2063 // FIXME: No verifier support for Loop passes!
2064 }
2065 return Error::success();
2066}
2067
2068Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2069 ArrayRef<PipelineElement> Pipeline,
2070 bool VerifyEachPass,
2071 bool DebugLogging) {
2072 for (const auto &Element : Pipeline) {
2073 if (auto Err =
2074 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2075 return Err;
2076 if (VerifyEachPass)
2077 FPM.addPass(VerifierPass());
2078 }
2079 return Error::success();
2080}
2081
2082Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2083 ArrayRef<PipelineElement> Pipeline,
2084 bool VerifyEachPass,
2085 bool DebugLogging) {
2086 for (const auto &Element : Pipeline) {
2087 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2088 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002089 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002090 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002091 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002092}
2093
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002094void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2095 FunctionAnalysisManager &FAM,
2096 CGSCCAnalysisManager &CGAM,
2097 ModuleAnalysisManager &MAM) {
2098 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2099 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002100 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2101 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2102 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2103 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2104 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2105}
2106
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002107Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2108 ArrayRef<PipelineElement> Pipeline,
2109 bool VerifyEachPass,
2110 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002111 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002112 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2113 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002114 if (VerifyEachPass)
2115 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002116 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002117 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002118}
2119
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002120// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002121// FIXME: Should this routine accept a TargetMachine or require the caller to
2122// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002123Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2124 StringRef PipelineText,
2125 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002126 auto Pipeline = parsePipelineText(PipelineText);
2127 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002128 return make_error<StringError>(
2129 formatv("invalid pipeline '{0}'", PipelineText).str(),
2130 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002131
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002132 // If the first name isn't at the module layer, wrap the pipeline up
2133 // automatically.
2134 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002135
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002136 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2137 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002138 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002139 } else if (isFunctionPassName(FirstName,
2140 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002141 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002142 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002143 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002144 } else {
2145 for (auto &C : TopLevelPipelineParsingCallbacks)
2146 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002147 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002148
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002149 // Unknown pass or pipeline name!
2150 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2151 return make_error<StringError>(
2152 formatv("unknown {0} name '{1}'",
2153 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2154 .str(),
2155 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002156 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002157 }
2158
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002159 if (auto Err =
2160 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2161 return Err;
2162 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002163}
Chandler Carruthedf59962016-02-18 09:45:17 +00002164
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002165// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002166Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2167 StringRef PipelineText,
2168 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002169 auto Pipeline = parsePipelineText(PipelineText);
2170 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002171 return make_error<StringError>(
2172 formatv("invalid pipeline '{0}'", PipelineText).str(),
2173 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002174
2175 StringRef FirstName = Pipeline->front().Name;
2176 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002177 return make_error<StringError>(
2178 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2179 PipelineText)
2180 .str(),
2181 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002182
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002183 if (auto Err =
2184 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2185 return Err;
2186 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002187}
2188
2189// Primary pass pipeline description parsing routine for a \c
2190// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002191Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2192 StringRef PipelineText,
2193 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002194 auto Pipeline = parsePipelineText(PipelineText);
2195 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002196 return make_error<StringError>(
2197 formatv("invalid pipeline '{0}'", PipelineText).str(),
2198 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002199
2200 StringRef FirstName = Pipeline->front().Name;
2201 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002202 return make_error<StringError>(
2203 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2204 PipelineText)
2205 .str(),
2206 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002207
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002208 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2209 DebugLogging))
2210 return Err;
2211 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002212}
2213
2214// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002215Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2216 StringRef PipelineText,
2217 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002218 auto Pipeline = parsePipelineText(PipelineText);
2219 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002220 return make_error<StringError>(
2221 formatv("invalid pipeline '{0}'", PipelineText).str(),
2222 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002223
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002224 if (auto Err =
2225 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2226 return Err;
2227
2228 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002229}
2230
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002231Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002232 // If the pipeline just consists of the word 'default' just replace the AA
2233 // manager with our default one.
2234 if (PipelineText == "default") {
2235 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002236 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002237 }
2238
Chandler Carruthedf59962016-02-18 09:45:17 +00002239 while (!PipelineText.empty()) {
2240 StringRef Name;
2241 std::tie(Name, PipelineText) = PipelineText.split(',');
2242 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002243 return make_error<StringError>(
2244 formatv("unknown alias analysis name '{0}'", Name).str(),
2245 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002246 }
2247
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002248 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002249}