blob: 89b9c520af83738da722da9f8929d4ba3cfa1ead [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
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000188static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000189 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
190 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000191
Davide Italianobe1b6a92017-06-03 23:18:29 +0000192static cl::opt<bool> EnableGVNSink(
193 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
194 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
195
David Green963401d2018-07-01 12:47:30 +0000196static cl::opt<bool> EnableUnrollAndJam(
197 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
198 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
199
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000200static cl::opt<bool> EnableSyntheticCounts(
201 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
202 cl::desc("Run synthetic function entry count generation "
203 "pass"));
204
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000205static Regex DefaultAliasRegex(
206 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000207
Eric Christophereff3b6f2019-04-18 06:17:40 +0000208// This option is used in simplifying testing SampleFDO optimizations for
209// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000210static cl::opt<bool>
211 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
212 cl::desc("Enable control height reduction optimization (CHR)"));
213
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000214PipelineTuningOptions::PipelineTuningOptions() {
215 LoopInterleaving = EnableLoopInterleaving;
216 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea458c7332019-05-08 17:58:35 +0000217 SLPVectorization = RunSLPVectorization;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000218 LicmMssaOptCap = SetLicmMssaOptCap;
219 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000220}
221
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000222extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000223extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000224
Wei Mi3bcccdf2019-01-17 20:48:34 +0000225extern cl::opt<bool> FlattenedProfileUsed;
226
Chandler Carruthe3f50642016-12-22 06:59:15 +0000227static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
228 switch (Level) {
229 case PassBuilder::O0:
230 case PassBuilder::O1:
231 case PassBuilder::O2:
232 case PassBuilder::O3:
233 return false;
234
235 case PassBuilder::Os:
236 case PassBuilder::Oz:
237 return true;
238 }
239 llvm_unreachable("Invalid optimization level!");
240}
241
Chandler Carruth66445382014-01-11 08:16:35 +0000242namespace {
243
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000244/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000245struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000246 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000247 return PreservedAnalyses::all();
248 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000249 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000250};
251
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000252/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000253class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
254 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000255 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000256
257public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000258 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000259 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000260 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000261};
262
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000263/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000264struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000265 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
266 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000267 return PreservedAnalyses::all();
268 }
269 static StringRef name() { return "NoOpCGSCCPass"; }
270};
271
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000272/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000273class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
274 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000275 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000276
277public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000278 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000279 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000280 return Result();
281 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000282 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000283};
284
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000285/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000286struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000287 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000288 return PreservedAnalyses::all();
289 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000290 static StringRef name() { return "NoOpFunctionPass"; }
291};
292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000293/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000294class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
295 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000296 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000297
298public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000299 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000300 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000301 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000302};
303
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000304/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000305struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000306 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
307 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000308 return PreservedAnalyses::all();
309 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000310 static StringRef name() { return "NoOpLoopPass"; }
311};
312
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000313/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000314class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
315 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000316 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000317
318public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000319 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000320 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
321 return Result();
322 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000323 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000324};
325
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000326AnalysisKey NoOpModuleAnalysis::Key;
327AnalysisKey NoOpCGSCCAnalysis::Key;
328AnalysisKey NoOpFunctionAnalysis::Key;
329AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000330
Chandler Carruth66445382014-01-11 08:16:35 +0000331} // End anonymous namespace.
332
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000333void PassBuilder::invokePeepholeEPCallbacks(
334 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
335 for (auto &C : PeepholeEPCallbacks)
336 C(FPM, Level);
337}
338
Chandler Carruth1ff77242015-03-07 09:02:36 +0000339void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000340#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000341 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000342#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000343
344 for (auto &C : ModuleAnalysisRegistrationCallbacks)
345 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000346}
347
Chandler Carruth1ff77242015-03-07 09:02:36 +0000348void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000349#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000350 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000351#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000352
353 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
354 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000355}
356
Chandler Carruth1ff77242015-03-07 09:02:36 +0000357void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000358#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000359 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000360#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000361
362 for (auto &C : FunctionAnalysisRegistrationCallbacks)
363 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000364}
365
Justin Bognereecc3c82016-02-25 07:23:08 +0000366void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000367#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000368 LAM.registerPass([&] { return CREATE_PASS; });
369#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000370
371 for (auto &C : LoopAnalysisRegistrationCallbacks)
372 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000373}
374
Chandler Carruthe3f50642016-12-22 06:59:15 +0000375FunctionPassManager
376PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000377 ThinLTOPhase Phase,
378 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000379 assert(Level != O0 && "Must request optimizations!");
380 FunctionPassManager FPM(DebugLogging);
381
382 // Form SSA out of local memory accesses after breaking apart aggregates into
383 // scalars.
384 FPM.addPass(SROA());
385
386 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000387 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000388
Davide Italianoc3688312017-06-01 23:08:14 +0000389 // Hoisting of scalars and load expressions.
390 if (EnableGVNHoist)
391 FPM.addPass(GVNHoistPass());
392
Davide Italianobe1b6a92017-06-03 23:18:29 +0000393 // Global value numbering based sinking.
394 if (EnableGVNSink) {
395 FPM.addPass(GVNSinkPass());
396 FPM.addPass(SimplifyCFGPass());
397 }
398
Chandler Carruthe3f50642016-12-22 06:59:15 +0000399 // Speculative execution if the target has divergent branches; otherwise nop.
400 FPM.addPass(SpeculativeExecutionPass());
401
402 // Optimize based on known information about branches, and cleanup afterward.
403 FPM.addPass(JumpThreadingPass());
404 FPM.addPass(CorrelatedValuePropagationPass());
405 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000406 if (Level == O3)
407 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000408 FPM.addPass(InstCombinePass());
409
410 if (!isOptimizingForSize(Level))
411 FPM.addPass(LibCallsShrinkWrapPass());
412
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000413 invokePeepholeEPCallbacks(FPM, Level);
414
Rong Xue1f42452017-10-23 22:21:29 +0000415 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
416 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000417 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000418 !isOptimizingForSize(Level))
419 FPM.addPass(PGOMemOPSizeOpt());
420
Chandler Carruthe3f50642016-12-22 06:59:15 +0000421 FPM.addPass(TailCallElimPass());
422 FPM.addPass(SimplifyCFGPass());
423
424 // Form canonically associated expression trees, and simplify the trees using
425 // basic mathematical properties. For example, this will form (nearly)
426 // minimal multiplication trees.
427 FPM.addPass(ReassociatePass());
428
429 // Add the primary loop simplification pipeline.
430 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000431 // some function passes in between them. These can and should be removed
432 // and/or replaced by scheduling the loop pass equivalents in the correct
433 // positions. But those equivalent passes aren't powerful enough yet.
434 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
435 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
436 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
437 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000438 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
439
Chandler Carruth71fd2702018-05-30 02:46:45 +0000440 // Simplify the loop body. We do this initially to clean up after other loop
441 // passes run, either when iterating on a loop or on inner loops with
442 // implications on the outer loop.
443 LPM1.addPass(LoopInstSimplifyPass());
444 LPM1.addPass(LoopSimplifyCFGPass());
445
Chandler Carruthe3f50642016-12-22 06:59:15 +0000446 // Rotate Loop - disable header duplication at -Oz
447 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000448 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000449 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000450 LPM2.addPass(IndVarSimplifyPass());
451 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000452
453 for (auto &C : LateLoopOptimizationsEPCallbacks)
454 C(LPM2, Level);
455
Chandler Carruth79b733b2017-01-26 23:21:17 +0000456 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000457 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000458 // because it changes IR to makes profile annotation in back compile
459 // inaccurate.
Rong Xudb29a3a2019-03-04 20:21:27 +0000460 if (Phase != ThinLTOPhase::PreLink || !PGOOpt ||
461 PGOOpt->Action != PGOOptions::SampleUse)
Teresa Johnsonecd90132017-08-02 20:35:29 +0000462 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000463
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000464 for (auto &C : LoopOptimizerEndEPCallbacks)
465 C(LPM2, Level);
466
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000467 // We provide the opt remark emitter pass for LICM to use. We only need to do
468 // this once as it is immutable.
469 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000470 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000471 FPM.addPass(SimplifyCFGPass());
472 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000473 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000474
475 // Eliminate redundancies.
476 if (Level != O1) {
477 // These passes add substantial compile time so skip them at O1.
478 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000479 if (RunNewGVN)
480 FPM.addPass(NewGVNPass());
481 else
482 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000483 }
484
485 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
486 FPM.addPass(MemCpyOptPass());
487
488 // Sparse conditional constant propagation.
489 // FIXME: It isn't clear why we do this *after* loop passes rather than
490 // before...
491 FPM.addPass(SCCPPass());
492
493 // Delete dead bit computations (instcombine runs after to fold away the dead
494 // computations, and then ADCE will run later to exploit any new DCE
495 // opportunities that creates).
496 FPM.addPass(BDCEPass());
497
498 // Run instcombine after redundancy and dead bit elimination to exploit
499 // opportunities opened up by them.
500 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000501 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000502
503 // Re-consider control flow based optimizations after redundancy elimination,
504 // redo DCE, etc.
505 FPM.addPass(JumpThreadingPass());
506 FPM.addPass(CorrelatedValuePropagationPass());
507 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000508 FPM.addPass(createFunctionToLoopPassAdaptor(
509 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
510 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000511
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000512 for (auto &C : ScalarOptimizerLateEPCallbacks)
513 C(FPM, Level);
514
Chandler Carruthe3f50642016-12-22 06:59:15 +0000515 // Finally, do an expensive DCE pass to catch all the dead code exposed by
516 // the simplifications and basic cleanup after all the simplifications.
517 FPM.addPass(ADCEPass());
518 FPM.addPass(SimplifyCFGPass());
519 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000520 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000521
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000522 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000523 (PGOOpt->Action == PGOOptions::IRUse ||
524 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000525 FPM.addPass(ControlHeightReductionPass());
526
Chandler Carruthe3f50642016-12-22 06:59:15 +0000527 return FPM;
528}
529
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000530void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
531 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000532 bool RunProfileGen, bool IsCS,
533 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000534 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000535 // Generally running simplification passes and the inliner with an high
536 // threshold results in smaller executables, but there may be cases where
537 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000538 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
539 // IsCS is true).
540 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000541 InlineParams IP;
542
543 // In the old pass manager, this is a cl::opt. Should still this be one?
544 IP.DefaultThreshold = 75;
545
546 // FIXME: The hint threshold has the same value used by the regular inliner.
547 // This should probably be lowered after performance testing.
548 // FIXME: this comment is cargo culted from the old pass manager, revisit).
549 IP.HintThreshold = 325;
550
551 CGSCCPassManager CGPipeline(DebugLogging);
552
553 CGPipeline.addPass(InlinerPass(IP));
554
555 FunctionPassManager FPM;
556 FPM.addPass(SROA());
557 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
558 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
559 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000560 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000561
Davide Italiano513dfaa2017-02-13 15:26:22 +0000562 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
563
564 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
565 }
566
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000567 // Delete anything that is now dead to make sure that we don't instrument
568 // dead code. Instrumentation can end up keeping dead code around and
569 // dramatically increase code size.
570 MPM.addPass(GlobalDCEPass());
571
Davide Italiano513dfaa2017-02-13 15:26:22 +0000572 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000573 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000574
Xinliang David Lib67530e2017-06-25 00:26:43 +0000575 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000576 FPM.addPass(
577 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000578 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
579
Davide Italiano513dfaa2017-02-13 15:26:22 +0000580 // Add the profile lowering pass.
581 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000582 if (!ProfileFile.empty())
583 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000584 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000585 Options.UseBFIInPromotion = IsCS;
586 MPM.addPass(InstrProfiling(Options, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000587 } else if (!ProfileFile.empty()) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000588 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000589 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
590 // RequireAnalysisPass for PSI before subsequent non-module passes.
591 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
592 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000593}
594
Easwaran Raman8249fac2017-06-28 13:33:49 +0000595static InlineParams
596getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
597 auto O3 = PassBuilder::O3;
598 unsigned OptLevel = Level > O3 ? 2 : Level;
599 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
600 return getInlineParams(OptLevel, SizeLevel);
601}
602
Chandler Carruthe3f50642016-12-22 06:59:15 +0000603ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000604PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000605 ThinLTOPhase Phase,
606 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000607 ModulePassManager MPM(DebugLogging);
608
Rong Xudb29a3a2019-03-04 20:21:27 +0000609 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000610
611 // In ThinLTO mode, when flattened profile is used, all the available
612 // profile information will be annotated in PreLink phase so there is
613 // no need to load the profile again in PostLink.
614 bool LoadSampleProfile =
615 HasSampleProfile &&
616 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
617
618 // During the ThinLTO backend phase we perform early indirect call promotion
619 // here, before globalopt. Otherwise imported available_externally functions
620 // look unreferenced and are removed. If we are going to load the sample
621 // profile then defer until later.
622 // TODO: See if we can move later and consolidate with the location where
623 // we perform ICP when we are loading a sample profile.
624 // TODO: We pass HasSampleProfile (whether there was a sample profile file
625 // passed to the compile) to the SamplePGO flag of ICP. This is used to
626 // determine whether the new direct calls are annotated with prof metadata.
627 // Ideally this should be determined from whether the IR is annotated with
628 // sample profile, and not whether the a sample profile was provided on the
629 // command line. E.g. for flattened profiles where we will not be reloading
630 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
631 // provide the sample profile file.
632 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
633 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
634
Chandler Carruthe3f50642016-12-22 06:59:15 +0000635 // Do basic inference of function attributes from known properties of system
636 // libraries and other oracles.
637 MPM.addPass(InferFunctionAttrsPass());
638
639 // Create an early function pass manager to cleanup the output of the
640 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000641 FunctionPassManager EarlyFPM(DebugLogging);
642 EarlyFPM.addPass(SimplifyCFGPass());
643 EarlyFPM.addPass(SROA());
644 EarlyFPM.addPass(EarlyCSEPass());
645 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000646 if (Level == O3)
647 EarlyFPM.addPass(CallSiteSplittingPass());
648
Dehao Chen08f88312017-08-07 20:23:20 +0000649 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
650 // to convert bitcast to direct calls so that they can be inlined during the
651 // profile annotation prepration step.
652 // More details about SamplePGO design can be found in:
653 // https://research.google.com/pubs/pub45290.html
654 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000655 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000656 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000657 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000658
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000659 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000660 // Annotate sample profile right after early FPM to ensure freshness of
661 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000662 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000663 PGOOpt->ProfileRemappingFile,
664 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000665 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
666 // RequireAnalysisPass for PSI before subsequent non-module passes.
667 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000668 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
669 // for the profile annotation to be accurate in the ThinLTO backend.
670 if (Phase != ThinLTOPhase::PreLink)
671 // We perform early indirect call promotion here, before globalopt.
672 // This is important for the ThinLTO backend phase because otherwise
673 // imported available_externally functions look unreferenced and are
674 // removed.
675 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000676 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000677 }
678
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000679 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000680 // and prior to optimizing globals.
681 // FIXME: This position in the pipeline hasn't been carefully considered in
682 // years, it should be re-analyzed.
683 MPM.addPass(IPSCCPPass());
684
Matthew Simpsoncb585582017-10-25 13:40:08 +0000685 // Attach metadata to indirect call sites indicating the set of functions
686 // they may target at run-time. This should follow IPSCCP.
687 MPM.addPass(CalledValuePropagationPass());
688
Chandler Carruthe3f50642016-12-22 06:59:15 +0000689 // Optimize globals to try and fold them into constants.
690 MPM.addPass(GlobalOptPass());
691
692 // Promote any localized globals to SSA registers.
693 // FIXME: Should this instead by a run of SROA?
694 // FIXME: We should probably run instcombine and simplify-cfg afterward to
695 // delete control flows that are dead once globals have been folded to
696 // constants.
697 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
698
699 // Remove any dead arguments exposed by cleanups and constand folding
700 // globals.
701 MPM.addPass(DeadArgumentEliminationPass());
702
703 // Create a small function pass pipeline to cleanup after all the global
704 // optimizations.
705 FunctionPassManager GlobalCleanupPM(DebugLogging);
706 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000707 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
708
Chandler Carruthe3f50642016-12-22 06:59:15 +0000709 GlobalCleanupPM.addPass(SimplifyCFGPass());
710 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
711
Dehao Chen89d32262017-08-02 01:28:31 +0000712 // Add all the requested passes for instrumentation PGO, if requested.
713 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000714 (PGOOpt->Action == PGOOptions::IRInstr ||
715 PGOOpt->Action == PGOOptions::IRUse)) {
716 addPGOInstrPasses(MPM, DebugLogging, Level,
717 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
718 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000719 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000720 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000721 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000722 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
723 PGOOpt->CSAction == PGOOptions::CSIRInstr)
724 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000725
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000726 // Synthesize function entry counts for non-PGO compilation.
727 if (EnableSyntheticCounts && !PGOOpt)
728 MPM.addPass(SyntheticCountsPropagation());
729
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000730 // Require the GlobalsAA analysis for the module so we can query it within
731 // the CGSCC pipeline.
732 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000733
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000734 // Require the ProfileSummaryAnalysis for the module so we can query it within
735 // the inliner pass.
736 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
737
Chandler Carruthe3f50642016-12-22 06:59:15 +0000738 // Now begin the main postorder CGSCC pipeline.
739 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
740 // manager and trying to emulate its precise behavior. Much of this doesn't
741 // make a lot of sense and we should revisit the core CGSCC structure.
742 CGSCCPassManager MainCGPipeline(DebugLogging);
743
744 // Note: historically, the PruneEH pass was run first to deduce nounwind and
745 // generally clean up exception handling overhead. It isn't clear this is
746 // valuable as the inliner doesn't currently care whether it is inlining an
747 // invoke or a call.
748
749 // Run the inliner first. The theory is that we are walking bottom-up and so
750 // the callees have already been fully optimized, and we want to inline them
751 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000752 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000753 // because it makes profile annotation in the backend inaccurate.
754 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000755 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
756 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000757 IP.HotCallSiteThreshold = 0;
758 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000759
760 // Now deduce any function attributes based in the current code.
761 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
762
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000763 // When at O3 add argument promotion to the pass pipeline.
764 // FIXME: It isn't at all clear why this should be limited to O3.
765 if (Level == O3)
766 MainCGPipeline.addPass(ArgumentPromotionPass());
767
Chandler Carruthe3f50642016-12-22 06:59:15 +0000768 // Lastly, add the core function simplification pipeline nested inside the
769 // CGSCC walk.
770 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000771 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000772
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000773 for (auto &C : CGSCCOptimizerLateEPCallbacks)
774 C(MainCGPipeline, Level);
775
Chandler Carruth719ffe12017-02-12 05:38:04 +0000776 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
777 // to detect when we devirtualize indirect calls and iterate the SCC passes
778 // in that case to try and catch knock-on inlining or function attrs
779 // opportunities. Then we add it to the module pipeline by walking the SCCs
780 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000781 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000782 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000783 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000784
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000785 return MPM;
786}
787
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000788ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
789 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000790 ModulePassManager MPM(DebugLogging);
791
792 // Optimize globals now that the module is fully simplified.
793 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000794 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000795
Xinliang David Li126157c2017-05-22 16:41:57 +0000796 // Run partial inlining pass to partially inline functions that have
797 // large bodies.
798 if (RunPartialInlining)
799 MPM.addPass(PartialInlinerPass());
800
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000801 // Remove avail extern fns and globals definitions since we aren't compiling
802 // an object file for later LTO. For LTO we want to preserve these so they
803 // are eligible for inlining at link-time. Note if they are unreferenced they
804 // will be removed by GlobalDCE later, so this only impacts referenced
805 // available externally globals. Eventually they will be suppressed during
806 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
807 // may make globals referenced by available external functions dead and saves
808 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000809 MPM.addPass(EliminateAvailableExternallyPass());
810
Manman Ren18295122019-02-28 20:13:38 +0000811 if (EnableOrderFileInstrumentation)
812 MPM.addPass(InstrOrderFilePass());
813
Chandler Carruthe3f50642016-12-22 06:59:15 +0000814 // Do RPO function attribute inference across the module to forward-propagate
815 // attributes where applicable.
816 // FIXME: Is this really an optimization rather than a canonicalization?
817 MPM.addPass(ReversePostOrderFunctionAttrsPass());
818
Rong Xudb29a3a2019-03-04 20:21:27 +0000819 // Do a post inline PGO instrumentation and use pass. This is a context
820 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
821 // cross-module inline has not been done yet. The context sensitive
822 // instrumentation is after all the inlines are done.
823 if (!LTOPreLink && PGOOpt) {
824 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
825 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
826 /* IsCS */ true, PGOOpt->CSProfileGenFile,
827 PGOOpt->ProfileRemappingFile);
828 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
829 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
830 /* IsCS */ true, PGOOpt->ProfileFile,
831 PGOOpt->ProfileRemappingFile);
832 }
833
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000834 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000835 // useful as the above will have inlined, DCE'ed, and function-attr
836 // propagated everything. We should at this point have a reasonably minimal
837 // and richly annotated call graph. By computing aliasing and mod/ref
838 // information for all local globals here, the late loop passes and notably
839 // the vectorizer will be able to use them to help recognize vectorizable
840 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000841 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000842
843 FunctionPassManager OptimizePM(DebugLogging);
844 OptimizePM.addPass(Float2IntPass());
845 // FIXME: We need to run some loop optimizations to re-rotate loops after
846 // simplify-cfg and others undo their rotation.
847
848 // Optimize the loop execution. These passes operate on entire loop nests
849 // rather than on each loop in an inside-out manner, and so they are actually
850 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000851
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000852 for (auto &C : VectorizerStartEPCallbacks)
853 C(OptimizePM, Level);
854
Chandler Carrutha95ff382017-01-27 00:50:21 +0000855 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000856 OptimizePM.addPass(
857 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000858
859 // Distribute loops to allow partial vectorization. I.e. isolate dependences
860 // into separate loop that would otherwise inhibit vectorization. This is
861 // currently only performed for loops marked with the metadata
862 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000863 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000864
865 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000866 OptimizePM.addPass(LoopVectorizePass(
867 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000868
Chandler Carruthbaabda92017-01-27 01:32:26 +0000869 // Eliminate loads by forwarding stores from the previous iteration to loads
870 // of the current iteration.
871 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000872
873 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000874 OptimizePM.addPass(InstCombinePass());
875
Chandler Carrutha95ff382017-01-27 00:50:21 +0000876 // Now that we've formed fast to execute loop structures, we do further
877 // optimizations. These are run afterward as they might block doing complex
878 // analyses and transforms such as what are needed for loop vectorization.
879
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000880 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
881 // GVN, loop transforms, and others have already run, so it's now better to
882 // convert to more optimized IR using more aggressive simplify CFG options.
883 // The extra sinking transform can create larger basic blocks, so do this
884 // before SLP vectorization.
885 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
886 forwardSwitchCondToPhi(true).
887 convertSwitchToLookupTable(true).
888 needCanonicalLoops(false).
889 sinkCommonInsts(true)));
890
Chandler Carruthe3f50642016-12-22 06:59:15 +0000891 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000892 if (PTO.SLPVectorization)
893 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000894
Chandler Carruthe3f50642016-12-22 06:59:15 +0000895 OptimizePM.addPass(InstCombinePass());
896
897 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000898 // execution resources of an out-of-order processor. We also then need to
899 // clean up redundancies and loop invariant code.
900 // FIXME: It would be really good to use a loop-integrated instruction
901 // combiner for cleanup here so that the unrolling and LICM can be pipelined
902 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000903 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
904 if (EnableUnrollAndJam) {
905 OptimizePM.addPass(
906 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
907 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000908 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000909 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000910 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000911 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000912 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
913 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
914 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000915
916 // Now that we've vectorized and unrolled loops, we may have more refined
917 // alignment information, try to re-derive it here.
918 OptimizePM.addPass(AlignmentFromAssumptionsPass());
919
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000920 // Split out cold code. Splitting is done late to avoid hiding context from
921 // other optimizations and inadvertently regressing performance. The tradeoff
922 // is that this has a higher code size cost than splitting early.
923 if (EnableHotColdSplit && !LTOPreLink)
924 MPM.addPass(HotColdSplittingPass());
925
Chandler Carrutha95ff382017-01-27 00:50:21 +0000926 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
927 // canonicalization pass that enables other optimizations. As a result,
928 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
929 // result too early.
930 OptimizePM.addPass(LoopSinkPass());
931
932 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000933 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000934
Sanjay Patel6fd43912017-09-09 13:38:18 +0000935 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
936 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
937 // flattening of blocks.
938 OptimizePM.addPass(DivRemPairsPass());
939
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000940 // LoopSink (and other loop passes since the last simplifyCFG) might have
941 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
942 OptimizePM.addPass(SimplifyCFGPass());
943
Chandler Carruthc34f7892017-11-28 11:32:31 +0000944 // Optimize PHIs by speculating around them when profitable. Note that this
945 // pass needs to be run after any PRE or similar pass as it is essentially
946 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
947 OptimizePM.addPass(SpeculateAroundPHIsPass());
948
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000949 for (auto &C : OptimizerLastEPCallbacks)
950 C(OptimizePM, Level);
951
Chandler Carrutha95ff382017-01-27 00:50:21 +0000952 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000953 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
954
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000955 MPM.addPass(CGProfilePass());
956
Chandler Carruthe3f50642016-12-22 06:59:15 +0000957 // Now we need to do some global optimization transforms.
958 // FIXME: It would seem like these should come first in the optimization
959 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
960 // ordering here.
961 MPM.addPass(GlobalDCEPass());
962 MPM.addPass(ConstantMergePass());
963
964 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000965}
966
Chandler Carruthe3f50642016-12-22 06:59:15 +0000967ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000968PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000969 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000970 assert(Level != O0 && "Must request optimizations for the default pipeline!");
971
972 ModulePassManager MPM(DebugLogging);
973
974 // Force any function attributes we want the rest of the pipeline to observe.
975 MPM.addPass(ForceFunctionAttrsPass());
976
David Blaikie0c64f5a2018-01-23 01:25:20 +0000977 // Apply module pipeline start EP callback.
978 for (auto &C : PipelineStartEPCallbacks)
979 C(MPM);
980
Dehao Chen08f88312017-08-07 20:23:20 +0000981 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000982 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
983
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000984 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000985 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
986 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000987
988 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000989 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000990
991 return MPM;
992}
993
994ModulePassManager
995PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
996 bool DebugLogging) {
997 assert(Level != O0 && "Must request optimizations for the default pipeline!");
998
999 ModulePassManager MPM(DebugLogging);
1000
1001 // Force any function attributes we want the rest of the pipeline to observe.
1002 MPM.addPass(ForceFunctionAttrsPass());
1003
Dehao Chen08f88312017-08-07 20:23:20 +00001004 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001005 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1006
David Blaikie0c64f5a2018-01-23 01:25:20 +00001007 // Apply module pipeline start EP callback.
1008 for (auto &C : PipelineStartEPCallbacks)
1009 C(MPM);
1010
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001011 // If we are planning to perform ThinLTO later, we don't bloat the code with
1012 // unrolling/vectorization/... now. Just simplify the module as much as we
1013 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001014 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1015 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001016
1017 // Run partial inlining pass to partially inline functions that have
1018 // large bodies.
1019 // FIXME: It isn't clear whether this is really the right place to run this
1020 // in ThinLTO. Because there is another canonicalization and simplification
1021 // phase that will run after the thin link, running this here ends up with
1022 // less information than will be available later and it may grow functions in
1023 // ways that aren't beneficial.
1024 if (RunPartialInlining)
1025 MPM.addPass(PartialInlinerPass());
1026
1027 // Reduce the size of the IR as much as possible.
1028 MPM.addPass(GlobalOptPass());
1029
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001030 return MPM;
1031}
1032
Teresa Johnson28023db2018-07-19 14:51:32 +00001033ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1034 OptimizationLevel Level, bool DebugLogging,
1035 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001036 ModulePassManager MPM(DebugLogging);
1037
Teresa Johnson28023db2018-07-19 14:51:32 +00001038 if (ImportSummary) {
1039 // These passes import type identifier resolutions for whole-program
1040 // devirtualization and CFI. They must run early because other passes may
1041 // disturb the specific instruction patterns that these passes look for,
1042 // creating dependencies on resolutions that may not appear in the summary.
1043 //
1044 // For example, GVN may transform the pattern assume(type.test) appearing in
1045 // two basic blocks into assume(phi(type.test, type.test)), which would
1046 // transform a dependency on a WPD resolution into a dependency on a type
1047 // identifier resolution for CFI.
1048 //
1049 // Also, WPD has access to more precise information than ICP and can
1050 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001051 //
1052 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1053 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001054 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1055 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1056 }
1057
Teresa Johnson867bc392019-04-23 18:56:19 +00001058 if (Level == O0)
1059 return MPM;
1060
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001061 // Force any function attributes we want the rest of the pipeline to observe.
1062 MPM.addPass(ForceFunctionAttrsPass());
1063
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001064 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001065 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1066 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001067
1068 // Now add the optimization pipeline.
1069 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1070
1071 return MPM;
1072}
1073
1074ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001075PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1076 bool DebugLogging) {
1077 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001078 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001079 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001080 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001081}
1082
Teresa Johnson28023db2018-07-19 14:51:32 +00001083ModulePassManager
1084PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1085 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001086 ModulePassManager MPM(DebugLogging);
1087
Teresa Johnson867bc392019-04-23 18:56:19 +00001088 if (Level == O0) {
1089 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1090 // metadata and intrinsics.
1091 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1092 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1093 return MPM;
1094 }
1095
Rong Xudb29a3a2019-03-04 20:21:27 +00001096 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001097 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001098 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001099 PGOOpt->ProfileRemappingFile,
1100 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001101 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1102 // RequireAnalysisPass for PSI before subsequent non-module passes.
1103 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001104 }
1105
Davide Italiano089a9122017-01-24 00:57:39 +00001106 // Remove unused virtual tables to improve the quality of code generated by
1107 // whole-program devirtualization and bitset lowering.
1108 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001109
Davide Italiano089a9122017-01-24 00:57:39 +00001110 // Force any function attributes we want the rest of the pipeline to observe.
1111 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001112
Davide Italiano089a9122017-01-24 00:57:39 +00001113 // Do basic inference of function attributes from known properties of system
1114 // libraries and other oracles.
1115 MPM.addPass(InferFunctionAttrsPass());
1116
1117 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001118 FunctionPassManager EarlyFPM(DebugLogging);
1119 EarlyFPM.addPass(CallSiteSplittingPass());
1120 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1121
Davide Italiano089a9122017-01-24 00:57:39 +00001122 // Indirect call promotion. This should promote all the targets that are
1123 // left by the earlier promotion pass that promotes intra-module targets.
1124 // This two-step promotion is to save the compile time. For LTO, it should
1125 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001126 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001127 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001128 // Propagate constants at call sites into the functions they call. This
1129 // opens opportunities for globalopt (and inlining) by substituting function
1130 // pointers passed as arguments to direct uses of functions.
1131 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001132
1133 // Attach metadata to indirect call sites indicating the set of functions
1134 // they may target at run-time. This should follow IPSCCP.
1135 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001136 }
1137
1138 // Now deduce any function attributes based in the current code.
1139 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1140 PostOrderFunctionAttrsPass()));
1141
1142 // Do RPO function attribute inference across the module to forward-propagate
1143 // attributes where applicable.
1144 // FIXME: Is this really an optimization rather than a canonicalization?
1145 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1146
Eric Christopher721eaef2019-02-26 20:33:22 +00001147 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001148 MPM.addPass(GlobalSplitPass());
1149
1150 // Run whole program optimization of virtual call when the list of callees
1151 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001152 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001153
1154 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001155 if (Level == 1) {
1156 // The LowerTypeTestsPass needs to run to lower type metadata and the
1157 // type.test intrinsics. The pass does nothing if CFI is disabled.
1158 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001159 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001160 }
Davide Italiano089a9122017-01-24 00:57:39 +00001161
1162 // Optimize globals to try and fold them into constants.
1163 MPM.addPass(GlobalOptPass());
1164
1165 // Promote any localized globals to SSA registers.
1166 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1167
1168 // Linking modules together can lead to duplicate global constant, only
1169 // keep one copy of each constant.
1170 MPM.addPass(ConstantMergePass());
1171
1172 // Remove unused arguments from functions.
1173 MPM.addPass(DeadArgumentEliminationPass());
1174
1175 // Reduce the code after globalopt and ipsccp. Both can open up significant
1176 // simplification opportunities, and both can propagate functions through
1177 // function pointers. When this happens, we often have to resolve varargs
1178 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001179 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001180 if (Level == O3)
1181 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001182 PeepholeFPM.addPass(InstCombinePass());
1183 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1184
1185 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001186
1187 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1188 // generally clean up exception handling overhead. It isn't clear this is
1189 // valuable as the inliner doesn't currently care whether it is inlining an
1190 // invoke or a call.
1191 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001192 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1193 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001194
1195 // Optimize globals again after we ran the inliner.
1196 MPM.addPass(GlobalOptPass());
1197
1198 // Garbage collect dead functions.
1199 // FIXME: Add ArgumentPromotion pass after once it's ported.
1200 MPM.addPass(GlobalDCEPass());
1201
1202 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001203 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001204 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001205 invokePeepholeEPCallbacks(FPM, Level);
1206
Davide Italiano089a9122017-01-24 00:57:39 +00001207 FPM.addPass(JumpThreadingPass());
1208
Rong Xudb29a3a2019-03-04 20:21:27 +00001209 // Do a post inline PGO instrumentation and use pass. This is a context
1210 // sensitive PGO pass.
1211 if (PGOOpt) {
1212 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1213 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1214 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1215 PGOOpt->ProfileRemappingFile);
1216 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1217 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1218 /* IsCS */ true, PGOOpt->ProfileFile,
1219 PGOOpt->ProfileRemappingFile);
1220 }
1221
Davide Italiano089a9122017-01-24 00:57:39 +00001222 // Break up allocas
1223 FPM.addPass(SROA());
1224
Robert Lougherf2158a82019-03-20 19:08:18 +00001225 // LTO provides additional opportunities for tailcall elimination due to
1226 // link-time inlining, and visibility of nocapture attribute.
1227 FPM.addPass(TailCallElimPass());
1228
Davide Italiano089a9122017-01-24 00:57:39 +00001229 // Run a few AA driver optimizations here and now to cleanup the code.
1230 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1231
1232 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1233 PostOrderFunctionAttrsPass()));
1234 // FIXME: here we run IP alias analysis in the legacy PM.
1235
1236 FunctionPassManager MainFPM;
1237
1238 // FIXME: once we fix LoopPass Manager, add LICM here.
1239 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001240 if (RunNewGVN)
1241 MainFPM.addPass(NewGVNPass());
1242 else
1243 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001244
1245 // Remove dead memcpy()'s.
1246 MainFPM.addPass(MemCpyOptPass());
1247
1248 // Nuke dead stores.
1249 MainFPM.addPass(DSEPass());
1250
1251 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001252 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001253 // loopVectorize. Enable them once the remaining issue with LPM
1254 // are sorted out.
1255
1256 MainFPM.addPass(InstCombinePass());
1257 MainFPM.addPass(SimplifyCFGPass());
1258 MainFPM.addPass(SCCPPass());
1259 MainFPM.addPass(InstCombinePass());
1260 MainFPM.addPass(BDCEPass());
1261
1262 // FIXME: We may want to run SLPVectorizer here.
1263 // After vectorization, assume intrinsics may tell us more
1264 // about pointer alignments.
1265#if 0
1266 MainFPM.add(AlignmentFromAssumptionsPass());
1267#endif
1268
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001269 // FIXME: Conditionally run LoadCombine here, after it's ported
1270 // (in case we still have this pass, given its questionable usefulness).
1271
Davide Italiano089a9122017-01-24 00:57:39 +00001272 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001273 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001274 MainFPM.addPass(JumpThreadingPass());
1275 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1276
1277 // Create a function that performs CFI checks for cross-DSO calls with
1278 // targets in the current module.
1279 MPM.addPass(CrossDSOCFIPass());
1280
1281 // Lower type metadata and the type.test intrinsic. This pass supports
1282 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1283 // to be run at link time if CFI is enabled. This pass does nothing if
1284 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001285 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001286
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001287 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1288 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1289 if (EnableHotColdSplit)
1290 MPM.addPass(HotColdSplittingPass());
1291
Davide Italiano089a9122017-01-24 00:57:39 +00001292 // Add late LTO optimization passes.
1293 // Delete basic blocks, which optimization passes may have killed.
1294 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1295
1296 // Drop bodies of available eternally objects to improve GlobalDCE.
1297 MPM.addPass(EliminateAvailableExternallyPass());
1298
1299 // Now that we have optimized the program, discard unreachable functions.
1300 MPM.addPass(GlobalDCEPass());
1301
Eric Christopher86e2f162019-05-03 00:15:23 +00001302 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001303 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001304}
1305
Chandler Carruth060ad612016-12-23 20:38:19 +00001306AAManager PassBuilder::buildDefaultAAPipeline() {
1307 AAManager AA;
1308
1309 // The order in which these are registered determines their priority when
1310 // being queried.
1311
1312 // First we register the basic alias analysis that provides the majority of
1313 // per-function local AA logic. This is a stateless, on-demand local set of
1314 // AA techniques.
1315 AA.registerFunctionAnalysis<BasicAA>();
1316
1317 // Next we query fast, specialized alias analyses that wrap IR-embedded
1318 // information about aliasing.
1319 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1320 AA.registerFunctionAnalysis<TypeBasedAA>();
1321
1322 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001323 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1324 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001325 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001326 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001327
1328 return AA;
1329}
1330
Chandler Carruth241bf242016-08-03 07:44:48 +00001331static Optional<int> parseRepeatPassName(StringRef Name) {
1332 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1333 return None;
1334 int Count;
1335 if (Name.getAsInteger(0, Count) || Count <= 0)
1336 return None;
1337 return Count;
1338}
1339
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001340static Optional<int> parseDevirtPassName(StringRef Name) {
1341 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1342 return None;
1343 int Count;
1344 if (Name.getAsInteger(0, Count) || Count <= 0)
1345 return None;
1346 return Count;
1347}
1348
Fedor Sergeevb7871402019-01-10 10:01:53 +00001349static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1350 if (!Name.consume_front(PassName))
1351 return false;
1352 // normal pass name w/o parameters == default parameters
1353 if (Name.empty())
1354 return true;
1355 return Name.startswith("<") && Name.endswith(">");
1356}
1357
1358namespace {
1359
1360/// This performs customized parsing of pass name with parameters.
1361///
1362/// We do not need parametrization of passes in textual pipeline very often,
1363/// yet on a rare occasion ability to specify parameters right there can be
1364/// useful.
1365///
1366/// \p Name - parameterized specification of a pass from a textual pipeline
1367/// is a string in a form of :
1368/// PassName '<' parameter-list '>'
1369///
1370/// Parameter list is being parsed by the parser callable argument, \p Parser,
1371/// It takes a string-ref of parameters and returns either StringError or a
1372/// parameter list in a form of a custom parameters type, all wrapped into
1373/// Expected<> template class.
1374///
1375template <typename ParametersParseCallableT>
1376auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1377 StringRef PassName) -> decltype(Parser(StringRef{})) {
1378 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1379
1380 StringRef Params = Name;
1381 if (!Params.consume_front(PassName)) {
1382 assert(false &&
1383 "unable to strip pass name from parametrized pass specification");
1384 }
1385 if (Params.empty())
1386 return ParametersT{};
1387 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1388 assert(false && "invalid format for parametrized pass name");
1389 }
1390
1391 Expected<ParametersT> Result = Parser(Params);
1392 assert((Result || Result.template errorIsA<StringError>()) &&
1393 "Pass parameter parser can only return StringErrors.");
1394 return std::move(Result);
1395}
1396
1397/// Parser of parameters for LoopUnroll pass.
1398Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1399 LoopUnrollOptions UnrollOpts;
1400 while (!Params.empty()) {
1401 StringRef ParamName;
1402 std::tie(ParamName, Params) = Params.split(';');
1403 int OptLevel = StringSwitch<int>(ParamName)
1404 .Case("O0", 0)
1405 .Case("O1", 1)
1406 .Case("O2", 2)
1407 .Case("O3", 3)
1408 .Default(-1);
1409 if (OptLevel >= 0) {
1410 UnrollOpts.setOptLevel(OptLevel);
1411 continue;
1412 }
1413
1414 bool Enable = !ParamName.consume_front("no-");
1415 if (ParamName == "partial") {
1416 UnrollOpts.setPartial(Enable);
1417 } else if (ParamName == "peeling") {
1418 UnrollOpts.setPeeling(Enable);
1419 } else if (ParamName == "runtime") {
1420 UnrollOpts.setRuntime(Enable);
1421 } else if (ParamName == "upperbound") {
1422 UnrollOpts.setUpperBound(Enable);
1423 } else {
1424 return make_error<StringError>(
1425 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1426 inconvertibleErrorCode());
1427 }
1428 }
1429 return UnrollOpts;
1430}
1431
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001432Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1433 MemorySanitizerOptions Result;
1434 while (!Params.empty()) {
1435 StringRef ParamName;
1436 std::tie(ParamName, Params) = Params.split(';');
1437
1438 if (ParamName == "recover") {
1439 Result.Recover = true;
1440 } else if (ParamName == "kernel") {
1441 Result.Kernel = true;
1442 } else if (ParamName.consume_front("track-origins=")) {
1443 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1444 return make_error<StringError>(
1445 formatv("invalid argument to MemorySanitizer pass track-origins "
1446 "parameter: '{0}' ",
1447 ParamName)
1448 .str(),
1449 inconvertibleErrorCode());
1450 } else {
1451 return make_error<StringError>(
1452 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1453 .str(),
1454 inconvertibleErrorCode());
1455 }
1456 }
1457 return Result;
1458}
1459
Serguei Katkovf5432832019-04-15 08:57:53 +00001460/// Parser of parameters for SimplifyCFG pass.
1461Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1462 SimplifyCFGOptions Result;
1463 while (!Params.empty()) {
1464 StringRef ParamName;
1465 std::tie(ParamName, Params) = Params.split(';');
1466
1467 bool Enable = !ParamName.consume_front("no-");
1468 if (ParamName == "forward-switch-cond") {
1469 Result.forwardSwitchCondToPhi(Enable);
1470 } else if (ParamName == "switch-to-lookup") {
1471 Result.convertSwitchToLookupTable(Enable);
1472 } else if (ParamName == "keep-loops") {
1473 Result.needCanonicalLoops(Enable);
1474 } else if (ParamName == "sink-common-insts") {
1475 Result.sinkCommonInsts(Enable);
1476 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1477 APInt BonusInstThreshold;
1478 if (ParamName.getAsInteger(0, BonusInstThreshold))
1479 return make_error<StringError>(
1480 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1481 "parameter: '{0}' ",
1482 ParamName).str(),
1483 inconvertibleErrorCode());
1484 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1485 } else {
1486 return make_error<StringError>(
1487 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1488 inconvertibleErrorCode());
1489 }
1490 }
1491 return Result;
1492}
1493
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001494/// Parser of parameters for LoopVectorize pass.
1495Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1496 LoopVectorizeOptions Opts;
1497 while (!Params.empty()) {
1498 StringRef ParamName;
1499 std::tie(ParamName, Params) = Params.split(';');
1500
1501 bool Enable = !ParamName.consume_front("no-");
1502 if (ParamName == "interleave-forced-only") {
1503 Opts.setInterleaveOnlyWhenForced(Enable);
1504 } else if (ParamName == "vectorize-forced-only") {
1505 Opts.setVectorizeOnlyWhenForced(Enable);
1506 } else {
1507 return make_error<StringError>(
1508 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1509 inconvertibleErrorCode());
1510 }
1511 }
1512 return Opts;
1513}
1514
Serguei Katkov40a3b962019-04-22 10:35:07 +00001515Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1516 bool Result = false;
1517 while (!Params.empty()) {
1518 StringRef ParamName;
1519 std::tie(ParamName, Params) = Params.split(';');
1520
1521 bool Enable = !ParamName.consume_front("no-");
1522 if (ParamName == "nontrivial") {
1523 Result = Enable;
1524 } else {
1525 return make_error<StringError>(
1526 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1527 .str(),
1528 inconvertibleErrorCode());
1529 }
1530 }
1531 return Result;
1532}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001533} // namespace
1534
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001535/// Tests whether a pass name starts with a valid prefix for a default pipeline
1536/// alias.
1537static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1538 return Name.startswith("default") || Name.startswith("thinlto") ||
1539 Name.startswith("lto");
1540}
1541
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001542/// Tests whether registered callbacks will accept a given pass name.
1543///
1544/// When parsing a pipeline text, the type of the outermost pipeline may be
1545/// omitted, in which case the type is automatically determined from the first
1546/// pass name in the text. This may be a name that is handled through one of the
1547/// callbacks. We check this through the oridinary parsing callbacks by setting
1548/// up a dummy PassManager in order to not force the client to also handle this
1549/// type of query.
1550template <typename PassManagerT, typename CallbacksT>
1551static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1552 if (!Callbacks.empty()) {
1553 PassManagerT DummyPM;
1554 for (auto &CB : Callbacks)
1555 if (CB(Name, DummyPM, {}))
1556 return true;
1557 }
1558 return false;
1559}
1560
1561template <typename CallbacksT>
1562static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001563 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001564 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001565 return DefaultAliasRegex.match(Name);
1566
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001567 // Explicitly handle pass manager names.
1568 if (Name == "module")
1569 return true;
1570 if (Name == "cgscc")
1571 return true;
1572 if (Name == "function")
1573 return true;
1574
Chandler Carruth241bf242016-08-03 07:44:48 +00001575 // Explicitly handle custom-parsed pass names.
1576 if (parseRepeatPassName(Name))
1577 return true;
1578
Chandler Carruth74a8a222016-06-17 07:15:29 +00001579#define MODULE_PASS(NAME, CREATE_PASS) \
1580 if (Name == NAME) \
1581 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001582#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001583 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001584 return true;
1585#include "PassRegistry.def"
1586
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001587 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001588}
1589
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001590template <typename CallbacksT>
1591static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001592 // Explicitly handle pass manager names.
1593 if (Name == "cgscc")
1594 return true;
1595 if (Name == "function")
1596 return true;
1597
Chandler Carruth241bf242016-08-03 07:44:48 +00001598 // Explicitly handle custom-parsed pass names.
1599 if (parseRepeatPassName(Name))
1600 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001601 if (parseDevirtPassName(Name))
1602 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001603
Chandler Carruth74a8a222016-06-17 07:15:29 +00001604#define CGSCC_PASS(NAME, CREATE_PASS) \
1605 if (Name == NAME) \
1606 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001607#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001608 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001609 return true;
1610#include "PassRegistry.def"
1611
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001612 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001613}
1614
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001615template <typename CallbacksT>
1616static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001617 // Explicitly handle pass manager names.
1618 if (Name == "function")
1619 return true;
1620 if (Name == "loop")
1621 return true;
1622
Chandler Carruth241bf242016-08-03 07:44:48 +00001623 // Explicitly handle custom-parsed pass names.
1624 if (parseRepeatPassName(Name))
1625 return true;
1626
Chandler Carruth74a8a222016-06-17 07:15:29 +00001627#define FUNCTION_PASS(NAME, CREATE_PASS) \
1628 if (Name == NAME) \
1629 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001630#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1631 if (checkParametrizedPassName(Name, NAME)) \
1632 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001633#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001634 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001635 return true;
1636#include "PassRegistry.def"
1637
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001638 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001639}
1640
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001641template <typename CallbacksT>
1642static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001643 // Explicitly handle pass manager names.
1644 if (Name == "loop")
1645 return true;
1646
Chandler Carruth241bf242016-08-03 07:44:48 +00001647 // Explicitly handle custom-parsed pass names.
1648 if (parseRepeatPassName(Name))
1649 return true;
1650
Chandler Carruth74a8a222016-06-17 07:15:29 +00001651#define LOOP_PASS(NAME, CREATE_PASS) \
1652 if (Name == NAME) \
1653 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001654#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1655 if (checkParametrizedPassName(Name, NAME)) \
1656 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001657#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1658 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1659 return true;
1660#include "PassRegistry.def"
1661
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001662 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001663}
1664
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001665Optional<std::vector<PassBuilder::PipelineElement>>
1666PassBuilder::parsePipelineText(StringRef Text) {
1667 std::vector<PipelineElement> ResultPipeline;
1668
1669 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1670 &ResultPipeline};
1671 for (;;) {
1672 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1673 size_t Pos = Text.find_first_of(",()");
1674 Pipeline.push_back({Text.substr(0, Pos), {}});
1675
1676 // If we have a single terminating name, we're done.
1677 if (Pos == Text.npos)
1678 break;
1679
1680 char Sep = Text[Pos];
1681 Text = Text.substr(Pos + 1);
1682 if (Sep == ',')
1683 // Just a name ending in a comma, continue.
1684 continue;
1685
1686 if (Sep == '(') {
1687 // Push the inner pipeline onto the stack to continue processing.
1688 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1689 continue;
1690 }
1691
1692 assert(Sep == ')' && "Bogus separator!");
1693 // When handling the close parenthesis, we greedily consume them to avoid
1694 // empty strings in the pipeline.
1695 do {
1696 // If we try to pop the outer pipeline we have unbalanced parentheses.
1697 if (PipelineStack.size() == 1)
1698 return None;
1699
1700 PipelineStack.pop_back();
1701 } while (Text.consume_front(")"));
1702
1703 // Check if we've finished parsing.
1704 if (Text.empty())
1705 break;
1706
1707 // Otherwise, the end of an inner pipeline always has to be followed by
1708 // a comma, and then we can continue.
1709 if (!Text.consume_front(","))
1710 return None;
1711 }
1712
1713 if (PipelineStack.size() > 1)
1714 // Unbalanced paretheses.
1715 return None;
1716
1717 assert(PipelineStack.back() == &ResultPipeline &&
1718 "Wrong pipeline at the bottom of the stack!");
1719 return {std::move(ResultPipeline)};
1720}
1721
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001722Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1723 const PipelineElement &E,
1724 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001725 auto &Name = E.Name;
1726 auto &InnerPipeline = E.InnerPipeline;
1727
1728 // First handle complex passes like the pass managers which carry pipelines.
1729 if (!InnerPipeline.empty()) {
1730 if (Name == "module") {
1731 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001732 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1733 VerifyEachPass, DebugLogging))
1734 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001735 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001736 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001737 }
1738 if (Name == "cgscc") {
1739 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001740 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1741 DebugLogging))
1742 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001743 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001744 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001745 }
1746 if (Name == "function") {
1747 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001748 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1749 VerifyEachPass, DebugLogging))
1750 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001751 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001752 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001753 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001754 if (auto Count = parseRepeatPassName(Name)) {
1755 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001756 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1757 VerifyEachPass, DebugLogging))
1758 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001759 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001760 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001761 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001762
1763 for (auto &C : ModulePipelineParsingCallbacks)
1764 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001765 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001766
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001767 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001768 return make_error<StringError>(
1769 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1770 inconvertibleErrorCode());
1771 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001772 }
1773
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001774 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001775 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001776 SmallVector<StringRef, 3> Matches;
1777 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001778 return make_error<StringError>(
1779 formatv("unknown default pipeline alias '{0}'", Name).str(),
1780 inconvertibleErrorCode());
1781
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001782 assert(Matches.size() == 3 && "Must capture two matched strings!");
1783
Jordan Rosef85a95f2016-07-25 18:34:51 +00001784 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001785 .Case("O0", O0)
1786 .Case("O1", O1)
1787 .Case("O2", O2)
1788 .Case("O3", O3)
1789 .Case("Os", Os)
1790 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001791 if (L == O0)
1792 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001793 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001794
1795 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001796 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001797 } else if (Matches[1] == "thinlto-pre-link") {
1798 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1799 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001800 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001801 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001802 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001803 } else {
1804 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001805 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001806 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001807 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001808 }
1809
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001810 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001811#define MODULE_PASS(NAME, CREATE_PASS) \
1812 if (Name == NAME) { \
1813 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001814 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001815 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001816#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1817 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001818 MPM.addPass( \
1819 RequireAnalysisPass< \
1820 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001821 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001822 } \
1823 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001824 MPM.addPass(InvalidateAnalysisPass< \
1825 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001826 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001827 }
1828#include "PassRegistry.def"
1829
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001830 for (auto &C : ModulePipelineParsingCallbacks)
1831 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001832 return Error::success();
1833 return make_error<StringError>(
1834 formatv("unknown module pass '{0}'", Name).str(),
1835 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001836}
1837
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001838Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1839 const PipelineElement &E, bool VerifyEachPass,
1840 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001841 auto &Name = E.Name;
1842 auto &InnerPipeline = E.InnerPipeline;
1843
1844 // First handle complex passes like the pass managers which carry pipelines.
1845 if (!InnerPipeline.empty()) {
1846 if (Name == "cgscc") {
1847 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001848 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1849 VerifyEachPass, DebugLogging))
1850 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001851 // Add the nested pass manager with the appropriate adaptor.
1852 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001853 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001854 }
1855 if (Name == "function") {
1856 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001857 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1858 VerifyEachPass, DebugLogging))
1859 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001860 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001861 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001862 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001863 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001864 if (auto Count = parseRepeatPassName(Name)) {
1865 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001866 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1867 VerifyEachPass, DebugLogging))
1868 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001869 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001870 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001871 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001872 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1873 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001874 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1875 VerifyEachPass, DebugLogging))
1876 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001877 CGPM.addPass(
1878 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001879 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001880 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001881
1882 for (auto &C : CGSCCPipelineParsingCallbacks)
1883 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001884 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001885
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001886 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001887 return make_error<StringError>(
1888 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1889 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001890 }
1891
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001892// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001893#define CGSCC_PASS(NAME, CREATE_PASS) \
1894 if (Name == NAME) { \
1895 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001896 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001897 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001898#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1899 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001900 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001901 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001902 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1903 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001904 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001905 } \
1906 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001907 CGPM.addPass(InvalidateAnalysisPass< \
1908 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001909 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001910 }
1911#include "PassRegistry.def"
1912
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001913 for (auto &C : CGSCCPipelineParsingCallbacks)
1914 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001915 return Error::success();
1916 return make_error<StringError>(
1917 formatv("unknown cgscc pass '{0}'", Name).str(),
1918 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001919}
1920
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001921Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1922 const PipelineElement &E,
1923 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001924 auto &Name = E.Name;
1925 auto &InnerPipeline = E.InnerPipeline;
1926
1927 // First handle complex passes like the pass managers which carry pipelines.
1928 if (!InnerPipeline.empty()) {
1929 if (Name == "function") {
1930 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001931 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1932 VerifyEachPass, DebugLogging))
1933 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001934 // Add the nested pass manager with the appropriate adaptor.
1935 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001936 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001937 }
1938 if (Name == "loop") {
1939 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001940 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1941 DebugLogging))
1942 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001943 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001944 FPM.addPass(
1945 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001946 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001947 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001948 if (auto Count = parseRepeatPassName(Name)) {
1949 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001950 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1951 VerifyEachPass, DebugLogging))
1952 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001953 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001954 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001955 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001956
1957 for (auto &C : FunctionPipelineParsingCallbacks)
1958 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001959 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001960
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001961 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001962 return make_error<StringError>(
1963 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1964 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001965 }
1966
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001967// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001968#define FUNCTION_PASS(NAME, CREATE_PASS) \
1969 if (Name == NAME) { \
1970 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001971 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001972 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001973#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1974 if (checkParametrizedPassName(Name, NAME)) { \
1975 auto Params = parsePassParameters(PARSER, Name, NAME); \
1976 if (!Params) \
1977 return Params.takeError(); \
1978 FPM.addPass(CREATE_PASS(Params.get())); \
1979 return Error::success(); \
1980 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001981#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1982 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001983 FPM.addPass( \
1984 RequireAnalysisPass< \
1985 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001986 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001987 } \
1988 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001989 FPM.addPass(InvalidateAnalysisPass< \
1990 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001991 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001992 }
1993#include "PassRegistry.def"
1994
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001995 for (auto &C : FunctionPipelineParsingCallbacks)
1996 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001997 return Error::success();
1998 return make_error<StringError>(
1999 formatv("unknown function pass '{0}'", Name).str(),
2000 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002001}
2002
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002003Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2004 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002005 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002006 auto &InnerPipeline = E.InnerPipeline;
2007
2008 // First handle complex passes like the pass managers which carry pipelines.
2009 if (!InnerPipeline.empty()) {
2010 if (Name == "loop") {
2011 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002012 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2013 VerifyEachPass, DebugLogging))
2014 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002015 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002016 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002017 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002018 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002019 if (auto Count = parseRepeatPassName(Name)) {
2020 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002021 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2022 VerifyEachPass, DebugLogging))
2023 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002024 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002025 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002026 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002027
2028 for (auto &C : LoopPipelineParsingCallbacks)
2029 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002030 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002031
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002032 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002033 return make_error<StringError>(
2034 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2035 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002036 }
2037
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002038// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002039#define LOOP_PASS(NAME, CREATE_PASS) \
2040 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002041 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002042 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002043 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002044#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2045 if (checkParametrizedPassName(Name, NAME)) { \
2046 auto Params = parsePassParameters(PARSER, Name, NAME); \
2047 if (!Params) \
2048 return Params.takeError(); \
2049 LPM.addPass(CREATE_PASS(Params.get())); \
2050 return Error::success(); \
2051 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002052#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2053 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002054 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002055 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2056 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2057 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002058 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002059 } \
2060 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002061 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002062 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002063 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002064 }
2065#include "PassRegistry.def"
2066
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002067 for (auto &C : LoopPipelineParsingCallbacks)
2068 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002069 return Error::success();
2070 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2071 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002072}
2073
Chandler Carruthedf59962016-02-18 09:45:17 +00002074bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002075#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2076 if (Name == NAME) { \
2077 AA.registerModuleAnalysis< \
2078 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2079 return true; \
2080 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002081#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2082 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002083 AA.registerFunctionAnalysis< \
2084 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002085 return true; \
2086 }
2087#include "PassRegistry.def"
2088
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002089 for (auto &C : AAParsingCallbacks)
2090 if (C(Name, AA))
2091 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002092 return false;
2093}
2094
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002095Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002096 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002097 bool VerifyEachPass,
2098 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002099 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002100 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2101 return Err;
2102 // FIXME: No verifier support for Loop passes!
2103 }
2104 return Error::success();
2105}
2106
2107Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2108 ArrayRef<PipelineElement> Pipeline,
2109 bool VerifyEachPass,
2110 bool DebugLogging) {
2111 for (const auto &Element : Pipeline) {
2112 if (auto Err =
2113 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2114 return Err;
2115 if (VerifyEachPass)
2116 FPM.addPass(VerifierPass());
2117 }
2118 return Error::success();
2119}
2120
2121Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2122 ArrayRef<PipelineElement> Pipeline,
2123 bool VerifyEachPass,
2124 bool DebugLogging) {
2125 for (const auto &Element : Pipeline) {
2126 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2127 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002128 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002129 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002130 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002131}
2132
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002133void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2134 FunctionAnalysisManager &FAM,
2135 CGSCCAnalysisManager &CGAM,
2136 ModuleAnalysisManager &MAM) {
2137 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2138 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002139 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2140 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2141 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2142 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2143 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2144}
2145
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002146Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2147 ArrayRef<PipelineElement> Pipeline,
2148 bool VerifyEachPass,
2149 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002150 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002151 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2152 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002153 if (VerifyEachPass)
2154 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002155 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002156 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002157}
2158
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002159// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002160// FIXME: Should this routine accept a TargetMachine or require the caller to
2161// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002162Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2163 StringRef PipelineText,
2164 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002165 auto Pipeline = parsePipelineText(PipelineText);
2166 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002167 return make_error<StringError>(
2168 formatv("invalid pipeline '{0}'", PipelineText).str(),
2169 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002170
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002171 // If the first name isn't at the module layer, wrap the pipeline up
2172 // automatically.
2173 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002174
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002175 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2176 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002177 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002178 } else if (isFunctionPassName(FirstName,
2179 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002180 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002181 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002182 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002183 } else {
2184 for (auto &C : TopLevelPipelineParsingCallbacks)
2185 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002186 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002187
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002188 // Unknown pass or pipeline name!
2189 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2190 return make_error<StringError>(
2191 formatv("unknown {0} name '{1}'",
2192 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2193 .str(),
2194 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002195 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002196 }
2197
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002198 if (auto Err =
2199 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2200 return Err;
2201 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002202}
Chandler Carruthedf59962016-02-18 09:45:17 +00002203
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002204// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002205Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2206 StringRef PipelineText,
2207 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002208 auto Pipeline = parsePipelineText(PipelineText);
2209 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002210 return make_error<StringError>(
2211 formatv("invalid pipeline '{0}'", PipelineText).str(),
2212 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002213
2214 StringRef FirstName = Pipeline->front().Name;
2215 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002216 return make_error<StringError>(
2217 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2218 PipelineText)
2219 .str(),
2220 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002221
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002222 if (auto Err =
2223 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2224 return Err;
2225 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002226}
2227
2228// Primary pass pipeline description parsing routine for a \c
2229// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002230Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2231 StringRef PipelineText,
2232 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002233 auto Pipeline = parsePipelineText(PipelineText);
2234 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002235 return make_error<StringError>(
2236 formatv("invalid pipeline '{0}'", PipelineText).str(),
2237 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002238
2239 StringRef FirstName = Pipeline->front().Name;
2240 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002241 return make_error<StringError>(
2242 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2243 PipelineText)
2244 .str(),
2245 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002246
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002247 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2248 DebugLogging))
2249 return Err;
2250 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002251}
2252
2253// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002254Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2255 StringRef PipelineText,
2256 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002257 auto Pipeline = parsePipelineText(PipelineText);
2258 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002259 return make_error<StringError>(
2260 formatv("invalid pipeline '{0}'", PipelineText).str(),
2261 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002262
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002263 if (auto Err =
2264 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2265 return Err;
2266
2267 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002268}
2269
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002270Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002271 // If the pipeline just consists of the word 'default' just replace the AA
2272 // manager with our default one.
2273 if (PipelineText == "default") {
2274 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002275 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002276 }
2277
Chandler Carruthedf59962016-02-18 09:45:17 +00002278 while (!PipelineText.empty()) {
2279 StringRef Name;
2280 std::tie(Name, PipelineText) = PipelineText.split(',');
2281 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002282 return make_error<StringError>(
2283 formatv("unknown alias analysis name '{0}'", Name).str(),
2284 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002285 }
2286
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002287 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002288}