blob: 2da923086b2054ee8ac21f202e5e9a7d41648ea5 [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"
Johannes Doerfertaade7822019-06-05 03:02:24 +000068#include "llvm/Transforms/IPO/Attributor.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000069#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000070#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000071#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000072#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000073#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000074#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000075#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000076#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000077#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000078#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000079#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000080#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000081#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000082#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000083#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000084#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000085#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000086#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000087#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000088#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000089#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000090#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000091#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000092#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000093#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000094#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000095#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000096#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000097#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Leonard Chan0cdd3b12019-05-14 21:17:21 +000098#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Manman Ren18295122019-02-28 20:13:38 +000099#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000100#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +0000101#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000102#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000103#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000104#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000105#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000106#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000107#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000108#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000109#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000110#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000111#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000112#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000113#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000114#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000115#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000116#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000117#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000118#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000119#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000120#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000121#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000122#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000123#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000124#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000125#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000126#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000127#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000128#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000129#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000130#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000131#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000132#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000133#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000134#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000135#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000136#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000137#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000138#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000139#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000140#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000141#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000142#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000143#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000144#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000145#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Clement Courbet43882b12019-05-23 12:35:26 +0000146#include "llvm/Transforms/Scalar/MergeICmps.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000147#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000148#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000149#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000150#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000151#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000152#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000153#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000154#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000155#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000156#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000157#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000158#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000159#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000160#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000161#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000162#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000163#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000164#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000165#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000166#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000167#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000168#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000169#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000170#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000171#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000172#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000173#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000174#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000175#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000176
Chandler Carruth66445382014-01-11 08:16:35 +0000177using namespace llvm;
178
Chandler Carruth719ffe12017-02-12 05:38:04 +0000179static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
180 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000181static cl::opt<bool>
182 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
183 cl::Hidden, cl::ZeroOrMore,
184 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000185
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000186static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000187 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000188 cl::Hidden, cl::ZeroOrMore,
189 cl::desc("Run NewGVN instead of GVN"));
190
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000191static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000192 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
193 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000194
Davide Italianobe1b6a92017-06-03 23:18:29 +0000195static cl::opt<bool> EnableGVNSink(
196 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
197 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
198
David Green963401d2018-07-01 12:47:30 +0000199static cl::opt<bool> EnableUnrollAndJam(
200 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
201 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
202
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000203static cl::opt<bool> EnableSyntheticCounts(
204 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
205 cl::desc("Run synthetic function entry count generation "
206 "pass"));
207
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000208static Regex DefaultAliasRegex(
209 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000210
Eric Christophereff3b6f2019-04-18 06:17:40 +0000211// This option is used in simplifying testing SampleFDO optimizations for
212// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000213static cl::opt<bool>
214 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
215 cl::desc("Enable control height reduction optimization (CHR)"));
216
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000217PipelineTuningOptions::PipelineTuningOptions() {
218 LoopInterleaving = EnableLoopInterleaving;
219 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea458c7332019-05-08 17:58:35 +0000220 SLPVectorization = RunSLPVectorization;
Alina Sbirleae4b27862019-05-23 19:35:40 +0000221 LoopUnrolling = true;
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000222 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000223 LicmMssaOptCap = SetLicmMssaOptCap;
224 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000225}
226
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000227extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000228extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000229
Wei Mi3bcccdf2019-01-17 20:48:34 +0000230extern cl::opt<bool> FlattenedProfileUsed;
231
Chandler Carruthe3f50642016-12-22 06:59:15 +0000232static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
233 switch (Level) {
234 case PassBuilder::O0:
235 case PassBuilder::O1:
236 case PassBuilder::O2:
237 case PassBuilder::O3:
238 return false;
239
240 case PassBuilder::Os:
241 case PassBuilder::Oz:
242 return true;
243 }
244 llvm_unreachable("Invalid optimization level!");
245}
246
Chandler Carruth66445382014-01-11 08:16:35 +0000247namespace {
248
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000249/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000250struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000251 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000252 return PreservedAnalyses::all();
253 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000254 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000255};
256
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000257/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000258class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
259 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000260 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000261
262public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000263 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000264 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000265 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000266};
267
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000268/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000269struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000270 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
271 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000272 return PreservedAnalyses::all();
273 }
274 static StringRef name() { return "NoOpCGSCCPass"; }
275};
276
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000277/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000278class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
279 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000280 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000281
282public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000283 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000284 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000285 return Result();
286 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000287 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000288};
289
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000290/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000291struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000292 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000293 return PreservedAnalyses::all();
294 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000295 static StringRef name() { return "NoOpFunctionPass"; }
296};
297
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000298/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000299class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
300 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000301 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000302
303public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000304 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000305 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000306 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000307};
308
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000309/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000310struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000311 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
312 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000313 return PreservedAnalyses::all();
314 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000315 static StringRef name() { return "NoOpLoopPass"; }
316};
317
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000318/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000319class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
320 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000321 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000322
323public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000324 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000325 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
326 return Result();
327 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000328 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000329};
330
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000331AnalysisKey NoOpModuleAnalysis::Key;
332AnalysisKey NoOpCGSCCAnalysis::Key;
333AnalysisKey NoOpFunctionAnalysis::Key;
334AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000335
Chandler Carruth66445382014-01-11 08:16:35 +0000336} // End anonymous namespace.
337
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000338void PassBuilder::invokePeepholeEPCallbacks(
339 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
340 for (auto &C : PeepholeEPCallbacks)
341 C(FPM, Level);
342}
343
Chandler Carruth1ff77242015-03-07 09:02:36 +0000344void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000345#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000346 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000347#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000348
349 for (auto &C : ModuleAnalysisRegistrationCallbacks)
350 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000351}
352
Chandler Carruth1ff77242015-03-07 09:02:36 +0000353void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000354#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000355 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000356#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000357
358 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
359 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000360}
361
Chandler Carruth1ff77242015-03-07 09:02:36 +0000362void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000363#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000364 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000365#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000366
367 for (auto &C : FunctionAnalysisRegistrationCallbacks)
368 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000369}
370
Justin Bognereecc3c82016-02-25 07:23:08 +0000371void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000372#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000373 LAM.registerPass([&] { return CREATE_PASS; });
374#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000375
376 for (auto &C : LoopAnalysisRegistrationCallbacks)
377 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000378}
379
Chandler Carruthe3f50642016-12-22 06:59:15 +0000380FunctionPassManager
381PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000382 ThinLTOPhase Phase,
383 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000384 assert(Level != O0 && "Must request optimizations!");
385 FunctionPassManager FPM(DebugLogging);
386
387 // Form SSA out of local memory accesses after breaking apart aggregates into
388 // scalars.
389 FPM.addPass(SROA());
390
391 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000392 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000393
Davide Italianoc3688312017-06-01 23:08:14 +0000394 // Hoisting of scalars and load expressions.
395 if (EnableGVNHoist)
396 FPM.addPass(GVNHoistPass());
397
Davide Italianobe1b6a92017-06-03 23:18:29 +0000398 // Global value numbering based sinking.
399 if (EnableGVNSink) {
400 FPM.addPass(GVNSinkPass());
401 FPM.addPass(SimplifyCFGPass());
402 }
403
Chandler Carruthe3f50642016-12-22 06:59:15 +0000404 // Speculative execution if the target has divergent branches; otherwise nop.
405 FPM.addPass(SpeculativeExecutionPass());
406
407 // Optimize based on known information about branches, and cleanup afterward.
408 FPM.addPass(JumpThreadingPass());
409 FPM.addPass(CorrelatedValuePropagationPass());
410 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000411 if (Level == O3)
412 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000413 FPM.addPass(InstCombinePass());
414
415 if (!isOptimizingForSize(Level))
416 FPM.addPass(LibCallsShrinkWrapPass());
417
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000418 invokePeepholeEPCallbacks(FPM, Level);
419
Rong Xue1f42452017-10-23 22:21:29 +0000420 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
421 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000422 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000423 !isOptimizingForSize(Level))
424 FPM.addPass(PGOMemOPSizeOpt());
425
Chandler Carruthe3f50642016-12-22 06:59:15 +0000426 FPM.addPass(TailCallElimPass());
427 FPM.addPass(SimplifyCFGPass());
428
429 // Form canonically associated expression trees, and simplify the trees using
430 // basic mathematical properties. For example, this will form (nearly)
431 // minimal multiplication trees.
432 FPM.addPass(ReassociatePass());
433
434 // Add the primary loop simplification pipeline.
435 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000436 // some function passes in between them. These can and should be removed
437 // and/or replaced by scheduling the loop pass equivalents in the correct
438 // positions. But those equivalent passes aren't powerful enough yet.
439 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
440 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
441 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
442 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000443 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
444
Chandler Carruth71fd2702018-05-30 02:46:45 +0000445 // Simplify the loop body. We do this initially to clean up after other loop
446 // passes run, either when iterating on a loop or on inner loops with
447 // implications on the outer loop.
448 LPM1.addPass(LoopInstSimplifyPass());
449 LPM1.addPass(LoopSimplifyCFGPass());
450
Chandler Carruthe3f50642016-12-22 06:59:15 +0000451 // Rotate Loop - disable header duplication at -Oz
452 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000453 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000454 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000455 LPM2.addPass(IndVarSimplifyPass());
456 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000457
458 for (auto &C : LateLoopOptimizationsEPCallbacks)
459 C(LPM2, Level);
460
Chandler Carruth79b733b2017-01-26 23:21:17 +0000461 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000462 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000463 // because it changes IR to makes profile annotation in back compile
464 // inaccurate.
Alina Sbirleae4b27862019-05-23 19:35:40 +0000465 if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
466 PGOOpt->Action != PGOOptions::SampleUse) &&
467 PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000468 LPM2.addPass(
469 LoopFullUnrollPass(Level, false, PTO.ForgetAllSCEVInLoopUnroll));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000470
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000471 for (auto &C : LoopOptimizerEndEPCallbacks)
472 C(LPM2, Level);
473
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000474 // We provide the opt remark emitter pass for LICM to use. We only need to do
475 // this once as it is immutable.
476 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000477 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000478 FPM.addPass(SimplifyCFGPass());
479 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000480 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000481
482 // Eliminate redundancies.
483 if (Level != O1) {
484 // These passes add substantial compile time so skip them at O1.
485 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000486 if (RunNewGVN)
487 FPM.addPass(NewGVNPass());
488 else
489 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000490 }
491
492 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
493 FPM.addPass(MemCpyOptPass());
494
495 // Sparse conditional constant propagation.
496 // FIXME: It isn't clear why we do this *after* loop passes rather than
497 // before...
498 FPM.addPass(SCCPPass());
499
500 // Delete dead bit computations (instcombine runs after to fold away the dead
501 // computations, and then ADCE will run later to exploit any new DCE
502 // opportunities that creates).
503 FPM.addPass(BDCEPass());
504
505 // Run instcombine after redundancy and dead bit elimination to exploit
506 // opportunities opened up by them.
507 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000508 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000509
510 // Re-consider control flow based optimizations after redundancy elimination,
511 // redo DCE, etc.
512 FPM.addPass(JumpThreadingPass());
513 FPM.addPass(CorrelatedValuePropagationPass());
514 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000515 FPM.addPass(createFunctionToLoopPassAdaptor(
516 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
517 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000518
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000519 for (auto &C : ScalarOptimizerLateEPCallbacks)
520 C(FPM, Level);
521
Chandler Carruthe3f50642016-12-22 06:59:15 +0000522 // Finally, do an expensive DCE pass to catch all the dead code exposed by
523 // the simplifications and basic cleanup after all the simplifications.
524 FPM.addPass(ADCEPass());
525 FPM.addPass(SimplifyCFGPass());
526 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000527 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000528
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000529 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000530 (PGOOpt->Action == PGOOptions::IRUse ||
531 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000532 FPM.addPass(ControlHeightReductionPass());
533
Chandler Carruthe3f50642016-12-22 06:59:15 +0000534 return FPM;
535}
536
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000537void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
538 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000539 bool RunProfileGen, bool IsCS,
540 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000541 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000542 // Generally running simplification passes and the inliner with an high
543 // threshold results in smaller executables, but there may be cases where
544 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000545 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
546 // IsCS is true).
547 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000548 InlineParams IP;
549
550 // In the old pass manager, this is a cl::opt. Should still this be one?
551 IP.DefaultThreshold = 75;
552
553 // FIXME: The hint threshold has the same value used by the regular inliner.
554 // This should probably be lowered after performance testing.
555 // FIXME: this comment is cargo culted from the old pass manager, revisit).
556 IP.HintThreshold = 325;
557
558 CGSCCPassManager CGPipeline(DebugLogging);
559
560 CGPipeline.addPass(InlinerPass(IP));
561
562 FunctionPassManager FPM;
563 FPM.addPass(SROA());
564 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
565 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
566 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000567 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000568
Davide Italiano513dfaa2017-02-13 15:26:22 +0000569 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
570
571 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
572 }
573
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000574 // Delete anything that is now dead to make sure that we don't instrument
575 // dead code. Instrumentation can end up keeping dead code around and
576 // dramatically increase code size.
577 MPM.addPass(GlobalDCEPass());
578
Davide Italiano513dfaa2017-02-13 15:26:22 +0000579 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000580 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000581
Xinliang David Lib67530e2017-06-25 00:26:43 +0000582 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000583 FPM.addPass(
584 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000585 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
586
Davide Italiano513dfaa2017-02-13 15:26:22 +0000587 // Add the profile lowering pass.
588 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000589 if (!ProfileFile.empty())
590 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000591 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000592 Options.UseBFIInPromotion = IsCS;
593 MPM.addPass(InstrProfiling(Options, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000594 } else if (!ProfileFile.empty()) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000595 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000596 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
597 // RequireAnalysisPass for PSI before subsequent non-module passes.
598 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
599 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000600}
601
Easwaran Raman8249fac2017-06-28 13:33:49 +0000602static InlineParams
603getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
604 auto O3 = PassBuilder::O3;
605 unsigned OptLevel = Level > O3 ? 2 : Level;
606 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
607 return getInlineParams(OptLevel, SizeLevel);
608}
609
Chandler Carruthe3f50642016-12-22 06:59:15 +0000610ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000611PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000612 ThinLTOPhase Phase,
613 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000614 ModulePassManager MPM(DebugLogging);
615
Rong Xudb29a3a2019-03-04 20:21:27 +0000616 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000617
618 // In ThinLTO mode, when flattened profile is used, all the available
619 // profile information will be annotated in PreLink phase so there is
620 // no need to load the profile again in PostLink.
621 bool LoadSampleProfile =
622 HasSampleProfile &&
623 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
624
625 // During the ThinLTO backend phase we perform early indirect call promotion
626 // here, before globalopt. Otherwise imported available_externally functions
627 // look unreferenced and are removed. If we are going to load the sample
628 // profile then defer until later.
629 // TODO: See if we can move later and consolidate with the location where
630 // we perform ICP when we are loading a sample profile.
631 // TODO: We pass HasSampleProfile (whether there was a sample profile file
632 // passed to the compile) to the SamplePGO flag of ICP. This is used to
633 // determine whether the new direct calls are annotated with prof metadata.
634 // Ideally this should be determined from whether the IR is annotated with
635 // sample profile, and not whether the a sample profile was provided on the
636 // command line. E.g. for flattened profiles where we will not be reloading
637 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
638 // provide the sample profile file.
639 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
640 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
641
Chandler Carruthe3f50642016-12-22 06:59:15 +0000642 // Do basic inference of function attributes from known properties of system
643 // libraries and other oracles.
644 MPM.addPass(InferFunctionAttrsPass());
645
646 // Create an early function pass manager to cleanup the output of the
647 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000648 FunctionPassManager EarlyFPM(DebugLogging);
649 EarlyFPM.addPass(SimplifyCFGPass());
650 EarlyFPM.addPass(SROA());
651 EarlyFPM.addPass(EarlyCSEPass());
652 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000653 if (Level == O3)
654 EarlyFPM.addPass(CallSiteSplittingPass());
655
Dehao Chen08f88312017-08-07 20:23:20 +0000656 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
657 // to convert bitcast to direct calls so that they can be inlined during the
658 // profile annotation prepration step.
659 // More details about SamplePGO design can be found in:
660 // https://research.google.com/pubs/pub45290.html
661 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000662 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000663 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000664 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000665
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000666 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000667 // Annotate sample profile right after early FPM to ensure freshness of
668 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000669 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000670 PGOOpt->ProfileRemappingFile,
671 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000672 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
673 // RequireAnalysisPass for PSI before subsequent non-module passes.
674 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000675 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
676 // for the profile annotation to be accurate in the ThinLTO backend.
677 if (Phase != ThinLTOPhase::PreLink)
678 // We perform early indirect call promotion here, before globalopt.
679 // This is important for the ThinLTO backend phase because otherwise
680 // imported available_externally functions look unreferenced and are
681 // removed.
682 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000683 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000684 }
685
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000686 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000687 // and prior to optimizing globals.
688 // FIXME: This position in the pipeline hasn't been carefully considered in
689 // years, it should be re-analyzed.
690 MPM.addPass(IPSCCPPass());
691
Matthew Simpsoncb585582017-10-25 13:40:08 +0000692 // Attach metadata to indirect call sites indicating the set of functions
693 // they may target at run-time. This should follow IPSCCP.
694 MPM.addPass(CalledValuePropagationPass());
695
Chandler Carruthe3f50642016-12-22 06:59:15 +0000696 // Optimize globals to try and fold them into constants.
697 MPM.addPass(GlobalOptPass());
698
699 // Promote any localized globals to SSA registers.
700 // FIXME: Should this instead by a run of SROA?
701 // FIXME: We should probably run instcombine and simplify-cfg afterward to
702 // delete control flows that are dead once globals have been folded to
703 // constants.
704 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
705
706 // Remove any dead arguments exposed by cleanups and constand folding
707 // globals.
708 MPM.addPass(DeadArgumentEliminationPass());
709
710 // Create a small function pass pipeline to cleanup after all the global
711 // optimizations.
712 FunctionPassManager GlobalCleanupPM(DebugLogging);
713 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000714 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
715
Chandler Carruthe3f50642016-12-22 06:59:15 +0000716 GlobalCleanupPM.addPass(SimplifyCFGPass());
717 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
718
Dehao Chen89d32262017-08-02 01:28:31 +0000719 // Add all the requested passes for instrumentation PGO, if requested.
720 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000721 (PGOOpt->Action == PGOOptions::IRInstr ||
722 PGOOpt->Action == PGOOptions::IRUse)) {
723 addPGOInstrPasses(MPM, DebugLogging, Level,
724 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
725 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000726 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000727 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000728 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000729 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
730 PGOOpt->CSAction == PGOOptions::CSIRInstr)
731 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000732
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000733 // Synthesize function entry counts for non-PGO compilation.
734 if (EnableSyntheticCounts && !PGOOpt)
735 MPM.addPass(SyntheticCountsPropagation());
736
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000737 // Require the GlobalsAA analysis for the module so we can query it within
738 // the CGSCC pipeline.
739 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000740
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000741 // Require the ProfileSummaryAnalysis for the module so we can query it within
742 // the inliner pass.
743 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
744
Chandler Carruthe3f50642016-12-22 06:59:15 +0000745 // Now begin the main postorder CGSCC pipeline.
746 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
747 // manager and trying to emulate its precise behavior. Much of this doesn't
748 // make a lot of sense and we should revisit the core CGSCC structure.
749 CGSCCPassManager MainCGPipeline(DebugLogging);
750
751 // Note: historically, the PruneEH pass was run first to deduce nounwind and
752 // generally clean up exception handling overhead. It isn't clear this is
753 // valuable as the inliner doesn't currently care whether it is inlining an
754 // invoke or a call.
755
756 // Run the inliner first. The theory is that we are walking bottom-up and so
757 // the callees have already been fully optimized, and we want to inline them
758 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000759 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000760 // because it makes profile annotation in the backend inaccurate.
761 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000762 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
763 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000764 IP.HotCallSiteThreshold = 0;
765 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000766
767 // Now deduce any function attributes based in the current code.
768 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
769
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000770 // When at O3 add argument promotion to the pass pipeline.
771 // FIXME: It isn't at all clear why this should be limited to O3.
772 if (Level == O3)
773 MainCGPipeline.addPass(ArgumentPromotionPass());
774
Chandler Carruthe3f50642016-12-22 06:59:15 +0000775 // Lastly, add the core function simplification pipeline nested inside the
776 // CGSCC walk.
777 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000778 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000779
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000780 for (auto &C : CGSCCOptimizerLateEPCallbacks)
781 C(MainCGPipeline, Level);
782
Chandler Carruth719ffe12017-02-12 05:38:04 +0000783 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
784 // to detect when we devirtualize indirect calls and iterate the SCC passes
785 // in that case to try and catch knock-on inlining or function attrs
786 // opportunities. Then we add it to the module pipeline by walking the SCCs
787 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000788 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000789 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000790 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000791
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000792 return MPM;
793}
794
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000795ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
796 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000797 ModulePassManager MPM(DebugLogging);
798
799 // Optimize globals now that the module is fully simplified.
800 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000801 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000802
Xinliang David Li126157c2017-05-22 16:41:57 +0000803 // Run partial inlining pass to partially inline functions that have
804 // large bodies.
805 if (RunPartialInlining)
806 MPM.addPass(PartialInlinerPass());
807
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000808 // Remove avail extern fns and globals definitions since we aren't compiling
809 // an object file for later LTO. For LTO we want to preserve these so they
810 // are eligible for inlining at link-time. Note if they are unreferenced they
811 // will be removed by GlobalDCE later, so this only impacts referenced
812 // available externally globals. Eventually they will be suppressed during
813 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
814 // may make globals referenced by available external functions dead and saves
815 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000816 MPM.addPass(EliminateAvailableExternallyPass());
817
Manman Ren18295122019-02-28 20:13:38 +0000818 if (EnableOrderFileInstrumentation)
819 MPM.addPass(InstrOrderFilePass());
820
Chandler Carruthe3f50642016-12-22 06:59:15 +0000821 // Do RPO function attribute inference across the module to forward-propagate
822 // attributes where applicable.
823 // FIXME: Is this really an optimization rather than a canonicalization?
824 MPM.addPass(ReversePostOrderFunctionAttrsPass());
825
Rong Xudb29a3a2019-03-04 20:21:27 +0000826 // Do a post inline PGO instrumentation and use pass. This is a context
827 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
828 // cross-module inline has not been done yet. The context sensitive
829 // instrumentation is after all the inlines are done.
830 if (!LTOPreLink && PGOOpt) {
831 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
832 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
833 /* IsCS */ true, PGOOpt->CSProfileGenFile,
834 PGOOpt->ProfileRemappingFile);
835 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
836 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
837 /* IsCS */ true, PGOOpt->ProfileFile,
838 PGOOpt->ProfileRemappingFile);
839 }
840
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000841 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000842 // useful as the above will have inlined, DCE'ed, and function-attr
843 // propagated everything. We should at this point have a reasonably minimal
844 // and richly annotated call graph. By computing aliasing and mod/ref
845 // information for all local globals here, the late loop passes and notably
846 // the vectorizer will be able to use them to help recognize vectorizable
847 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000848 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000849
850 FunctionPassManager OptimizePM(DebugLogging);
851 OptimizePM.addPass(Float2IntPass());
852 // FIXME: We need to run some loop optimizations to re-rotate loops after
853 // simplify-cfg and others undo their rotation.
854
855 // Optimize the loop execution. These passes operate on entire loop nests
856 // rather than on each loop in an inside-out manner, and so they are actually
857 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000858
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000859 for (auto &C : VectorizerStartEPCallbacks)
860 C(OptimizePM, Level);
861
Chandler Carrutha95ff382017-01-27 00:50:21 +0000862 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000863 OptimizePM.addPass(
864 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000865
866 // Distribute loops to allow partial vectorization. I.e. isolate dependences
867 // into separate loop that would otherwise inhibit vectorization. This is
868 // currently only performed for loops marked with the metadata
869 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000870 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000871
872 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000873 OptimizePM.addPass(LoopVectorizePass(
874 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000875
Chandler Carruthbaabda92017-01-27 01:32:26 +0000876 // Eliminate loads by forwarding stores from the previous iteration to loads
877 // of the current iteration.
878 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000879
880 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000881 OptimizePM.addPass(InstCombinePass());
882
Chandler Carrutha95ff382017-01-27 00:50:21 +0000883 // Now that we've formed fast to execute loop structures, we do further
884 // optimizations. These are run afterward as they might block doing complex
885 // analyses and transforms such as what are needed for loop vectorization.
886
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000887 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
888 // GVN, loop transforms, and others have already run, so it's now better to
889 // convert to more optimized IR using more aggressive simplify CFG options.
890 // The extra sinking transform can create larger basic blocks, so do this
891 // before SLP vectorization.
892 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
893 forwardSwitchCondToPhi(true).
894 convertSwitchToLookupTable(true).
895 needCanonicalLoops(false).
896 sinkCommonInsts(true)));
897
Chandler Carruthe3f50642016-12-22 06:59:15 +0000898 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000899 if (PTO.SLPVectorization)
900 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000901
Chandler Carruthe3f50642016-12-22 06:59:15 +0000902 OptimizePM.addPass(InstCombinePass());
903
904 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000905 // execution resources of an out-of-order processor. We also then need to
906 // clean up redundancies and loop invariant code.
907 // FIXME: It would be really good to use a loop-integrated instruction
908 // combiner for cleanup here so that the unrolling and LICM can be pipelined
909 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000910 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
911 if (EnableUnrollAndJam) {
912 OptimizePM.addPass(
913 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
914 }
Alina Sbirleae4b27862019-05-23 19:35:40 +0000915 if (PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000916 OptimizePM.addPass(LoopUnrollPass(
917 LoopUnrollOptions(Level, false, PTO.ForgetAllSCEVInLoopUnroll)));
Michael Kruse72448522018-12-12 17:32:52 +0000918 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000919 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000920 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000921 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
922 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
923 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000924
925 // Now that we've vectorized and unrolled loops, we may have more refined
926 // alignment information, try to re-derive it here.
927 OptimizePM.addPass(AlignmentFromAssumptionsPass());
928
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000929 // Split out cold code. Splitting is done late to avoid hiding context from
930 // other optimizations and inadvertently regressing performance. The tradeoff
931 // is that this has a higher code size cost than splitting early.
932 if (EnableHotColdSplit && !LTOPreLink)
933 MPM.addPass(HotColdSplittingPass());
934
Chandler Carrutha95ff382017-01-27 00:50:21 +0000935 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
936 // canonicalization pass that enables other optimizations. As a result,
937 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
938 // result too early.
939 OptimizePM.addPass(LoopSinkPass());
940
941 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000942 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000943
Sanjay Patel6fd43912017-09-09 13:38:18 +0000944 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
945 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
946 // flattening of blocks.
947 OptimizePM.addPass(DivRemPairsPass());
948
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000949 // LoopSink (and other loop passes since the last simplifyCFG) might have
950 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
951 OptimizePM.addPass(SimplifyCFGPass());
952
Chandler Carruthc34f7892017-11-28 11:32:31 +0000953 // Optimize PHIs by speculating around them when profitable. Note that this
954 // pass needs to be run after any PRE or similar pass as it is essentially
Joerg Sonnenbergerec6ee792019-05-16 18:01:57 +0000955 // inserting redundancies into the program. This even includes SimplifyCFG.
Chandler Carruthc34f7892017-11-28 11:32:31 +0000956 OptimizePM.addPass(SpeculateAroundPHIsPass());
957
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000958 for (auto &C : OptimizerLastEPCallbacks)
959 C(OptimizePM, Level);
960
Chandler Carrutha95ff382017-01-27 00:50:21 +0000961 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000962 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
963
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000964 MPM.addPass(CGProfilePass());
965
Chandler Carruthe3f50642016-12-22 06:59:15 +0000966 // Now we need to do some global optimization transforms.
967 // FIXME: It would seem like these should come first in the optimization
968 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
969 // ordering here.
970 MPM.addPass(GlobalDCEPass());
971 MPM.addPass(ConstantMergePass());
972
973 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000974}
975
Chandler Carruthe3f50642016-12-22 06:59:15 +0000976ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000977PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000978 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000979 assert(Level != O0 && "Must request optimizations for the default pipeline!");
980
981 ModulePassManager MPM(DebugLogging);
982
983 // Force any function attributes we want the rest of the pipeline to observe.
984 MPM.addPass(ForceFunctionAttrsPass());
985
David Blaikie0c64f5a2018-01-23 01:25:20 +0000986 // Apply module pipeline start EP callback.
987 for (auto &C : PipelineStartEPCallbacks)
988 C(MPM);
989
Dehao Chen08f88312017-08-07 20:23:20 +0000990 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000991 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
992
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000993 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000994 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
995 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000996
997 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000998 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000999
1000 return MPM;
1001}
1002
1003ModulePassManager
1004PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1005 bool DebugLogging) {
1006 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1007
1008 ModulePassManager MPM(DebugLogging);
1009
1010 // Force any function attributes we want the rest of the pipeline to observe.
1011 MPM.addPass(ForceFunctionAttrsPass());
1012
Dehao Chen08f88312017-08-07 20:23:20 +00001013 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001014 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1015
David Blaikie0c64f5a2018-01-23 01:25:20 +00001016 // Apply module pipeline start EP callback.
1017 for (auto &C : PipelineStartEPCallbacks)
1018 C(MPM);
1019
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001020 // If we are planning to perform ThinLTO later, we don't bloat the code with
1021 // unrolling/vectorization/... now. Just simplify the module as much as we
1022 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001023 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1024 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001025
1026 // Run partial inlining pass to partially inline functions that have
1027 // large bodies.
1028 // FIXME: It isn't clear whether this is really the right place to run this
1029 // in ThinLTO. Because there is another canonicalization and simplification
1030 // phase that will run after the thin link, running this here ends up with
1031 // less information than will be available later and it may grow functions in
1032 // ways that aren't beneficial.
1033 if (RunPartialInlining)
1034 MPM.addPass(PartialInlinerPass());
1035
1036 // Reduce the size of the IR as much as possible.
1037 MPM.addPass(GlobalOptPass());
1038
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001039 return MPM;
1040}
1041
Teresa Johnson28023db2018-07-19 14:51:32 +00001042ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1043 OptimizationLevel Level, bool DebugLogging,
1044 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001045 ModulePassManager MPM(DebugLogging);
1046
Teresa Johnson28023db2018-07-19 14:51:32 +00001047 if (ImportSummary) {
1048 // These passes import type identifier resolutions for whole-program
1049 // devirtualization and CFI. They must run early because other passes may
1050 // disturb the specific instruction patterns that these passes look for,
1051 // creating dependencies on resolutions that may not appear in the summary.
1052 //
1053 // For example, GVN may transform the pattern assume(type.test) appearing in
1054 // two basic blocks into assume(phi(type.test, type.test)), which would
1055 // transform a dependency on a WPD resolution into a dependency on a type
1056 // identifier resolution for CFI.
1057 //
1058 // Also, WPD has access to more precise information than ICP and can
1059 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001060 //
1061 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1062 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001063 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1064 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1065 }
1066
Teresa Johnson867bc392019-04-23 18:56:19 +00001067 if (Level == O0)
1068 return MPM;
1069
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001070 // Force any function attributes we want the rest of the pipeline to observe.
1071 MPM.addPass(ForceFunctionAttrsPass());
1072
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001073 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001074 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1075 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001076
1077 // Now add the optimization pipeline.
1078 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1079
1080 return MPM;
1081}
1082
1083ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001084PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1085 bool DebugLogging) {
1086 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001087 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001088 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001089 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001090}
1091
Teresa Johnson28023db2018-07-19 14:51:32 +00001092ModulePassManager
1093PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1094 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001095 ModulePassManager MPM(DebugLogging);
1096
Teresa Johnson867bc392019-04-23 18:56:19 +00001097 if (Level == O0) {
1098 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1099 // metadata and intrinsics.
1100 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1101 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1102 return MPM;
1103 }
1104
Rong Xudb29a3a2019-03-04 20:21:27 +00001105 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001106 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001107 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001108 PGOOpt->ProfileRemappingFile,
1109 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001110 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1111 // RequireAnalysisPass for PSI before subsequent non-module passes.
1112 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001113 }
1114
Davide Italiano089a9122017-01-24 00:57:39 +00001115 // Remove unused virtual tables to improve the quality of code generated by
1116 // whole-program devirtualization and bitset lowering.
1117 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001118
Davide Italiano089a9122017-01-24 00:57:39 +00001119 // Force any function attributes we want the rest of the pipeline to observe.
1120 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001121
Davide Italiano089a9122017-01-24 00:57:39 +00001122 // Do basic inference of function attributes from known properties of system
1123 // libraries and other oracles.
1124 MPM.addPass(InferFunctionAttrsPass());
1125
1126 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001127 FunctionPassManager EarlyFPM(DebugLogging);
1128 EarlyFPM.addPass(CallSiteSplittingPass());
1129 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1130
Davide Italiano089a9122017-01-24 00:57:39 +00001131 // Indirect call promotion. This should promote all the targets that are
1132 // left by the earlier promotion pass that promotes intra-module targets.
1133 // This two-step promotion is to save the compile time. For LTO, it should
1134 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001135 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001136 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001137 // Propagate constants at call sites into the functions they call. This
1138 // opens opportunities for globalopt (and inlining) by substituting function
1139 // pointers passed as arguments to direct uses of functions.
1140 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001141
1142 // Attach metadata to indirect call sites indicating the set of functions
1143 // they may target at run-time. This should follow IPSCCP.
1144 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001145 }
1146
1147 // Now deduce any function attributes based in the current code.
1148 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1149 PostOrderFunctionAttrsPass()));
1150
1151 // Do RPO function attribute inference across the module to forward-propagate
1152 // attributes where applicable.
1153 // FIXME: Is this really an optimization rather than a canonicalization?
1154 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1155
Eric Christopher721eaef2019-02-26 20:33:22 +00001156 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001157 MPM.addPass(GlobalSplitPass());
1158
1159 // Run whole program optimization of virtual call when the list of callees
1160 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001161 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001162
1163 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001164 if (Level == 1) {
1165 // The LowerTypeTestsPass needs to run to lower type metadata and the
1166 // type.test intrinsics. The pass does nothing if CFI is disabled.
1167 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001168 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001169 }
Davide Italiano089a9122017-01-24 00:57:39 +00001170
1171 // Optimize globals to try and fold them into constants.
1172 MPM.addPass(GlobalOptPass());
1173
1174 // Promote any localized globals to SSA registers.
1175 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1176
1177 // Linking modules together can lead to duplicate global constant, only
1178 // keep one copy of each constant.
1179 MPM.addPass(ConstantMergePass());
1180
1181 // Remove unused arguments from functions.
1182 MPM.addPass(DeadArgumentEliminationPass());
1183
1184 // Reduce the code after globalopt and ipsccp. Both can open up significant
1185 // simplification opportunities, and both can propagate functions through
1186 // function pointers. When this happens, we often have to resolve varargs
1187 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001188 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001189 if (Level == O3)
1190 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001191 PeepholeFPM.addPass(InstCombinePass());
1192 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1193
1194 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001195
1196 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1197 // generally clean up exception handling overhead. It isn't clear this is
1198 // valuable as the inliner doesn't currently care whether it is inlining an
1199 // invoke or a call.
1200 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001201 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1202 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001203
1204 // Optimize globals again after we ran the inliner.
1205 MPM.addPass(GlobalOptPass());
1206
1207 // Garbage collect dead functions.
1208 // FIXME: Add ArgumentPromotion pass after once it's ported.
1209 MPM.addPass(GlobalDCEPass());
1210
1211 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001212 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001213 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001214 invokePeepholeEPCallbacks(FPM, Level);
1215
Davide Italiano089a9122017-01-24 00:57:39 +00001216 FPM.addPass(JumpThreadingPass());
1217
Rong Xudb29a3a2019-03-04 20:21:27 +00001218 // Do a post inline PGO instrumentation and use pass. This is a context
1219 // sensitive PGO pass.
1220 if (PGOOpt) {
1221 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1222 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1223 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1224 PGOOpt->ProfileRemappingFile);
1225 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1226 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1227 /* IsCS */ true, PGOOpt->ProfileFile,
1228 PGOOpt->ProfileRemappingFile);
1229 }
1230
Davide Italiano089a9122017-01-24 00:57:39 +00001231 // Break up allocas
1232 FPM.addPass(SROA());
1233
Robert Lougherf2158a82019-03-20 19:08:18 +00001234 // LTO provides additional opportunities for tailcall elimination due to
1235 // link-time inlining, and visibility of nocapture attribute.
1236 FPM.addPass(TailCallElimPass());
1237
Davide Italiano089a9122017-01-24 00:57:39 +00001238 // Run a few AA driver optimizations here and now to cleanup the code.
1239 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1240
1241 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1242 PostOrderFunctionAttrsPass()));
1243 // FIXME: here we run IP alias analysis in the legacy PM.
1244
1245 FunctionPassManager MainFPM;
1246
1247 // FIXME: once we fix LoopPass Manager, add LICM here.
1248 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001249 if (RunNewGVN)
1250 MainFPM.addPass(NewGVNPass());
1251 else
1252 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001253
1254 // Remove dead memcpy()'s.
1255 MainFPM.addPass(MemCpyOptPass());
1256
1257 // Nuke dead stores.
1258 MainFPM.addPass(DSEPass());
1259
1260 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001261 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001262 // loopVectorize. Enable them once the remaining issue with LPM
1263 // are sorted out.
1264
1265 MainFPM.addPass(InstCombinePass());
1266 MainFPM.addPass(SimplifyCFGPass());
1267 MainFPM.addPass(SCCPPass());
1268 MainFPM.addPass(InstCombinePass());
1269 MainFPM.addPass(BDCEPass());
1270
1271 // FIXME: We may want to run SLPVectorizer here.
1272 // After vectorization, assume intrinsics may tell us more
1273 // about pointer alignments.
1274#if 0
1275 MainFPM.add(AlignmentFromAssumptionsPass());
1276#endif
1277
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001278 // FIXME: Conditionally run LoadCombine here, after it's ported
1279 // (in case we still have this pass, given its questionable usefulness).
1280
Davide Italiano089a9122017-01-24 00:57:39 +00001281 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001282 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001283 MainFPM.addPass(JumpThreadingPass());
1284 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1285
1286 // Create a function that performs CFI checks for cross-DSO calls with
1287 // targets in the current module.
1288 MPM.addPass(CrossDSOCFIPass());
1289
1290 // Lower type metadata and the type.test intrinsic. This pass supports
1291 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1292 // to be run at link time if CFI is enabled. This pass does nothing if
1293 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001294 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001295
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001296 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1297 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1298 if (EnableHotColdSplit)
1299 MPM.addPass(HotColdSplittingPass());
1300
Davide Italiano089a9122017-01-24 00:57:39 +00001301 // Add late LTO optimization passes.
1302 // Delete basic blocks, which optimization passes may have killed.
1303 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1304
1305 // Drop bodies of available eternally objects to improve GlobalDCE.
1306 MPM.addPass(EliminateAvailableExternallyPass());
1307
1308 // Now that we have optimized the program, discard unreachable functions.
1309 MPM.addPass(GlobalDCEPass());
1310
Eric Christopher86e2f162019-05-03 00:15:23 +00001311 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001312 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001313}
1314
Chandler Carruth060ad612016-12-23 20:38:19 +00001315AAManager PassBuilder::buildDefaultAAPipeline() {
1316 AAManager AA;
1317
1318 // The order in which these are registered determines their priority when
1319 // being queried.
1320
1321 // First we register the basic alias analysis that provides the majority of
1322 // per-function local AA logic. This is a stateless, on-demand local set of
1323 // AA techniques.
1324 AA.registerFunctionAnalysis<BasicAA>();
1325
1326 // Next we query fast, specialized alias analyses that wrap IR-embedded
1327 // information about aliasing.
1328 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1329 AA.registerFunctionAnalysis<TypeBasedAA>();
1330
1331 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001332 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1333 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001334 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001335 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001336
1337 return AA;
1338}
1339
Chandler Carruth241bf242016-08-03 07:44:48 +00001340static Optional<int> parseRepeatPassName(StringRef Name) {
1341 if (!Name.consume_front("repeat<") || !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
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001349static Optional<int> parseDevirtPassName(StringRef Name) {
1350 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1351 return None;
1352 int Count;
1353 if (Name.getAsInteger(0, Count) || Count <= 0)
1354 return None;
1355 return Count;
1356}
1357
Fedor Sergeevb7871402019-01-10 10:01:53 +00001358static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1359 if (!Name.consume_front(PassName))
1360 return false;
1361 // normal pass name w/o parameters == default parameters
1362 if (Name.empty())
1363 return true;
1364 return Name.startswith("<") && Name.endswith(">");
1365}
1366
1367namespace {
1368
1369/// This performs customized parsing of pass name with parameters.
1370///
1371/// We do not need parametrization of passes in textual pipeline very often,
1372/// yet on a rare occasion ability to specify parameters right there can be
1373/// useful.
1374///
1375/// \p Name - parameterized specification of a pass from a textual pipeline
1376/// is a string in a form of :
1377/// PassName '<' parameter-list '>'
1378///
1379/// Parameter list is being parsed by the parser callable argument, \p Parser,
1380/// It takes a string-ref of parameters and returns either StringError or a
1381/// parameter list in a form of a custom parameters type, all wrapped into
1382/// Expected<> template class.
1383///
1384template <typename ParametersParseCallableT>
1385auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1386 StringRef PassName) -> decltype(Parser(StringRef{})) {
1387 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1388
1389 StringRef Params = Name;
1390 if (!Params.consume_front(PassName)) {
1391 assert(false &&
1392 "unable to strip pass name from parametrized pass specification");
1393 }
1394 if (Params.empty())
1395 return ParametersT{};
1396 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1397 assert(false && "invalid format for parametrized pass name");
1398 }
1399
1400 Expected<ParametersT> Result = Parser(Params);
1401 assert((Result || Result.template errorIsA<StringError>()) &&
1402 "Pass parameter parser can only return StringErrors.");
1403 return std::move(Result);
1404}
1405
1406/// Parser of parameters for LoopUnroll pass.
1407Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1408 LoopUnrollOptions UnrollOpts;
1409 while (!Params.empty()) {
1410 StringRef ParamName;
1411 std::tie(ParamName, Params) = Params.split(';');
1412 int OptLevel = StringSwitch<int>(ParamName)
1413 .Case("O0", 0)
1414 .Case("O1", 1)
1415 .Case("O2", 2)
1416 .Case("O3", 3)
1417 .Default(-1);
1418 if (OptLevel >= 0) {
1419 UnrollOpts.setOptLevel(OptLevel);
1420 continue;
1421 }
1422
1423 bool Enable = !ParamName.consume_front("no-");
1424 if (ParamName == "partial") {
1425 UnrollOpts.setPartial(Enable);
1426 } else if (ParamName == "peeling") {
1427 UnrollOpts.setPeeling(Enable);
1428 } else if (ParamName == "runtime") {
1429 UnrollOpts.setRuntime(Enable);
1430 } else if (ParamName == "upperbound") {
1431 UnrollOpts.setUpperBound(Enable);
1432 } else {
1433 return make_error<StringError>(
1434 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1435 inconvertibleErrorCode());
1436 }
1437 }
1438 return UnrollOpts;
1439}
1440
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001441Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1442 MemorySanitizerOptions Result;
1443 while (!Params.empty()) {
1444 StringRef ParamName;
1445 std::tie(ParamName, Params) = Params.split(';');
1446
1447 if (ParamName == "recover") {
1448 Result.Recover = true;
1449 } else if (ParamName == "kernel") {
1450 Result.Kernel = true;
1451 } else if (ParamName.consume_front("track-origins=")) {
1452 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1453 return make_error<StringError>(
1454 formatv("invalid argument to MemorySanitizer pass track-origins "
1455 "parameter: '{0}' ",
1456 ParamName)
1457 .str(),
1458 inconvertibleErrorCode());
1459 } else {
1460 return make_error<StringError>(
1461 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1462 .str(),
1463 inconvertibleErrorCode());
1464 }
1465 }
1466 return Result;
1467}
1468
Serguei Katkovf5432832019-04-15 08:57:53 +00001469/// Parser of parameters for SimplifyCFG pass.
1470Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1471 SimplifyCFGOptions Result;
1472 while (!Params.empty()) {
1473 StringRef ParamName;
1474 std::tie(ParamName, Params) = Params.split(';');
1475
1476 bool Enable = !ParamName.consume_front("no-");
1477 if (ParamName == "forward-switch-cond") {
1478 Result.forwardSwitchCondToPhi(Enable);
1479 } else if (ParamName == "switch-to-lookup") {
1480 Result.convertSwitchToLookupTable(Enable);
1481 } else if (ParamName == "keep-loops") {
1482 Result.needCanonicalLoops(Enable);
1483 } else if (ParamName == "sink-common-insts") {
1484 Result.sinkCommonInsts(Enable);
1485 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1486 APInt BonusInstThreshold;
1487 if (ParamName.getAsInteger(0, BonusInstThreshold))
1488 return make_error<StringError>(
1489 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1490 "parameter: '{0}' ",
1491 ParamName).str(),
1492 inconvertibleErrorCode());
1493 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1494 } else {
1495 return make_error<StringError>(
1496 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1497 inconvertibleErrorCode());
1498 }
1499 }
1500 return Result;
1501}
1502
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001503/// Parser of parameters for LoopVectorize pass.
1504Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1505 LoopVectorizeOptions Opts;
1506 while (!Params.empty()) {
1507 StringRef ParamName;
1508 std::tie(ParamName, Params) = Params.split(';');
1509
1510 bool Enable = !ParamName.consume_front("no-");
1511 if (ParamName == "interleave-forced-only") {
1512 Opts.setInterleaveOnlyWhenForced(Enable);
1513 } else if (ParamName == "vectorize-forced-only") {
1514 Opts.setVectorizeOnlyWhenForced(Enable);
1515 } else {
1516 return make_error<StringError>(
1517 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1518 inconvertibleErrorCode());
1519 }
1520 }
1521 return Opts;
1522}
1523
Serguei Katkov40a3b962019-04-22 10:35:07 +00001524Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1525 bool Result = false;
1526 while (!Params.empty()) {
1527 StringRef ParamName;
1528 std::tie(ParamName, Params) = Params.split(';');
1529
1530 bool Enable = !ParamName.consume_front("no-");
1531 if (ParamName == "nontrivial") {
1532 Result = Enable;
1533 } else {
1534 return make_error<StringError>(
1535 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1536 .str(),
1537 inconvertibleErrorCode());
1538 }
1539 }
1540 return Result;
1541}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001542} // namespace
1543
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001544/// Tests whether a pass name starts with a valid prefix for a default pipeline
1545/// alias.
1546static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1547 return Name.startswith("default") || Name.startswith("thinlto") ||
1548 Name.startswith("lto");
1549}
1550
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001551/// Tests whether registered callbacks will accept a given pass name.
1552///
1553/// When parsing a pipeline text, the type of the outermost pipeline may be
1554/// omitted, in which case the type is automatically determined from the first
1555/// pass name in the text. This may be a name that is handled through one of the
1556/// callbacks. We check this through the oridinary parsing callbacks by setting
1557/// up a dummy PassManager in order to not force the client to also handle this
1558/// type of query.
1559template <typename PassManagerT, typename CallbacksT>
1560static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1561 if (!Callbacks.empty()) {
1562 PassManagerT DummyPM;
1563 for (auto &CB : Callbacks)
1564 if (CB(Name, DummyPM, {}))
1565 return true;
1566 }
1567 return false;
1568}
1569
1570template <typename CallbacksT>
1571static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001572 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001573 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001574 return DefaultAliasRegex.match(Name);
1575
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001576 // Explicitly handle pass manager names.
1577 if (Name == "module")
1578 return true;
1579 if (Name == "cgscc")
1580 return true;
1581 if (Name == "function")
1582 return true;
1583
Chandler Carruth241bf242016-08-03 07:44:48 +00001584 // Explicitly handle custom-parsed pass names.
1585 if (parseRepeatPassName(Name))
1586 return true;
1587
Chandler Carruth74a8a222016-06-17 07:15:29 +00001588#define MODULE_PASS(NAME, CREATE_PASS) \
1589 if (Name == NAME) \
1590 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001591#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001592 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001593 return true;
1594#include "PassRegistry.def"
1595
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001596 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001597}
1598
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001599template <typename CallbacksT>
1600static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001601 // Explicitly handle pass manager names.
1602 if (Name == "cgscc")
1603 return true;
1604 if (Name == "function")
1605 return true;
1606
Chandler Carruth241bf242016-08-03 07:44:48 +00001607 // Explicitly handle custom-parsed pass names.
1608 if (parseRepeatPassName(Name))
1609 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001610 if (parseDevirtPassName(Name))
1611 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001612
Chandler Carruth74a8a222016-06-17 07:15:29 +00001613#define CGSCC_PASS(NAME, CREATE_PASS) \
1614 if (Name == NAME) \
1615 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001616#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001617 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001618 return true;
1619#include "PassRegistry.def"
1620
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001621 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001622}
1623
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001624template <typename CallbacksT>
1625static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001626 // Explicitly handle pass manager names.
1627 if (Name == "function")
1628 return true;
1629 if (Name == "loop")
1630 return true;
1631
Chandler Carruth241bf242016-08-03 07:44:48 +00001632 // Explicitly handle custom-parsed pass names.
1633 if (parseRepeatPassName(Name))
1634 return true;
1635
Chandler Carruth74a8a222016-06-17 07:15:29 +00001636#define FUNCTION_PASS(NAME, CREATE_PASS) \
1637 if (Name == NAME) \
1638 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001639#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1640 if (checkParametrizedPassName(Name, NAME)) \
1641 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001642#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001643 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001644 return true;
1645#include "PassRegistry.def"
1646
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001647 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001648}
1649
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001650template <typename CallbacksT>
1651static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001652 // Explicitly handle pass manager names.
1653 if (Name == "loop")
1654 return true;
1655
Chandler Carruth241bf242016-08-03 07:44:48 +00001656 // Explicitly handle custom-parsed pass names.
1657 if (parseRepeatPassName(Name))
1658 return true;
1659
Chandler Carruth74a8a222016-06-17 07:15:29 +00001660#define LOOP_PASS(NAME, CREATE_PASS) \
1661 if (Name == NAME) \
1662 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001663#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1664 if (checkParametrizedPassName(Name, NAME)) \
1665 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001666#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1667 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1668 return true;
1669#include "PassRegistry.def"
1670
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001671 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001672}
1673
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001674Optional<std::vector<PassBuilder::PipelineElement>>
1675PassBuilder::parsePipelineText(StringRef Text) {
1676 std::vector<PipelineElement> ResultPipeline;
1677
1678 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1679 &ResultPipeline};
1680 for (;;) {
1681 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1682 size_t Pos = Text.find_first_of(",()");
1683 Pipeline.push_back({Text.substr(0, Pos), {}});
1684
1685 // If we have a single terminating name, we're done.
1686 if (Pos == Text.npos)
1687 break;
1688
1689 char Sep = Text[Pos];
1690 Text = Text.substr(Pos + 1);
1691 if (Sep == ',')
1692 // Just a name ending in a comma, continue.
1693 continue;
1694
1695 if (Sep == '(') {
1696 // Push the inner pipeline onto the stack to continue processing.
1697 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1698 continue;
1699 }
1700
1701 assert(Sep == ')' && "Bogus separator!");
1702 // When handling the close parenthesis, we greedily consume them to avoid
1703 // empty strings in the pipeline.
1704 do {
1705 // If we try to pop the outer pipeline we have unbalanced parentheses.
1706 if (PipelineStack.size() == 1)
1707 return None;
1708
1709 PipelineStack.pop_back();
1710 } while (Text.consume_front(")"));
1711
1712 // Check if we've finished parsing.
1713 if (Text.empty())
1714 break;
1715
1716 // Otherwise, the end of an inner pipeline always has to be followed by
1717 // a comma, and then we can continue.
1718 if (!Text.consume_front(","))
1719 return None;
1720 }
1721
1722 if (PipelineStack.size() > 1)
1723 // Unbalanced paretheses.
1724 return None;
1725
1726 assert(PipelineStack.back() == &ResultPipeline &&
1727 "Wrong pipeline at the bottom of the stack!");
1728 return {std::move(ResultPipeline)};
1729}
1730
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001731Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1732 const PipelineElement &E,
1733 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001734 auto &Name = E.Name;
1735 auto &InnerPipeline = E.InnerPipeline;
1736
1737 // First handle complex passes like the pass managers which carry pipelines.
1738 if (!InnerPipeline.empty()) {
1739 if (Name == "module") {
1740 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001741 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1742 VerifyEachPass, DebugLogging))
1743 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001744 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001745 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001746 }
1747 if (Name == "cgscc") {
1748 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001749 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1750 DebugLogging))
1751 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001752 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001753 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001754 }
1755 if (Name == "function") {
1756 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001757 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1758 VerifyEachPass, DebugLogging))
1759 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001760 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001761 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001762 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001763 if (auto Count = parseRepeatPassName(Name)) {
1764 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001765 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1766 VerifyEachPass, DebugLogging))
1767 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001768 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001769 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001770 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001771
1772 for (auto &C : ModulePipelineParsingCallbacks)
1773 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001774 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001775
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001776 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001777 return make_error<StringError>(
1778 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1779 inconvertibleErrorCode());
1780 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001781 }
1782
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001783 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001784 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001785 SmallVector<StringRef, 3> Matches;
1786 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001787 return make_error<StringError>(
1788 formatv("unknown default pipeline alias '{0}'", Name).str(),
1789 inconvertibleErrorCode());
1790
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001791 assert(Matches.size() == 3 && "Must capture two matched strings!");
1792
Jordan Rosef85a95f2016-07-25 18:34:51 +00001793 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001794 .Case("O0", O0)
1795 .Case("O1", O1)
1796 .Case("O2", O2)
1797 .Case("O3", O3)
1798 .Case("Os", Os)
1799 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001800 if (L == O0)
1801 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001802 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001803
1804 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001805 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001806 } else if (Matches[1] == "thinlto-pre-link") {
1807 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1808 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001809 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001810 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001811 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001812 } else {
1813 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001814 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001815 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001816 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001817 }
1818
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001819 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001820#define MODULE_PASS(NAME, CREATE_PASS) \
1821 if (Name == NAME) { \
1822 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001823 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001824 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001825#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1826 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001827 MPM.addPass( \
1828 RequireAnalysisPass< \
1829 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001830 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001831 } \
1832 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001833 MPM.addPass(InvalidateAnalysisPass< \
1834 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001835 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001836 }
1837#include "PassRegistry.def"
1838
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001839 for (auto &C : ModulePipelineParsingCallbacks)
1840 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001841 return Error::success();
1842 return make_error<StringError>(
1843 formatv("unknown module pass '{0}'", Name).str(),
1844 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001845}
1846
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001847Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1848 const PipelineElement &E, bool VerifyEachPass,
1849 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001850 auto &Name = E.Name;
1851 auto &InnerPipeline = E.InnerPipeline;
1852
1853 // First handle complex passes like the pass managers which carry pipelines.
1854 if (!InnerPipeline.empty()) {
1855 if (Name == "cgscc") {
1856 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001857 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1858 VerifyEachPass, DebugLogging))
1859 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001860 // Add the nested pass manager with the appropriate adaptor.
1861 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001862 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001863 }
1864 if (Name == "function") {
1865 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001866 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1867 VerifyEachPass, DebugLogging))
1868 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001869 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001870 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001871 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001872 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001873 if (auto Count = parseRepeatPassName(Name)) {
1874 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001875 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1876 VerifyEachPass, DebugLogging))
1877 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001878 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001879 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001880 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001881 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1882 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001883 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1884 VerifyEachPass, DebugLogging))
1885 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001886 CGPM.addPass(
1887 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001888 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001889 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001890
1891 for (auto &C : CGSCCPipelineParsingCallbacks)
1892 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001893 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001894
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001895 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001896 return make_error<StringError>(
1897 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1898 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001899 }
1900
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001901// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001902#define CGSCC_PASS(NAME, CREATE_PASS) \
1903 if (Name == NAME) { \
1904 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001905 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001906 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001907#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1908 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001909 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001910 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001911 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1912 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001913 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001914 } \
1915 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001916 CGPM.addPass(InvalidateAnalysisPass< \
1917 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001918 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001919 }
1920#include "PassRegistry.def"
1921
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001922 for (auto &C : CGSCCPipelineParsingCallbacks)
1923 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001924 return Error::success();
1925 return make_error<StringError>(
1926 formatv("unknown cgscc pass '{0}'", Name).str(),
1927 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001928}
1929
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001930Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1931 const PipelineElement &E,
1932 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001933 auto &Name = E.Name;
1934 auto &InnerPipeline = E.InnerPipeline;
1935
1936 // First handle complex passes like the pass managers which carry pipelines.
1937 if (!InnerPipeline.empty()) {
1938 if (Name == "function") {
1939 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001940 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1941 VerifyEachPass, DebugLogging))
1942 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001943 // Add the nested pass manager with the appropriate adaptor.
1944 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001945 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001946 }
1947 if (Name == "loop") {
1948 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001949 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1950 DebugLogging))
1951 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001952 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001953 FPM.addPass(
1954 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001955 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001956 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001957 if (auto Count = parseRepeatPassName(Name)) {
1958 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001959 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1960 VerifyEachPass, DebugLogging))
1961 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001962 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001963 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001964 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001965
1966 for (auto &C : FunctionPipelineParsingCallbacks)
1967 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001968 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001969
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001970 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001971 return make_error<StringError>(
1972 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1973 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001974 }
1975
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001976// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001977#define FUNCTION_PASS(NAME, CREATE_PASS) \
1978 if (Name == NAME) { \
1979 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001980 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001981 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001982#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1983 if (checkParametrizedPassName(Name, NAME)) { \
1984 auto Params = parsePassParameters(PARSER, Name, NAME); \
1985 if (!Params) \
1986 return Params.takeError(); \
1987 FPM.addPass(CREATE_PASS(Params.get())); \
1988 return Error::success(); \
1989 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001990#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1991 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001992 FPM.addPass( \
1993 RequireAnalysisPass< \
1994 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001995 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001996 } \
1997 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001998 FPM.addPass(InvalidateAnalysisPass< \
1999 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002000 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002001 }
2002#include "PassRegistry.def"
2003
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002004 for (auto &C : FunctionPipelineParsingCallbacks)
2005 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002006 return Error::success();
2007 return make_error<StringError>(
2008 formatv("unknown function pass '{0}'", Name).str(),
2009 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002010}
2011
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002012Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2013 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002014 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002015 auto &InnerPipeline = E.InnerPipeline;
2016
2017 // First handle complex passes like the pass managers which carry pipelines.
2018 if (!InnerPipeline.empty()) {
2019 if (Name == "loop") {
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 Carruth6cb2ab22016-08-03 03:21:41 +00002024 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002025 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002026 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002027 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002028 if (auto Count = parseRepeatPassName(Name)) {
2029 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002030 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2031 VerifyEachPass, DebugLogging))
2032 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002033 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002034 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002035 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002036
2037 for (auto &C : LoopPipelineParsingCallbacks)
2038 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002039 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002040
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002041 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002042 return make_error<StringError>(
2043 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2044 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002045 }
2046
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002047// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002048#define LOOP_PASS(NAME, CREATE_PASS) \
2049 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002050 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002051 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002052 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002053#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2054 if (checkParametrizedPassName(Name, NAME)) { \
2055 auto Params = parsePassParameters(PARSER, Name, NAME); \
2056 if (!Params) \
2057 return Params.takeError(); \
2058 LPM.addPass(CREATE_PASS(Params.get())); \
2059 return Error::success(); \
2060 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002061#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2062 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002063 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002064 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2065 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2066 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002067 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002068 } \
2069 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002070 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002071 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002072 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002073 }
2074#include "PassRegistry.def"
2075
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002076 for (auto &C : LoopPipelineParsingCallbacks)
2077 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002078 return Error::success();
2079 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2080 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002081}
2082
Chandler Carruthedf59962016-02-18 09:45:17 +00002083bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002084#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2085 if (Name == NAME) { \
2086 AA.registerModuleAnalysis< \
2087 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2088 return true; \
2089 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002090#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2091 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002092 AA.registerFunctionAnalysis< \
2093 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002094 return true; \
2095 }
2096#include "PassRegistry.def"
2097
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002098 for (auto &C : AAParsingCallbacks)
2099 if (C(Name, AA))
2100 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002101 return false;
2102}
2103
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002104Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002105 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002106 bool VerifyEachPass,
2107 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002108 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002109 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2110 return Err;
2111 // FIXME: No verifier support for Loop passes!
2112 }
2113 return Error::success();
2114}
2115
2116Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2117 ArrayRef<PipelineElement> Pipeline,
2118 bool VerifyEachPass,
2119 bool DebugLogging) {
2120 for (const auto &Element : Pipeline) {
2121 if (auto Err =
2122 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2123 return Err;
2124 if (VerifyEachPass)
2125 FPM.addPass(VerifierPass());
2126 }
2127 return Error::success();
2128}
2129
2130Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2131 ArrayRef<PipelineElement> Pipeline,
2132 bool VerifyEachPass,
2133 bool DebugLogging) {
2134 for (const auto &Element : Pipeline) {
2135 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2136 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002137 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002138 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002139 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002140}
2141
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002142void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2143 FunctionAnalysisManager &FAM,
2144 CGSCCAnalysisManager &CGAM,
2145 ModuleAnalysisManager &MAM) {
2146 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2147 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002148 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2149 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2150 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2151 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2152 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2153}
2154
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002155Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2156 ArrayRef<PipelineElement> Pipeline,
2157 bool VerifyEachPass,
2158 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002159 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002160 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2161 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002162 if (VerifyEachPass)
2163 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002164 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002165 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002166}
2167
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002168// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002169// FIXME: Should this routine accept a TargetMachine or require the caller to
2170// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002171Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2172 StringRef PipelineText,
2173 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002174 auto Pipeline = parsePipelineText(PipelineText);
2175 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002176 return make_error<StringError>(
2177 formatv("invalid pipeline '{0}'", PipelineText).str(),
2178 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002179
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002180 // If the first name isn't at the module layer, wrap the pipeline up
2181 // automatically.
2182 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002183
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002184 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2185 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002186 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002187 } else if (isFunctionPassName(FirstName,
2188 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002189 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002190 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002191 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002192 } else {
2193 for (auto &C : TopLevelPipelineParsingCallbacks)
2194 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002195 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002196
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002197 // Unknown pass or pipeline name!
2198 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2199 return make_error<StringError>(
2200 formatv("unknown {0} name '{1}'",
2201 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2202 .str(),
2203 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002204 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002205 }
2206
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002207 if (auto Err =
2208 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2209 return Err;
2210 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002211}
Chandler Carruthedf59962016-02-18 09:45:17 +00002212
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002213// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002214Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2215 StringRef PipelineText,
2216 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002217 auto Pipeline = parsePipelineText(PipelineText);
2218 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002219 return make_error<StringError>(
2220 formatv("invalid pipeline '{0}'", PipelineText).str(),
2221 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002222
2223 StringRef FirstName = Pipeline->front().Name;
2224 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002225 return make_error<StringError>(
2226 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2227 PipelineText)
2228 .str(),
2229 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002230
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002231 if (auto Err =
2232 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2233 return Err;
2234 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002235}
2236
2237// Primary pass pipeline description parsing routine for a \c
2238// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002239Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2240 StringRef PipelineText,
2241 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002242 auto Pipeline = parsePipelineText(PipelineText);
2243 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002244 return make_error<StringError>(
2245 formatv("invalid pipeline '{0}'", PipelineText).str(),
2246 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002247
2248 StringRef FirstName = Pipeline->front().Name;
2249 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002250 return make_error<StringError>(
2251 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2252 PipelineText)
2253 .str(),
2254 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002255
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002256 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2257 DebugLogging))
2258 return Err;
2259 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002260}
2261
2262// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002263Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2264 StringRef PipelineText,
2265 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002266 auto Pipeline = parsePipelineText(PipelineText);
2267 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002268 return make_error<StringError>(
2269 formatv("invalid pipeline '{0}'", PipelineText).str(),
2270 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002271
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002272 if (auto Err =
2273 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2274 return Err;
2275
2276 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002277}
2278
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002279Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002280 // If the pipeline just consists of the word 'default' just replace the AA
2281 // manager with our default one.
2282 if (PipelineText == "default") {
2283 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002284 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002285 }
2286
Chandler Carruthedf59962016-02-18 09:45:17 +00002287 while (!PipelineText.empty()) {
2288 StringRef Name;
2289 std::tie(Name, PipelineText) = PipelineText.split(',');
2290 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002291 return make_error<StringError>(
2292 formatv("unknown alias analysis name '{0}'", Name).str(),
2293 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002294 }
2295
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002296 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002297}