blob: 074abebb1429f452aa5a41c40c6a1a942f0d1ae2 [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
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000212static cl::opt<bool>
213 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
214 cl::desc("Enable control height reduction optimization (CHR)"));
215
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000216extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000217extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000218
Wei Mi3bcccdf2019-01-17 20:48:34 +0000219extern cl::opt<bool> FlattenedProfileUsed;
220
Chandler Carruthe3f50642016-12-22 06:59:15 +0000221static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
222 switch (Level) {
223 case PassBuilder::O0:
224 case PassBuilder::O1:
225 case PassBuilder::O2:
226 case PassBuilder::O3:
227 return false;
228
229 case PassBuilder::Os:
230 case PassBuilder::Oz:
231 return true;
232 }
233 llvm_unreachable("Invalid optimization level!");
234}
235
Chandler Carruth66445382014-01-11 08:16:35 +0000236namespace {
237
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000238/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000239struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000240 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000241 return PreservedAnalyses::all();
242 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000243 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000244};
245
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000246/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000247class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
248 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000249 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000250
251public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000252 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000253 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000254 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000255};
256
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000257/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000258struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000259 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
260 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000261 return PreservedAnalyses::all();
262 }
263 static StringRef name() { return "NoOpCGSCCPass"; }
264};
265
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000266/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000267class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
268 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000269 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000270
271public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000272 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000273 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000274 return Result();
275 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000276 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000277};
278
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000279/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000280struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000281 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000282 return PreservedAnalyses::all();
283 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000284 static StringRef name() { return "NoOpFunctionPass"; }
285};
286
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000287/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000288class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
289 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000290 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000291
292public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000293 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000294 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000295 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000296};
297
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000298/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000299struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000300 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
301 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000302 return PreservedAnalyses::all();
303 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000304 static StringRef name() { return "NoOpLoopPass"; }
305};
306
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000307/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000308class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
309 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000310 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000311
312public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000313 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000314 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
315 return Result();
316 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000317 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000318};
319
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000320AnalysisKey NoOpModuleAnalysis::Key;
321AnalysisKey NoOpCGSCCAnalysis::Key;
322AnalysisKey NoOpFunctionAnalysis::Key;
323AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000324
Chandler Carruth66445382014-01-11 08:16:35 +0000325} // End anonymous namespace.
326
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000327void PassBuilder::invokePeepholeEPCallbacks(
328 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
329 for (auto &C : PeepholeEPCallbacks)
330 C(FPM, Level);
331}
332
Chandler Carruth1ff77242015-03-07 09:02:36 +0000333void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000334#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000335 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000336#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000337
338 for (auto &C : ModuleAnalysisRegistrationCallbacks)
339 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000340}
341
Chandler Carruth1ff77242015-03-07 09:02:36 +0000342void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000343#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000344 CGAM.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 : CGSCCAnalysisRegistrationCallbacks)
348 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000349}
350
Chandler Carruth1ff77242015-03-07 09:02:36 +0000351void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000352#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000353 FAM.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 : FunctionAnalysisRegistrationCallbacks)
357 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000358}
359
Justin Bognereecc3c82016-02-25 07:23:08 +0000360void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000361#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000362 LAM.registerPass([&] { return CREATE_PASS; });
363#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000364
365 for (auto &C : LoopAnalysisRegistrationCallbacks)
366 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000367}
368
Chandler Carruthe3f50642016-12-22 06:59:15 +0000369FunctionPassManager
370PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000371 ThinLTOPhase Phase,
372 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000373 assert(Level != O0 && "Must request optimizations!");
374 FunctionPassManager FPM(DebugLogging);
375
376 // Form SSA out of local memory accesses after breaking apart aggregates into
377 // scalars.
378 FPM.addPass(SROA());
379
380 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000381 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000382
Davide Italianoc3688312017-06-01 23:08:14 +0000383 // Hoisting of scalars and load expressions.
384 if (EnableGVNHoist)
385 FPM.addPass(GVNHoistPass());
386
Davide Italianobe1b6a92017-06-03 23:18:29 +0000387 // Global value numbering based sinking.
388 if (EnableGVNSink) {
389 FPM.addPass(GVNSinkPass());
390 FPM.addPass(SimplifyCFGPass());
391 }
392
Chandler Carruthe3f50642016-12-22 06:59:15 +0000393 // Speculative execution if the target has divergent branches; otherwise nop.
394 FPM.addPass(SpeculativeExecutionPass());
395
396 // Optimize based on known information about branches, and cleanup afterward.
397 FPM.addPass(JumpThreadingPass());
398 FPM.addPass(CorrelatedValuePropagationPass());
399 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000400 if (Level == O3)
401 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000402 FPM.addPass(InstCombinePass());
403
404 if (!isOptimizingForSize(Level))
405 FPM.addPass(LibCallsShrinkWrapPass());
406
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000407 invokePeepholeEPCallbacks(FPM, Level);
408
Rong Xue1f42452017-10-23 22:21:29 +0000409 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
410 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000411 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000412 !isOptimizingForSize(Level))
413 FPM.addPass(PGOMemOPSizeOpt());
414
Chandler Carruthe3f50642016-12-22 06:59:15 +0000415 FPM.addPass(TailCallElimPass());
416 FPM.addPass(SimplifyCFGPass());
417
418 // Form canonically associated expression trees, and simplify the trees using
419 // basic mathematical properties. For example, this will form (nearly)
420 // minimal multiplication trees.
421 FPM.addPass(ReassociatePass());
422
423 // Add the primary loop simplification pipeline.
424 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000425 // some function passes in between them. These can and should be removed
426 // and/or replaced by scheduling the loop pass equivalents in the correct
427 // positions. But those equivalent passes aren't powerful enough yet.
428 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
429 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
430 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
431 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000432 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
433
Chandler Carruth71fd2702018-05-30 02:46:45 +0000434 // Simplify the loop body. We do this initially to clean up after other loop
435 // passes run, either when iterating on a loop or on inner loops with
436 // implications on the outer loop.
437 LPM1.addPass(LoopInstSimplifyPass());
438 LPM1.addPass(LoopSimplifyCFGPass());
439
Chandler Carruthe3f50642016-12-22 06:59:15 +0000440 // Rotate Loop - disable header duplication at -Oz
441 LPM1.addPass(LoopRotatePass(Level != Oz));
442 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000443 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000444 LPM2.addPass(IndVarSimplifyPass());
445 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000446
447 for (auto &C : LateLoopOptimizationsEPCallbacks)
448 C(LPM2, Level);
449
Chandler Carruth79b733b2017-01-26 23:21:17 +0000450 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000451 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000452 // because it changes IR to makes profile annotation in back compile
453 // inaccurate.
Rong Xudb29a3a2019-03-04 20:21:27 +0000454 if (Phase != ThinLTOPhase::PreLink || !PGOOpt ||
455 PGOOpt->Action != PGOOptions::SampleUse)
Teresa Johnsonecd90132017-08-02 20:35:29 +0000456 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000457
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000458 for (auto &C : LoopOptimizerEndEPCallbacks)
459 C(LPM2, Level);
460
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000461 // We provide the opt remark emitter pass for LICM to use. We only need to do
462 // this once as it is immutable.
463 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000464 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000465 FPM.addPass(SimplifyCFGPass());
466 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000467 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000468
469 // Eliminate redundancies.
470 if (Level != O1) {
471 // These passes add substantial compile time so skip them at O1.
472 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000473 if (RunNewGVN)
474 FPM.addPass(NewGVNPass());
475 else
476 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000477 }
478
479 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
480 FPM.addPass(MemCpyOptPass());
481
482 // Sparse conditional constant propagation.
483 // FIXME: It isn't clear why we do this *after* loop passes rather than
484 // before...
485 FPM.addPass(SCCPPass());
486
487 // Delete dead bit computations (instcombine runs after to fold away the dead
488 // computations, and then ADCE will run later to exploit any new DCE
489 // opportunities that creates).
490 FPM.addPass(BDCEPass());
491
492 // Run instcombine after redundancy and dead bit elimination to exploit
493 // opportunities opened up by them.
494 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000495 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000496
497 // Re-consider control flow based optimizations after redundancy elimination,
498 // redo DCE, etc.
499 FPM.addPass(JumpThreadingPass());
500 FPM.addPass(CorrelatedValuePropagationPass());
501 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000502 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000503
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000504 for (auto &C : ScalarOptimizerLateEPCallbacks)
505 C(FPM, Level);
506
Chandler Carruthe3f50642016-12-22 06:59:15 +0000507 // Finally, do an expensive DCE pass to catch all the dead code exposed by
508 // the simplifications and basic cleanup after all the simplifications.
509 FPM.addPass(ADCEPass());
510 FPM.addPass(SimplifyCFGPass());
511 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000512 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000513
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000514 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000515 (PGOOpt->Action == PGOOptions::IRUse ||
516 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000517 FPM.addPass(ControlHeightReductionPass());
518
Chandler Carruthe3f50642016-12-22 06:59:15 +0000519 return FPM;
520}
521
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000522void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
523 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000524 bool RunProfileGen, bool IsCS,
525 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000526 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000527 // Generally running simplification passes and the inliner with an high
528 // threshold results in smaller executables, but there may be cases where
529 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000530 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
531 // IsCS is true).
532 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000533 InlineParams IP;
534
535 // In the old pass manager, this is a cl::opt. Should still this be one?
536 IP.DefaultThreshold = 75;
537
538 // FIXME: The hint threshold has the same value used by the regular inliner.
539 // This should probably be lowered after performance testing.
540 // FIXME: this comment is cargo culted from the old pass manager, revisit).
541 IP.HintThreshold = 325;
542
543 CGSCCPassManager CGPipeline(DebugLogging);
544
545 CGPipeline.addPass(InlinerPass(IP));
546
547 FunctionPassManager FPM;
548 FPM.addPass(SROA());
549 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
550 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
551 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000552 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000553
Davide Italiano513dfaa2017-02-13 15:26:22 +0000554 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
555
556 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
557 }
558
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000559 // Delete anything that is now dead to make sure that we don't instrument
560 // dead code. Instrumentation can end up keeping dead code around and
561 // dramatically increase code size.
562 MPM.addPass(GlobalDCEPass());
563
Davide Italiano513dfaa2017-02-13 15:26:22 +0000564 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000565 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000566
Xinliang David Lib67530e2017-06-25 00:26:43 +0000567 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000568 FPM.addPass(
569 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000570 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
571
Davide Italiano513dfaa2017-02-13 15:26:22 +0000572 // Add the profile lowering pass.
573 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000574 if (!ProfileFile.empty())
575 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000576 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000577 Options.UseBFIInPromotion = IsCS;
578 MPM.addPass(InstrProfiling(Options, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000579 } else if (!ProfileFile.empty()) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000580 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000581 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
582 // RequireAnalysisPass for PSI before subsequent non-module passes.
583 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
584 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000585}
586
Easwaran Raman8249fac2017-06-28 13:33:49 +0000587static InlineParams
588getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
589 auto O3 = PassBuilder::O3;
590 unsigned OptLevel = Level > O3 ? 2 : Level;
591 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
592 return getInlineParams(OptLevel, SizeLevel);
593}
594
Chandler Carruthe3f50642016-12-22 06:59:15 +0000595ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000596PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000597 ThinLTOPhase Phase,
598 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000599 ModulePassManager MPM(DebugLogging);
600
Rong Xudb29a3a2019-03-04 20:21:27 +0000601 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000602
603 // In ThinLTO mode, when flattened profile is used, all the available
604 // profile information will be annotated in PreLink phase so there is
605 // no need to load the profile again in PostLink.
606 bool LoadSampleProfile =
607 HasSampleProfile &&
608 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
609
610 // During the ThinLTO backend phase we perform early indirect call promotion
611 // here, before globalopt. Otherwise imported available_externally functions
612 // look unreferenced and are removed. If we are going to load the sample
613 // profile then defer until later.
614 // TODO: See if we can move later and consolidate with the location where
615 // we perform ICP when we are loading a sample profile.
616 // TODO: We pass HasSampleProfile (whether there was a sample profile file
617 // passed to the compile) to the SamplePGO flag of ICP. This is used to
618 // determine whether the new direct calls are annotated with prof metadata.
619 // Ideally this should be determined from whether the IR is annotated with
620 // sample profile, and not whether the a sample profile was provided on the
621 // command line. E.g. for flattened profiles where we will not be reloading
622 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
623 // provide the sample profile file.
624 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
625 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
626
Chandler Carruthe3f50642016-12-22 06:59:15 +0000627 // Do basic inference of function attributes from known properties of system
628 // libraries and other oracles.
629 MPM.addPass(InferFunctionAttrsPass());
630
631 // Create an early function pass manager to cleanup the output of the
632 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000633 FunctionPassManager EarlyFPM(DebugLogging);
634 EarlyFPM.addPass(SimplifyCFGPass());
635 EarlyFPM.addPass(SROA());
636 EarlyFPM.addPass(EarlyCSEPass());
637 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000638 if (Level == O3)
639 EarlyFPM.addPass(CallSiteSplittingPass());
640
Dehao Chen08f88312017-08-07 20:23:20 +0000641 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
642 // to convert bitcast to direct calls so that they can be inlined during the
643 // profile annotation prepration step.
644 // More details about SamplePGO design can be found in:
645 // https://research.google.com/pubs/pub45290.html
646 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000647 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000648 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000649 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000650
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000651 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000652 // Annotate sample profile right after early FPM to ensure freshness of
653 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000654 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000655 PGOOpt->ProfileRemappingFile,
656 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000657 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
658 // RequireAnalysisPass for PSI before subsequent non-module passes.
659 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000660 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
661 // for the profile annotation to be accurate in the ThinLTO backend.
662 if (Phase != ThinLTOPhase::PreLink)
663 // We perform early indirect call promotion here, before globalopt.
664 // This is important for the ThinLTO backend phase because otherwise
665 // imported available_externally functions look unreferenced and are
666 // removed.
667 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000668 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000669 }
670
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000671 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000672 // and prior to optimizing globals.
673 // FIXME: This position in the pipeline hasn't been carefully considered in
674 // years, it should be re-analyzed.
675 MPM.addPass(IPSCCPPass());
676
Matthew Simpsoncb585582017-10-25 13:40:08 +0000677 // Attach metadata to indirect call sites indicating the set of functions
678 // they may target at run-time. This should follow IPSCCP.
679 MPM.addPass(CalledValuePropagationPass());
680
Chandler Carruthe3f50642016-12-22 06:59:15 +0000681 // Optimize globals to try and fold them into constants.
682 MPM.addPass(GlobalOptPass());
683
684 // Promote any localized globals to SSA registers.
685 // FIXME: Should this instead by a run of SROA?
686 // FIXME: We should probably run instcombine and simplify-cfg afterward to
687 // delete control flows that are dead once globals have been folded to
688 // constants.
689 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
690
691 // Remove any dead arguments exposed by cleanups and constand folding
692 // globals.
693 MPM.addPass(DeadArgumentEliminationPass());
694
695 // Create a small function pass pipeline to cleanup after all the global
696 // optimizations.
697 FunctionPassManager GlobalCleanupPM(DebugLogging);
698 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000699 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
700
Chandler Carruthe3f50642016-12-22 06:59:15 +0000701 GlobalCleanupPM.addPass(SimplifyCFGPass());
702 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
703
Dehao Chen89d32262017-08-02 01:28:31 +0000704 // Add all the requested passes for instrumentation PGO, if requested.
705 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000706 (PGOOpt->Action == PGOOptions::IRInstr ||
707 PGOOpt->Action == PGOOptions::IRUse)) {
708 addPGOInstrPasses(MPM, DebugLogging, Level,
709 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
710 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000711 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000712 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000713 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000714 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
715 PGOOpt->CSAction == PGOOptions::CSIRInstr)
716 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000717
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000718 // Synthesize function entry counts for non-PGO compilation.
719 if (EnableSyntheticCounts && !PGOOpt)
720 MPM.addPass(SyntheticCountsPropagation());
721
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000722 // Require the GlobalsAA analysis for the module so we can query it within
723 // the CGSCC pipeline.
724 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000725
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000726 // Require the ProfileSummaryAnalysis for the module so we can query it within
727 // the inliner pass.
728 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
729
Chandler Carruthe3f50642016-12-22 06:59:15 +0000730 // Now begin the main postorder CGSCC pipeline.
731 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
732 // manager and trying to emulate its precise behavior. Much of this doesn't
733 // make a lot of sense and we should revisit the core CGSCC structure.
734 CGSCCPassManager MainCGPipeline(DebugLogging);
735
736 // Note: historically, the PruneEH pass was run first to deduce nounwind and
737 // generally clean up exception handling overhead. It isn't clear this is
738 // valuable as the inliner doesn't currently care whether it is inlining an
739 // invoke or a call.
740
741 // Run the inliner first. The theory is that we are walking bottom-up and so
742 // the callees have already been fully optimized, and we want to inline them
743 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000744 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000745 // because it makes profile annotation in the backend inaccurate.
746 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000747 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
748 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000749 IP.HotCallSiteThreshold = 0;
750 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000751
752 // Now deduce any function attributes based in the current code.
753 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
754
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000755 // When at O3 add argument promotion to the pass pipeline.
756 // FIXME: It isn't at all clear why this should be limited to O3.
757 if (Level == O3)
758 MainCGPipeline.addPass(ArgumentPromotionPass());
759
Chandler Carruthe3f50642016-12-22 06:59:15 +0000760 // Lastly, add the core function simplification pipeline nested inside the
761 // CGSCC walk.
762 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000763 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000764
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000765 for (auto &C : CGSCCOptimizerLateEPCallbacks)
766 C(MainCGPipeline, Level);
767
Chandler Carruth719ffe12017-02-12 05:38:04 +0000768 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
769 // to detect when we devirtualize indirect calls and iterate the SCC passes
770 // in that case to try and catch knock-on inlining or function attrs
771 // opportunities. Then we add it to the module pipeline by walking the SCCs
772 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000773 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000774 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000775 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000776
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000777 return MPM;
778}
779
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000780ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
781 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000782 ModulePassManager MPM(DebugLogging);
783
784 // Optimize globals now that the module is fully simplified.
785 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000786 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000787
Xinliang David Li126157c2017-05-22 16:41:57 +0000788 // Run partial inlining pass to partially inline functions that have
789 // large bodies.
790 if (RunPartialInlining)
791 MPM.addPass(PartialInlinerPass());
792
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000793 // Remove avail extern fns and globals definitions since we aren't compiling
794 // an object file for later LTO. For LTO we want to preserve these so they
795 // are eligible for inlining at link-time. Note if they are unreferenced they
796 // will be removed by GlobalDCE later, so this only impacts referenced
797 // available externally globals. Eventually they will be suppressed during
798 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
799 // may make globals referenced by available external functions dead and saves
800 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000801 MPM.addPass(EliminateAvailableExternallyPass());
802
Manman Ren18295122019-02-28 20:13:38 +0000803 if (EnableOrderFileInstrumentation)
804 MPM.addPass(InstrOrderFilePass());
805
Chandler Carruthe3f50642016-12-22 06:59:15 +0000806 // Do RPO function attribute inference across the module to forward-propagate
807 // attributes where applicable.
808 // FIXME: Is this really an optimization rather than a canonicalization?
809 MPM.addPass(ReversePostOrderFunctionAttrsPass());
810
Rong Xudb29a3a2019-03-04 20:21:27 +0000811 // Do a post inline PGO instrumentation and use pass. This is a context
812 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
813 // cross-module inline has not been done yet. The context sensitive
814 // instrumentation is after all the inlines are done.
815 if (!LTOPreLink && PGOOpt) {
816 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
817 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
818 /* IsCS */ true, PGOOpt->CSProfileGenFile,
819 PGOOpt->ProfileRemappingFile);
820 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
821 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
822 /* IsCS */ true, PGOOpt->ProfileFile,
823 PGOOpt->ProfileRemappingFile);
824 }
825
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000826 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000827 // useful as the above will have inlined, DCE'ed, and function-attr
828 // propagated everything. We should at this point have a reasonably minimal
829 // and richly annotated call graph. By computing aliasing and mod/ref
830 // information for all local globals here, the late loop passes and notably
831 // the vectorizer will be able to use them to help recognize vectorizable
832 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000833 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000834
835 FunctionPassManager OptimizePM(DebugLogging);
836 OptimizePM.addPass(Float2IntPass());
837 // FIXME: We need to run some loop optimizations to re-rotate loops after
838 // simplify-cfg and others undo their rotation.
839
840 // Optimize the loop execution. These passes operate on entire loop nests
841 // rather than on each loop in an inside-out manner, and so they are actually
842 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000843
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000844 for (auto &C : VectorizerStartEPCallbacks)
845 C(OptimizePM, Level);
846
Chandler Carrutha95ff382017-01-27 00:50:21 +0000847 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000848 OptimizePM.addPass(
849 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000850
851 // Distribute loops to allow partial vectorization. I.e. isolate dependences
852 // into separate loop that would otherwise inhibit vectorization. This is
853 // currently only performed for loops marked with the metadata
854 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000855 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000856
857 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000858 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000859
Chandler Carruthbaabda92017-01-27 01:32:26 +0000860 // Eliminate loads by forwarding stores from the previous iteration to loads
861 // of the current iteration.
862 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000863
864 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000865 OptimizePM.addPass(InstCombinePass());
866
Chandler Carrutha95ff382017-01-27 00:50:21 +0000867 // Now that we've formed fast to execute loop structures, we do further
868 // optimizations. These are run afterward as they might block doing complex
869 // analyses and transforms such as what are needed for loop vectorization.
870
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000871 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
872 // GVN, loop transforms, and others have already run, so it's now better to
873 // convert to more optimized IR using more aggressive simplify CFG options.
874 // The extra sinking transform can create larger basic blocks, so do this
875 // before SLP vectorization.
876 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
877 forwardSwitchCondToPhi(true).
878 convertSwitchToLookupTable(true).
879 needCanonicalLoops(false).
880 sinkCommonInsts(true)));
881
Chandler Carruthe3f50642016-12-22 06:59:15 +0000882 // Optimize parallel scalar instruction chains into SIMD instructions.
883 OptimizePM.addPass(SLPVectorizerPass());
884
Chandler Carruthe3f50642016-12-22 06:59:15 +0000885 OptimizePM.addPass(InstCombinePass());
886
887 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000888 // execution resources of an out-of-order processor. We also then need to
889 // clean up redundancies and loop invariant code.
890 // FIXME: It would be really good to use a loop-integrated instruction
891 // combiner for cleanup here so that the unrolling and LICM can be pipelined
892 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000893 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
894 if (EnableUnrollAndJam) {
895 OptimizePM.addPass(
896 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
897 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000898 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000899 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000900 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000901 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000902 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000903
904 // Now that we've vectorized and unrolled loops, we may have more refined
905 // alignment information, try to re-derive it here.
906 OptimizePM.addPass(AlignmentFromAssumptionsPass());
907
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000908 // Split out cold code. Splitting is done late to avoid hiding context from
909 // other optimizations and inadvertently regressing performance. The tradeoff
910 // is that this has a higher code size cost than splitting early.
911 if (EnableHotColdSplit && !LTOPreLink)
912 MPM.addPass(HotColdSplittingPass());
913
Chandler Carrutha95ff382017-01-27 00:50:21 +0000914 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
915 // canonicalization pass that enables other optimizations. As a result,
916 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
917 // result too early.
918 OptimizePM.addPass(LoopSinkPass());
919
920 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000921 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000922
Sanjay Patel6fd43912017-09-09 13:38:18 +0000923 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
924 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
925 // flattening of blocks.
926 OptimizePM.addPass(DivRemPairsPass());
927
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000928 // LoopSink (and other loop passes since the last simplifyCFG) might have
929 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
930 OptimizePM.addPass(SimplifyCFGPass());
931
Chandler Carruthc34f7892017-11-28 11:32:31 +0000932 // Optimize PHIs by speculating around them when profitable. Note that this
933 // pass needs to be run after any PRE or similar pass as it is essentially
934 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
935 OptimizePM.addPass(SpeculateAroundPHIsPass());
936
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000937 for (auto &C : OptimizerLastEPCallbacks)
938 C(OptimizePM, Level);
939
Chandler Carrutha95ff382017-01-27 00:50:21 +0000940 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000941 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
942
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000943 MPM.addPass(CGProfilePass());
944
Chandler Carruthe3f50642016-12-22 06:59:15 +0000945 // Now we need to do some global optimization transforms.
946 // FIXME: It would seem like these should come first in the optimization
947 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
948 // ordering here.
949 MPM.addPass(GlobalDCEPass());
950 MPM.addPass(ConstantMergePass());
951
952 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000953}
954
Chandler Carruthe3f50642016-12-22 06:59:15 +0000955ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000956PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000957 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000958 assert(Level != O0 && "Must request optimizations for the default pipeline!");
959
960 ModulePassManager MPM(DebugLogging);
961
962 // Force any function attributes we want the rest of the pipeline to observe.
963 MPM.addPass(ForceFunctionAttrsPass());
964
David Blaikie0c64f5a2018-01-23 01:25:20 +0000965 // Apply module pipeline start EP callback.
966 for (auto &C : PipelineStartEPCallbacks)
967 C(MPM);
968
Dehao Chen08f88312017-08-07 20:23:20 +0000969 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000970 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
971
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000972 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000973 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
974 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000975
976 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000977 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000978
979 return MPM;
980}
981
982ModulePassManager
983PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
984 bool DebugLogging) {
985 assert(Level != O0 && "Must request optimizations for the default pipeline!");
986
987 ModulePassManager MPM(DebugLogging);
988
989 // Force any function attributes we want the rest of the pipeline to observe.
990 MPM.addPass(ForceFunctionAttrsPass());
991
Dehao Chen08f88312017-08-07 20:23:20 +0000992 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000993 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
994
David Blaikie0c64f5a2018-01-23 01:25:20 +0000995 // Apply module pipeline start EP callback.
996 for (auto &C : PipelineStartEPCallbacks)
997 C(MPM);
998
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000999 // If we are planning to perform ThinLTO later, we don't bloat the code with
1000 // unrolling/vectorization/... now. Just simplify the module as much as we
1001 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001002 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1003 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001004
1005 // Run partial inlining pass to partially inline functions that have
1006 // large bodies.
1007 // FIXME: It isn't clear whether this is really the right place to run this
1008 // in ThinLTO. Because there is another canonicalization and simplification
1009 // phase that will run after the thin link, running this here ends up with
1010 // less information than will be available later and it may grow functions in
1011 // ways that aren't beneficial.
1012 if (RunPartialInlining)
1013 MPM.addPass(PartialInlinerPass());
1014
1015 // Reduce the size of the IR as much as possible.
1016 MPM.addPass(GlobalOptPass());
1017
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001018 return MPM;
1019}
1020
Teresa Johnson28023db2018-07-19 14:51:32 +00001021ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1022 OptimizationLevel Level, bool DebugLogging,
1023 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001024 ModulePassManager MPM(DebugLogging);
1025
Teresa Johnson28023db2018-07-19 14:51:32 +00001026 if (ImportSummary) {
1027 // These passes import type identifier resolutions for whole-program
1028 // devirtualization and CFI. They must run early because other passes may
1029 // disturb the specific instruction patterns that these passes look for,
1030 // creating dependencies on resolutions that may not appear in the summary.
1031 //
1032 // For example, GVN may transform the pattern assume(type.test) appearing in
1033 // two basic blocks into assume(phi(type.test, type.test)), which would
1034 // transform a dependency on a WPD resolution into a dependency on a type
1035 // identifier resolution for CFI.
1036 //
1037 // Also, WPD has access to more precise information than ICP and can
1038 // devirtualize more effectively, so it should operate on the IR first.
1039 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1040 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1041 }
1042
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001043 // Force any function attributes we want the rest of the pipeline to observe.
1044 MPM.addPass(ForceFunctionAttrsPass());
1045
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001046 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001047 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1048 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001049
1050 // Now add the optimization pipeline.
1051 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1052
1053 return MPM;
1054}
1055
1056ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001057PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1058 bool DebugLogging) {
1059 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001060 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001061 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001062 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001063}
1064
Teresa Johnson28023db2018-07-19 14:51:32 +00001065ModulePassManager
1066PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1067 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001068 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1069 ModulePassManager MPM(DebugLogging);
1070
Rong Xudb29a3a2019-03-04 20:21:27 +00001071 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001072 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001073 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001074 PGOOpt->ProfileRemappingFile,
1075 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001076 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1077 // RequireAnalysisPass for PSI before subsequent non-module passes.
1078 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001079 }
1080
Davide Italiano089a9122017-01-24 00:57:39 +00001081 // Remove unused virtual tables to improve the quality of code generated by
1082 // whole-program devirtualization and bitset lowering.
1083 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001084
Davide Italiano089a9122017-01-24 00:57:39 +00001085 // Force any function attributes we want the rest of the pipeline to observe.
1086 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001087
Davide Italiano089a9122017-01-24 00:57:39 +00001088 // Do basic inference of function attributes from known properties of system
1089 // libraries and other oracles.
1090 MPM.addPass(InferFunctionAttrsPass());
1091
1092 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001093 FunctionPassManager EarlyFPM(DebugLogging);
1094 EarlyFPM.addPass(CallSiteSplittingPass());
1095 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1096
Davide Italiano089a9122017-01-24 00:57:39 +00001097 // Indirect call promotion. This should promote all the targets that are
1098 // left by the earlier promotion pass that promotes intra-module targets.
1099 // This two-step promotion is to save the compile time. For LTO, it should
1100 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001101 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001102 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001103 // Propagate constants at call sites into the functions they call. This
1104 // opens opportunities for globalopt (and inlining) by substituting function
1105 // pointers passed as arguments to direct uses of functions.
1106 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001107
1108 // Attach metadata to indirect call sites indicating the set of functions
1109 // they may target at run-time. This should follow IPSCCP.
1110 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001111 }
1112
1113 // Now deduce any function attributes based in the current code.
1114 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1115 PostOrderFunctionAttrsPass()));
1116
1117 // Do RPO function attribute inference across the module to forward-propagate
1118 // attributes where applicable.
1119 // FIXME: Is this really an optimization rather than a canonicalization?
1120 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1121
Eric Christopher721eaef2019-02-26 20:33:22 +00001122 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001123 MPM.addPass(GlobalSplitPass());
1124
1125 // Run whole program optimization of virtual call when the list of callees
1126 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001127 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001128
1129 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001130 if (Level == 1) {
1131 // The LowerTypeTestsPass needs to run to lower type metadata and the
1132 // type.test intrinsics. The pass does nothing if CFI is disabled.
1133 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001134 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001135 }
Davide Italiano089a9122017-01-24 00:57:39 +00001136
1137 // Optimize globals to try and fold them into constants.
1138 MPM.addPass(GlobalOptPass());
1139
1140 // Promote any localized globals to SSA registers.
1141 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1142
1143 // Linking modules together can lead to duplicate global constant, only
1144 // keep one copy of each constant.
1145 MPM.addPass(ConstantMergePass());
1146
1147 // Remove unused arguments from functions.
1148 MPM.addPass(DeadArgumentEliminationPass());
1149
1150 // Reduce the code after globalopt and ipsccp. Both can open up significant
1151 // simplification opportunities, and both can propagate functions through
1152 // function pointers. When this happens, we often have to resolve varargs
1153 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001154 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001155 if (Level == O3)
1156 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001157 PeepholeFPM.addPass(InstCombinePass());
1158 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1159
1160 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001161
1162 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1163 // generally clean up exception handling overhead. It isn't clear this is
1164 // valuable as the inliner doesn't currently care whether it is inlining an
1165 // invoke or a call.
1166 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001167 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1168 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001169
1170 // Optimize globals again after we ran the inliner.
1171 MPM.addPass(GlobalOptPass());
1172
1173 // Garbage collect dead functions.
1174 // FIXME: Add ArgumentPromotion pass after once it's ported.
1175 MPM.addPass(GlobalDCEPass());
1176
1177 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001178 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001179 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001180 invokePeepholeEPCallbacks(FPM, Level);
1181
Davide Italiano089a9122017-01-24 00:57:39 +00001182 FPM.addPass(JumpThreadingPass());
1183
Rong Xudb29a3a2019-03-04 20:21:27 +00001184 // Do a post inline PGO instrumentation and use pass. This is a context
1185 // sensitive PGO pass.
1186 if (PGOOpt) {
1187 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1188 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1189 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1190 PGOOpt->ProfileRemappingFile);
1191 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1192 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1193 /* IsCS */ true, PGOOpt->ProfileFile,
1194 PGOOpt->ProfileRemappingFile);
1195 }
1196
Davide Italiano089a9122017-01-24 00:57:39 +00001197 // Break up allocas
1198 FPM.addPass(SROA());
1199
Robert Lougherf2158a82019-03-20 19:08:18 +00001200 // LTO provides additional opportunities for tailcall elimination due to
1201 // link-time inlining, and visibility of nocapture attribute.
1202 FPM.addPass(TailCallElimPass());
1203
Davide Italiano089a9122017-01-24 00:57:39 +00001204 // Run a few AA driver optimizations here and now to cleanup the code.
1205 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1206
1207 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1208 PostOrderFunctionAttrsPass()));
1209 // FIXME: here we run IP alias analysis in the legacy PM.
1210
1211 FunctionPassManager MainFPM;
1212
1213 // FIXME: once we fix LoopPass Manager, add LICM here.
1214 // FIXME: once we provide support for enabling MLSM, add it here.
1215 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001216 if (RunNewGVN)
1217 MainFPM.addPass(NewGVNPass());
1218 else
1219 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001220
1221 // Remove dead memcpy()'s.
1222 MainFPM.addPass(MemCpyOptPass());
1223
1224 // Nuke dead stores.
1225 MainFPM.addPass(DSEPass());
1226
1227 // FIXME: at this point, we run a bunch of loop passes:
1228 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1229 // loopVectorize. Enable them once the remaining issue with LPM
1230 // are sorted out.
1231
1232 MainFPM.addPass(InstCombinePass());
1233 MainFPM.addPass(SimplifyCFGPass());
1234 MainFPM.addPass(SCCPPass());
1235 MainFPM.addPass(InstCombinePass());
1236 MainFPM.addPass(BDCEPass());
1237
1238 // FIXME: We may want to run SLPVectorizer here.
1239 // After vectorization, assume intrinsics may tell us more
1240 // about pointer alignments.
1241#if 0
1242 MainFPM.add(AlignmentFromAssumptionsPass());
1243#endif
1244
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001245 // FIXME: Conditionally run LoadCombine here, after it's ported
1246 // (in case we still have this pass, given its questionable usefulness).
1247
Davide Italiano089a9122017-01-24 00:57:39 +00001248 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001249 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001250 MainFPM.addPass(JumpThreadingPass());
1251 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1252
1253 // Create a function that performs CFI checks for cross-DSO calls with
1254 // targets in the current module.
1255 MPM.addPass(CrossDSOCFIPass());
1256
1257 // Lower type metadata and the type.test intrinsic. This pass supports
1258 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1259 // to be run at link time if CFI is enabled. This pass does nothing if
1260 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001261 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001262
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001263 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1264 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1265 if (EnableHotColdSplit)
1266 MPM.addPass(HotColdSplittingPass());
1267
Davide Italiano089a9122017-01-24 00:57:39 +00001268 // Add late LTO optimization passes.
1269 // Delete basic blocks, which optimization passes may have killed.
1270 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1271
1272 // Drop bodies of available eternally objects to improve GlobalDCE.
1273 MPM.addPass(EliminateAvailableExternallyPass());
1274
1275 // Now that we have optimized the program, discard unreachable functions.
1276 MPM.addPass(GlobalDCEPass());
1277
1278 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001279 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001280}
1281
Chandler Carruth060ad612016-12-23 20:38:19 +00001282AAManager PassBuilder::buildDefaultAAPipeline() {
1283 AAManager AA;
1284
1285 // The order in which these are registered determines their priority when
1286 // being queried.
1287
1288 // First we register the basic alias analysis that provides the majority of
1289 // per-function local AA logic. This is a stateless, on-demand local set of
1290 // AA techniques.
1291 AA.registerFunctionAnalysis<BasicAA>();
1292
1293 // Next we query fast, specialized alias analyses that wrap IR-embedded
1294 // information about aliasing.
1295 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1296 AA.registerFunctionAnalysis<TypeBasedAA>();
1297
1298 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001299 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1300 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001301 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001302 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001303
1304 return AA;
1305}
1306
Chandler Carruth241bf242016-08-03 07:44:48 +00001307static Optional<int> parseRepeatPassName(StringRef Name) {
1308 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1309 return None;
1310 int Count;
1311 if (Name.getAsInteger(0, Count) || Count <= 0)
1312 return None;
1313 return Count;
1314}
1315
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001316static Optional<int> parseDevirtPassName(StringRef Name) {
1317 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1318 return None;
1319 int Count;
1320 if (Name.getAsInteger(0, Count) || Count <= 0)
1321 return None;
1322 return Count;
1323}
1324
Fedor Sergeevb7871402019-01-10 10:01:53 +00001325static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1326 if (!Name.consume_front(PassName))
1327 return false;
1328 // normal pass name w/o parameters == default parameters
1329 if (Name.empty())
1330 return true;
1331 return Name.startswith("<") && Name.endswith(">");
1332}
1333
1334namespace {
1335
1336/// This performs customized parsing of pass name with parameters.
1337///
1338/// We do not need parametrization of passes in textual pipeline very often,
1339/// yet on a rare occasion ability to specify parameters right there can be
1340/// useful.
1341///
1342/// \p Name - parameterized specification of a pass from a textual pipeline
1343/// is a string in a form of :
1344/// PassName '<' parameter-list '>'
1345///
1346/// Parameter list is being parsed by the parser callable argument, \p Parser,
1347/// It takes a string-ref of parameters and returns either StringError or a
1348/// parameter list in a form of a custom parameters type, all wrapped into
1349/// Expected<> template class.
1350///
1351template <typename ParametersParseCallableT>
1352auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1353 StringRef PassName) -> decltype(Parser(StringRef{})) {
1354 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1355
1356 StringRef Params = Name;
1357 if (!Params.consume_front(PassName)) {
1358 assert(false &&
1359 "unable to strip pass name from parametrized pass specification");
1360 }
1361 if (Params.empty())
1362 return ParametersT{};
1363 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1364 assert(false && "invalid format for parametrized pass name");
1365 }
1366
1367 Expected<ParametersT> Result = Parser(Params);
1368 assert((Result || Result.template errorIsA<StringError>()) &&
1369 "Pass parameter parser can only return StringErrors.");
1370 return std::move(Result);
1371}
1372
1373/// Parser of parameters for LoopUnroll pass.
1374Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1375 LoopUnrollOptions UnrollOpts;
1376 while (!Params.empty()) {
1377 StringRef ParamName;
1378 std::tie(ParamName, Params) = Params.split(';');
1379 int OptLevel = StringSwitch<int>(ParamName)
1380 .Case("O0", 0)
1381 .Case("O1", 1)
1382 .Case("O2", 2)
1383 .Case("O3", 3)
1384 .Default(-1);
1385 if (OptLevel >= 0) {
1386 UnrollOpts.setOptLevel(OptLevel);
1387 continue;
1388 }
1389
1390 bool Enable = !ParamName.consume_front("no-");
1391 if (ParamName == "partial") {
1392 UnrollOpts.setPartial(Enable);
1393 } else if (ParamName == "peeling") {
1394 UnrollOpts.setPeeling(Enable);
1395 } else if (ParamName == "runtime") {
1396 UnrollOpts.setRuntime(Enable);
1397 } else if (ParamName == "upperbound") {
1398 UnrollOpts.setUpperBound(Enable);
1399 } else {
1400 return make_error<StringError>(
1401 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1402 inconvertibleErrorCode());
1403 }
1404 }
1405 return UnrollOpts;
1406}
1407
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001408Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1409 MemorySanitizerOptions Result;
1410 while (!Params.empty()) {
1411 StringRef ParamName;
1412 std::tie(ParamName, Params) = Params.split(';');
1413
1414 if (ParamName == "recover") {
1415 Result.Recover = true;
1416 } else if (ParamName == "kernel") {
1417 Result.Kernel = true;
1418 } else if (ParamName.consume_front("track-origins=")) {
1419 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1420 return make_error<StringError>(
1421 formatv("invalid argument to MemorySanitizer pass track-origins "
1422 "parameter: '{0}' ",
1423 ParamName)
1424 .str(),
1425 inconvertibleErrorCode());
1426 } else {
1427 return make_error<StringError>(
1428 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1429 .str(),
1430 inconvertibleErrorCode());
1431 }
1432 }
1433 return Result;
1434}
1435
Serguei Katkovf5432832019-04-15 08:57:53 +00001436/// Parser of parameters for SimplifyCFG pass.
1437Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1438 SimplifyCFGOptions Result;
1439 while (!Params.empty()) {
1440 StringRef ParamName;
1441 std::tie(ParamName, Params) = Params.split(';');
1442
1443 bool Enable = !ParamName.consume_front("no-");
1444 if (ParamName == "forward-switch-cond") {
1445 Result.forwardSwitchCondToPhi(Enable);
1446 } else if (ParamName == "switch-to-lookup") {
1447 Result.convertSwitchToLookupTable(Enable);
1448 } else if (ParamName == "keep-loops") {
1449 Result.needCanonicalLoops(Enable);
1450 } else if (ParamName == "sink-common-insts") {
1451 Result.sinkCommonInsts(Enable);
1452 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1453 APInt BonusInstThreshold;
1454 if (ParamName.getAsInteger(0, BonusInstThreshold))
1455 return make_error<StringError>(
1456 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1457 "parameter: '{0}' ",
1458 ParamName).str(),
1459 inconvertibleErrorCode());
1460 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1461 } else {
1462 return make_error<StringError>(
1463 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1464 inconvertibleErrorCode());
1465 }
1466 }
1467 return Result;
1468}
1469
Fedor Sergeevb7871402019-01-10 10:01:53 +00001470} // namespace
1471
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001472/// Tests whether a pass name starts with a valid prefix for a default pipeline
1473/// alias.
1474static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1475 return Name.startswith("default") || Name.startswith("thinlto") ||
1476 Name.startswith("lto");
1477}
1478
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001479/// Tests whether registered callbacks will accept a given pass name.
1480///
1481/// When parsing a pipeline text, the type of the outermost pipeline may be
1482/// omitted, in which case the type is automatically determined from the first
1483/// pass name in the text. This may be a name that is handled through one of the
1484/// callbacks. We check this through the oridinary parsing callbacks by setting
1485/// up a dummy PassManager in order to not force the client to also handle this
1486/// type of query.
1487template <typename PassManagerT, typename CallbacksT>
1488static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1489 if (!Callbacks.empty()) {
1490 PassManagerT DummyPM;
1491 for (auto &CB : Callbacks)
1492 if (CB(Name, DummyPM, {}))
1493 return true;
1494 }
1495 return false;
1496}
1497
1498template <typename CallbacksT>
1499static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001500 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001501 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001502 return DefaultAliasRegex.match(Name);
1503
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001504 // Explicitly handle pass manager names.
1505 if (Name == "module")
1506 return true;
1507 if (Name == "cgscc")
1508 return true;
1509 if (Name == "function")
1510 return true;
1511
Chandler Carruth241bf242016-08-03 07:44:48 +00001512 // Explicitly handle custom-parsed pass names.
1513 if (parseRepeatPassName(Name))
1514 return true;
1515
Chandler Carruth74a8a222016-06-17 07:15:29 +00001516#define MODULE_PASS(NAME, CREATE_PASS) \
1517 if (Name == NAME) \
1518 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001519#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001520 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001521 return true;
1522#include "PassRegistry.def"
1523
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001524 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001525}
1526
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001527template <typename CallbacksT>
1528static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001529 // Explicitly handle pass manager names.
1530 if (Name == "cgscc")
1531 return true;
1532 if (Name == "function")
1533 return true;
1534
Chandler Carruth241bf242016-08-03 07:44:48 +00001535 // Explicitly handle custom-parsed pass names.
1536 if (parseRepeatPassName(Name))
1537 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001538 if (parseDevirtPassName(Name))
1539 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001540
Chandler Carruth74a8a222016-06-17 07:15:29 +00001541#define CGSCC_PASS(NAME, CREATE_PASS) \
1542 if (Name == NAME) \
1543 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001544#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001545 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001546 return true;
1547#include "PassRegistry.def"
1548
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001549 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001550}
1551
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001552template <typename CallbacksT>
1553static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001554 // Explicitly handle pass manager names.
1555 if (Name == "function")
1556 return true;
1557 if (Name == "loop")
1558 return true;
1559
Chandler Carruth241bf242016-08-03 07:44:48 +00001560 // Explicitly handle custom-parsed pass names.
1561 if (parseRepeatPassName(Name))
1562 return true;
1563
Chandler Carruth74a8a222016-06-17 07:15:29 +00001564#define FUNCTION_PASS(NAME, CREATE_PASS) \
1565 if (Name == NAME) \
1566 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001567#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1568 if (checkParametrizedPassName(Name, NAME)) \
1569 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001570#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001571 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001572 return true;
1573#include "PassRegistry.def"
1574
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001575 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001576}
1577
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001578template <typename CallbacksT>
1579static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001580 // Explicitly handle pass manager names.
1581 if (Name == "loop")
1582 return true;
1583
Chandler Carruth241bf242016-08-03 07:44:48 +00001584 // Explicitly handle custom-parsed pass names.
1585 if (parseRepeatPassName(Name))
1586 return true;
1587
Chandler Carruth74a8a222016-06-17 07:15:29 +00001588#define LOOP_PASS(NAME, CREATE_PASS) \
1589 if (Name == NAME) \
1590 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001591#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1592 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1593 return true;
1594#include "PassRegistry.def"
1595
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001596 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001597}
1598
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001599Optional<std::vector<PassBuilder::PipelineElement>>
1600PassBuilder::parsePipelineText(StringRef Text) {
1601 std::vector<PipelineElement> ResultPipeline;
1602
1603 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1604 &ResultPipeline};
1605 for (;;) {
1606 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1607 size_t Pos = Text.find_first_of(",()");
1608 Pipeline.push_back({Text.substr(0, Pos), {}});
1609
1610 // If we have a single terminating name, we're done.
1611 if (Pos == Text.npos)
1612 break;
1613
1614 char Sep = Text[Pos];
1615 Text = Text.substr(Pos + 1);
1616 if (Sep == ',')
1617 // Just a name ending in a comma, continue.
1618 continue;
1619
1620 if (Sep == '(') {
1621 // Push the inner pipeline onto the stack to continue processing.
1622 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1623 continue;
1624 }
1625
1626 assert(Sep == ')' && "Bogus separator!");
1627 // When handling the close parenthesis, we greedily consume them to avoid
1628 // empty strings in the pipeline.
1629 do {
1630 // If we try to pop the outer pipeline we have unbalanced parentheses.
1631 if (PipelineStack.size() == 1)
1632 return None;
1633
1634 PipelineStack.pop_back();
1635 } while (Text.consume_front(")"));
1636
1637 // Check if we've finished parsing.
1638 if (Text.empty())
1639 break;
1640
1641 // Otherwise, the end of an inner pipeline always has to be followed by
1642 // a comma, and then we can continue.
1643 if (!Text.consume_front(","))
1644 return None;
1645 }
1646
1647 if (PipelineStack.size() > 1)
1648 // Unbalanced paretheses.
1649 return None;
1650
1651 assert(PipelineStack.back() == &ResultPipeline &&
1652 "Wrong pipeline at the bottom of the stack!");
1653 return {std::move(ResultPipeline)};
1654}
1655
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001656Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1657 const PipelineElement &E,
1658 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001659 auto &Name = E.Name;
1660 auto &InnerPipeline = E.InnerPipeline;
1661
1662 // First handle complex passes like the pass managers which carry pipelines.
1663 if (!InnerPipeline.empty()) {
1664 if (Name == "module") {
1665 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001666 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1667 VerifyEachPass, DebugLogging))
1668 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001669 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001670 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001671 }
1672 if (Name == "cgscc") {
1673 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001674 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1675 DebugLogging))
1676 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001677 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001678 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001679 }
1680 if (Name == "function") {
1681 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001682 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1683 VerifyEachPass, DebugLogging))
1684 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001685 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001686 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001687 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001688 if (auto Count = parseRepeatPassName(Name)) {
1689 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001690 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1691 VerifyEachPass, DebugLogging))
1692 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001693 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001694 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001695 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001696
1697 for (auto &C : ModulePipelineParsingCallbacks)
1698 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001699 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001700
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001701 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001702 return make_error<StringError>(
1703 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1704 inconvertibleErrorCode());
1705 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001706 }
1707
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001708 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001709 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001710 SmallVector<StringRef, 3> Matches;
1711 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001712 return make_error<StringError>(
1713 formatv("unknown default pipeline alias '{0}'", Name).str(),
1714 inconvertibleErrorCode());
1715
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001716 assert(Matches.size() == 3 && "Must capture two matched strings!");
1717
Jordan Rosef85a95f2016-07-25 18:34:51 +00001718 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001719 .Case("O0", O0)
1720 .Case("O1", O1)
1721 .Case("O2", O2)
1722 .Case("O3", O3)
1723 .Case("Os", Os)
1724 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001725 if (L == O0)
1726 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001727 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001728
1729 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001730 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001731 } else if (Matches[1] == "thinlto-pre-link") {
1732 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1733 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001734 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001735 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001736 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001737 } else {
1738 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001739 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001740 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001741 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001742 }
1743
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001744 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001745#define MODULE_PASS(NAME, CREATE_PASS) \
1746 if (Name == NAME) { \
1747 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001748 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001749 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001750#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1751 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001752 MPM.addPass( \
1753 RequireAnalysisPass< \
1754 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001755 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001756 } \
1757 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001758 MPM.addPass(InvalidateAnalysisPass< \
1759 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001760 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001761 }
1762#include "PassRegistry.def"
1763
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001764 for (auto &C : ModulePipelineParsingCallbacks)
1765 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001766 return Error::success();
1767 return make_error<StringError>(
1768 formatv("unknown module pass '{0}'", Name).str(),
1769 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001770}
1771
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001772Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1773 const PipelineElement &E, bool VerifyEachPass,
1774 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001775 auto &Name = E.Name;
1776 auto &InnerPipeline = E.InnerPipeline;
1777
1778 // First handle complex passes like the pass managers which carry pipelines.
1779 if (!InnerPipeline.empty()) {
1780 if (Name == "cgscc") {
1781 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001782 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1783 VerifyEachPass, DebugLogging))
1784 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001785 // Add the nested pass manager with the appropriate adaptor.
1786 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001787 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001788 }
1789 if (Name == "function") {
1790 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001791 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1792 VerifyEachPass, DebugLogging))
1793 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001794 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001795 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001796 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001797 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001798 if (auto Count = parseRepeatPassName(Name)) {
1799 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001800 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1801 VerifyEachPass, DebugLogging))
1802 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001803 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001804 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001805 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001806 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1807 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001808 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1809 VerifyEachPass, DebugLogging))
1810 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001811 CGPM.addPass(
1812 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001813 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001814 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001815
1816 for (auto &C : CGSCCPipelineParsingCallbacks)
1817 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001818 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001819
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001820 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001821 return make_error<StringError>(
1822 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1823 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001824 }
1825
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001826// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001827#define CGSCC_PASS(NAME, CREATE_PASS) \
1828 if (Name == NAME) { \
1829 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001830 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001831 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001832#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1833 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001834 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001835 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001836 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1837 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001838 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001839 } \
1840 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001841 CGPM.addPass(InvalidateAnalysisPass< \
1842 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001843 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001844 }
1845#include "PassRegistry.def"
1846
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001847 for (auto &C : CGSCCPipelineParsingCallbacks)
1848 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001849 return Error::success();
1850 return make_error<StringError>(
1851 formatv("unknown cgscc pass '{0}'", Name).str(),
1852 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001853}
1854
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001855Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1856 const PipelineElement &E,
1857 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001858 auto &Name = E.Name;
1859 auto &InnerPipeline = E.InnerPipeline;
1860
1861 // First handle complex passes like the pass managers which carry pipelines.
1862 if (!InnerPipeline.empty()) {
1863 if (Name == "function") {
1864 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001865 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1866 VerifyEachPass, DebugLogging))
1867 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001868 // Add the nested pass manager with the appropriate adaptor.
1869 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001870 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001871 }
1872 if (Name == "loop") {
1873 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001874 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1875 DebugLogging))
1876 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001877 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001878 FPM.addPass(
1879 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001880 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001881 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001882 if (auto Count = parseRepeatPassName(Name)) {
1883 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001884 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1885 VerifyEachPass, DebugLogging))
1886 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001887 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001888 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001889 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001890
1891 for (auto &C : FunctionPipelineParsingCallbacks)
1892 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001893 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001894
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001895 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001896 return make_error<StringError>(
1897 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1898 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001899 }
1900
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001901// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001902#define FUNCTION_PASS(NAME, CREATE_PASS) \
1903 if (Name == NAME) { \
1904 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001905 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001906 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001907#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1908 if (checkParametrizedPassName(Name, NAME)) { \
1909 auto Params = parsePassParameters(PARSER, Name, NAME); \
1910 if (!Params) \
1911 return Params.takeError(); \
1912 FPM.addPass(CREATE_PASS(Params.get())); \
1913 return Error::success(); \
1914 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001915#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1916 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001917 FPM.addPass( \
1918 RequireAnalysisPass< \
1919 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001920 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001921 } \
1922 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001923 FPM.addPass(InvalidateAnalysisPass< \
1924 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001925 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001926 }
1927#include "PassRegistry.def"
1928
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001929 for (auto &C : FunctionPipelineParsingCallbacks)
1930 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001931 return Error::success();
1932 return make_error<StringError>(
1933 formatv("unknown function pass '{0}'", Name).str(),
1934 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001935}
1936
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001937Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1938 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001939 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001940 auto &InnerPipeline = E.InnerPipeline;
1941
1942 // First handle complex passes like the pass managers which carry pipelines.
1943 if (!InnerPipeline.empty()) {
1944 if (Name == "loop") {
1945 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001946 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1947 VerifyEachPass, DebugLogging))
1948 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001949 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001950 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001951 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001952 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001953 if (auto Count = parseRepeatPassName(Name)) {
1954 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001955 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1956 VerifyEachPass, DebugLogging))
1957 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001958 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001959 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001960 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001961
1962 for (auto &C : LoopPipelineParsingCallbacks)
1963 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001964 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001965
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001966 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001967 return make_error<StringError>(
1968 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1969 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001970 }
1971
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001972// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001973#define LOOP_PASS(NAME, CREATE_PASS) \
1974 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001975 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001976 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001977 }
1978#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1979 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001980 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001981 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1982 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1983 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001984 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001985 } \
1986 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001987 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001988 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001989 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001990 }
1991#include "PassRegistry.def"
1992
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001993 for (auto &C : LoopPipelineParsingCallbacks)
1994 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001995 return Error::success();
1996 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1997 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001998}
1999
Chandler Carruthedf59962016-02-18 09:45:17 +00002000bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002001#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2002 if (Name == NAME) { \
2003 AA.registerModuleAnalysis< \
2004 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2005 return true; \
2006 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002007#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2008 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002009 AA.registerFunctionAnalysis< \
2010 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002011 return true; \
2012 }
2013#include "PassRegistry.def"
2014
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002015 for (auto &C : AAParsingCallbacks)
2016 if (C(Name, AA))
2017 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002018 return false;
2019}
2020
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002021Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002022 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002023 bool VerifyEachPass,
2024 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002025 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002026 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2027 return Err;
2028 // FIXME: No verifier support for Loop passes!
2029 }
2030 return Error::success();
2031}
2032
2033Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2034 ArrayRef<PipelineElement> Pipeline,
2035 bool VerifyEachPass,
2036 bool DebugLogging) {
2037 for (const auto &Element : Pipeline) {
2038 if (auto Err =
2039 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2040 return Err;
2041 if (VerifyEachPass)
2042 FPM.addPass(VerifierPass());
2043 }
2044 return Error::success();
2045}
2046
2047Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2048 ArrayRef<PipelineElement> Pipeline,
2049 bool VerifyEachPass,
2050 bool DebugLogging) {
2051 for (const auto &Element : Pipeline) {
2052 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2053 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002054 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002055 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002056 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002057}
2058
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002059void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2060 FunctionAnalysisManager &FAM,
2061 CGSCCAnalysisManager &CGAM,
2062 ModuleAnalysisManager &MAM) {
2063 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2064 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002065 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2066 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2067 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2068 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2069 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2070}
2071
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002072Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2073 ArrayRef<PipelineElement> Pipeline,
2074 bool VerifyEachPass,
2075 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002076 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002077 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2078 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002079 if (VerifyEachPass)
2080 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002081 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002082 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002083}
2084
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002085// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002086// FIXME: Should this routine accept a TargetMachine or require the caller to
2087// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002088Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2089 StringRef PipelineText,
2090 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002091 auto Pipeline = parsePipelineText(PipelineText);
2092 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002093 return make_error<StringError>(
2094 formatv("invalid pipeline '{0}'", PipelineText).str(),
2095 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002096
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002097 // If the first name isn't at the module layer, wrap the pipeline up
2098 // automatically.
2099 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002100
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002101 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2102 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002103 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002104 } else if (isFunctionPassName(FirstName,
2105 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002106 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002107 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002108 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002109 } else {
2110 for (auto &C : TopLevelPipelineParsingCallbacks)
2111 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002112 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002113
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002114 // Unknown pass or pipeline name!
2115 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2116 return make_error<StringError>(
2117 formatv("unknown {0} name '{1}'",
2118 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2119 .str(),
2120 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002121 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002122 }
2123
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002124 if (auto Err =
2125 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2126 return Err;
2127 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002128}
Chandler Carruthedf59962016-02-18 09:45:17 +00002129
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002130// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002131Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2132 StringRef PipelineText,
2133 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002134 auto Pipeline = parsePipelineText(PipelineText);
2135 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002136 return make_error<StringError>(
2137 formatv("invalid pipeline '{0}'", PipelineText).str(),
2138 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002139
2140 StringRef FirstName = Pipeline->front().Name;
2141 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002142 return make_error<StringError>(
2143 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2144 PipelineText)
2145 .str(),
2146 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002147
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002148 if (auto Err =
2149 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2150 return Err;
2151 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002152}
2153
2154// Primary pass pipeline description parsing routine for a \c
2155// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002156Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2157 StringRef PipelineText,
2158 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002159 auto Pipeline = parsePipelineText(PipelineText);
2160 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002161 return make_error<StringError>(
2162 formatv("invalid pipeline '{0}'", PipelineText).str(),
2163 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002164
2165 StringRef FirstName = Pipeline->front().Name;
2166 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002167 return make_error<StringError>(
2168 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2169 PipelineText)
2170 .str(),
2171 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002172
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002173 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2174 DebugLogging))
2175 return Err;
2176 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002177}
2178
2179// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002180Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2181 StringRef PipelineText,
2182 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002183 auto Pipeline = parsePipelineText(PipelineText);
2184 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002185 return make_error<StringError>(
2186 formatv("invalid pipeline '{0}'", PipelineText).str(),
2187 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002188
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002189 if (auto Err =
2190 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2191 return Err;
2192
2193 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002194}
2195
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002196Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002197 // If the pipeline just consists of the word 'default' just replace the AA
2198 // manager with our default one.
2199 if (PipelineText == "default") {
2200 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002201 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002202 }
2203
Chandler Carruthedf59962016-02-18 09:45:17 +00002204 while (!PipelineText.empty()) {
2205 StringRef Name;
2206 std::tie(Name, PipelineText) = PipelineText.split(',');
2207 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002208 return make_error<StringError>(
2209 formatv("unknown alias analysis name '{0}'", Name).str(),
2210 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002211 }
2212
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002213 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002214}