blob: bd7ec65052ab31cc9e527d1ce15d044b8f2dc4fb [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
Leonard Chan97dc6222019-06-20 19:44:51 +0000815 // running remaining passes on the eliminated functions. These should be
816 // preserved during prelinking for link-time inlining decisions.
817 if (!LTOPreLink)
818 MPM.addPass(EliminateAvailableExternallyPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000819
Manman Ren18295122019-02-28 20:13:38 +0000820 if (EnableOrderFileInstrumentation)
821 MPM.addPass(InstrOrderFilePass());
822
Chandler Carruthe3f50642016-12-22 06:59:15 +0000823 // Do RPO function attribute inference across the module to forward-propagate
824 // attributes where applicable.
825 // FIXME: Is this really an optimization rather than a canonicalization?
826 MPM.addPass(ReversePostOrderFunctionAttrsPass());
827
Rong Xudb29a3a2019-03-04 20:21:27 +0000828 // Do a post inline PGO instrumentation and use pass. This is a context
829 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
830 // cross-module inline has not been done yet. The context sensitive
831 // instrumentation is after all the inlines are done.
832 if (!LTOPreLink && PGOOpt) {
833 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
834 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
835 /* IsCS */ true, PGOOpt->CSProfileGenFile,
836 PGOOpt->ProfileRemappingFile);
837 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
838 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
839 /* IsCS */ true, PGOOpt->ProfileFile,
840 PGOOpt->ProfileRemappingFile);
841 }
842
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000843 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000844 // useful as the above will have inlined, DCE'ed, and function-attr
845 // propagated everything. We should at this point have a reasonably minimal
846 // and richly annotated call graph. By computing aliasing and mod/ref
847 // information for all local globals here, the late loop passes and notably
848 // the vectorizer will be able to use them to help recognize vectorizable
849 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000850 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000851
852 FunctionPassManager OptimizePM(DebugLogging);
853 OptimizePM.addPass(Float2IntPass());
854 // FIXME: We need to run some loop optimizations to re-rotate loops after
855 // simplify-cfg and others undo their rotation.
856
857 // Optimize the loop execution. These passes operate on entire loop nests
858 // rather than on each loop in an inside-out manner, and so they are actually
859 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000860
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000861 for (auto &C : VectorizerStartEPCallbacks)
862 C(OptimizePM, Level);
863
Chandler Carrutha95ff382017-01-27 00:50:21 +0000864 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000865 OptimizePM.addPass(
866 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000867
868 // Distribute loops to allow partial vectorization. I.e. isolate dependences
869 // into separate loop that would otherwise inhibit vectorization. This is
870 // currently only performed for loops marked with the metadata
871 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000872 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000873
874 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000875 OptimizePM.addPass(LoopVectorizePass(
876 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000877
Chandler Carruthbaabda92017-01-27 01:32:26 +0000878 // Eliminate loads by forwarding stores from the previous iteration to loads
879 // of the current iteration.
880 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000881
882 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000883 OptimizePM.addPass(InstCombinePass());
884
Chandler Carrutha95ff382017-01-27 00:50:21 +0000885 // Now that we've formed fast to execute loop structures, we do further
886 // optimizations. These are run afterward as they might block doing complex
887 // analyses and transforms such as what are needed for loop vectorization.
888
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000889 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
890 // GVN, loop transforms, and others have already run, so it's now better to
891 // convert to more optimized IR using more aggressive simplify CFG options.
892 // The extra sinking transform can create larger basic blocks, so do this
893 // before SLP vectorization.
894 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
895 forwardSwitchCondToPhi(true).
896 convertSwitchToLookupTable(true).
897 needCanonicalLoops(false).
898 sinkCommonInsts(true)));
899
Chandler Carruthe3f50642016-12-22 06:59:15 +0000900 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000901 if (PTO.SLPVectorization)
902 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000903
Chandler Carruthe3f50642016-12-22 06:59:15 +0000904 OptimizePM.addPass(InstCombinePass());
905
906 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000907 // execution resources of an out-of-order processor. We also then need to
908 // clean up redundancies and loop invariant code.
909 // FIXME: It would be really good to use a loop-integrated instruction
910 // combiner for cleanup here so that the unrolling and LICM can be pipelined
911 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000912 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
913 if (EnableUnrollAndJam) {
914 OptimizePM.addPass(
915 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
916 }
Alina Sbirleae4b27862019-05-23 19:35:40 +0000917 if (PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000918 OptimizePM.addPass(LoopUnrollPass(
919 LoopUnrollOptions(Level, false, PTO.ForgetAllSCEVInLoopUnroll)));
Michael Kruse72448522018-12-12 17:32:52 +0000920 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000921 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000922 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000923 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
924 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
925 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000926
927 // Now that we've vectorized and unrolled loops, we may have more refined
928 // alignment information, try to re-derive it here.
929 OptimizePM.addPass(AlignmentFromAssumptionsPass());
930
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000931 // Split out cold code. Splitting is done late to avoid hiding context from
932 // other optimizations and inadvertently regressing performance. The tradeoff
933 // is that this has a higher code size cost than splitting early.
934 if (EnableHotColdSplit && !LTOPreLink)
935 MPM.addPass(HotColdSplittingPass());
936
Chandler Carrutha95ff382017-01-27 00:50:21 +0000937 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
938 // canonicalization pass that enables other optimizations. As a result,
939 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
940 // result too early.
941 OptimizePM.addPass(LoopSinkPass());
942
943 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000944 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000945
Sanjay Patel6fd43912017-09-09 13:38:18 +0000946 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
947 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
948 // flattening of blocks.
949 OptimizePM.addPass(DivRemPairsPass());
950
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000951 // LoopSink (and other loop passes since the last simplifyCFG) might have
952 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
953 OptimizePM.addPass(SimplifyCFGPass());
954
Chandler Carruthc34f7892017-11-28 11:32:31 +0000955 // Optimize PHIs by speculating around them when profitable. Note that this
956 // pass needs to be run after any PRE or similar pass as it is essentially
Joerg Sonnenbergerec6ee792019-05-16 18:01:57 +0000957 // inserting redundancies into the program. This even includes SimplifyCFG.
Chandler Carruthc34f7892017-11-28 11:32:31 +0000958 OptimizePM.addPass(SpeculateAroundPHIsPass());
959
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000960 for (auto &C : OptimizerLastEPCallbacks)
961 C(OptimizePM, Level);
962
Chandler Carrutha95ff382017-01-27 00:50:21 +0000963 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000964 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
965
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000966 MPM.addPass(CGProfilePass());
967
Chandler Carruthe3f50642016-12-22 06:59:15 +0000968 // Now we need to do some global optimization transforms.
969 // FIXME: It would seem like these should come first in the optimization
970 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
971 // ordering here.
972 MPM.addPass(GlobalDCEPass());
973 MPM.addPass(ConstantMergePass());
974
975 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000976}
977
Chandler Carruthe3f50642016-12-22 06:59:15 +0000978ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000979PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000980 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000981 assert(Level != O0 && "Must request optimizations for the default pipeline!");
982
983 ModulePassManager MPM(DebugLogging);
984
985 // Force any function attributes we want the rest of the pipeline to observe.
986 MPM.addPass(ForceFunctionAttrsPass());
987
David Blaikie0c64f5a2018-01-23 01:25:20 +0000988 // Apply module pipeline start EP callback.
989 for (auto &C : PipelineStartEPCallbacks)
990 C(MPM);
991
Dehao Chen08f88312017-08-07 20:23:20 +0000992 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000993 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
994
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000995 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000996 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
997 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000998
999 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001000 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001001
1002 return MPM;
1003}
1004
1005ModulePassManager
1006PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1007 bool DebugLogging) {
1008 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1009
1010 ModulePassManager MPM(DebugLogging);
1011
1012 // Force any function attributes we want the rest of the pipeline to observe.
1013 MPM.addPass(ForceFunctionAttrsPass());
1014
Dehao Chen08f88312017-08-07 20:23:20 +00001015 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001016 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1017
David Blaikie0c64f5a2018-01-23 01:25:20 +00001018 // Apply module pipeline start EP callback.
1019 for (auto &C : PipelineStartEPCallbacks)
1020 C(MPM);
1021
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001022 // If we are planning to perform ThinLTO later, we don't bloat the code with
1023 // unrolling/vectorization/... now. Just simplify the module as much as we
1024 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001025 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1026 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001027
1028 // Run partial inlining pass to partially inline functions that have
1029 // large bodies.
1030 // FIXME: It isn't clear whether this is really the right place to run this
1031 // in ThinLTO. Because there is another canonicalization and simplification
1032 // phase that will run after the thin link, running this here ends up with
1033 // less information than will be available later and it may grow functions in
1034 // ways that aren't beneficial.
1035 if (RunPartialInlining)
1036 MPM.addPass(PartialInlinerPass());
1037
1038 // Reduce the size of the IR as much as possible.
1039 MPM.addPass(GlobalOptPass());
1040
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001041 return MPM;
1042}
1043
Teresa Johnson28023db2018-07-19 14:51:32 +00001044ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1045 OptimizationLevel Level, bool DebugLogging,
1046 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001047 ModulePassManager MPM(DebugLogging);
1048
Teresa Johnson28023db2018-07-19 14:51:32 +00001049 if (ImportSummary) {
1050 // These passes import type identifier resolutions for whole-program
1051 // devirtualization and CFI. They must run early because other passes may
1052 // disturb the specific instruction patterns that these passes look for,
1053 // creating dependencies on resolutions that may not appear in the summary.
1054 //
1055 // For example, GVN may transform the pattern assume(type.test) appearing in
1056 // two basic blocks into assume(phi(type.test, type.test)), which would
1057 // transform a dependency on a WPD resolution into a dependency on a type
1058 // identifier resolution for CFI.
1059 //
1060 // Also, WPD has access to more precise information than ICP and can
1061 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001062 //
1063 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1064 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001065 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1066 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1067 }
1068
Teresa Johnson867bc392019-04-23 18:56:19 +00001069 if (Level == O0)
1070 return MPM;
1071
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001072 // Force any function attributes we want the rest of the pipeline to observe.
1073 MPM.addPass(ForceFunctionAttrsPass());
1074
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001075 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001076 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1077 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001078
1079 // Now add the optimization pipeline.
1080 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1081
1082 return MPM;
1083}
1084
1085ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001086PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1087 bool DebugLogging) {
1088 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001089 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001090 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001091 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001092}
1093
Teresa Johnson28023db2018-07-19 14:51:32 +00001094ModulePassManager
1095PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1096 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001097 ModulePassManager MPM(DebugLogging);
1098
Teresa Johnson867bc392019-04-23 18:56:19 +00001099 if (Level == O0) {
1100 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1101 // metadata and intrinsics.
1102 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1103 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1104 return MPM;
1105 }
1106
Rong Xudb29a3a2019-03-04 20:21:27 +00001107 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001108 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001109 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001110 PGOOpt->ProfileRemappingFile,
1111 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001112 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1113 // RequireAnalysisPass for PSI before subsequent non-module passes.
1114 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001115 }
1116
Davide Italiano089a9122017-01-24 00:57:39 +00001117 // Remove unused virtual tables to improve the quality of code generated by
1118 // whole-program devirtualization and bitset lowering.
1119 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001120
Davide Italiano089a9122017-01-24 00:57:39 +00001121 // Force any function attributes we want the rest of the pipeline to observe.
1122 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001123
Davide Italiano089a9122017-01-24 00:57:39 +00001124 // Do basic inference of function attributes from known properties of system
1125 // libraries and other oracles.
1126 MPM.addPass(InferFunctionAttrsPass());
1127
1128 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001129 FunctionPassManager EarlyFPM(DebugLogging);
1130 EarlyFPM.addPass(CallSiteSplittingPass());
1131 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1132
Davide Italiano089a9122017-01-24 00:57:39 +00001133 // Indirect call promotion. This should promote all the targets that are
1134 // left by the earlier promotion pass that promotes intra-module targets.
1135 // This two-step promotion is to save the compile time. For LTO, it should
1136 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001137 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001138 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001139 // Propagate constants at call sites into the functions they call. This
1140 // opens opportunities for globalopt (and inlining) by substituting function
1141 // pointers passed as arguments to direct uses of functions.
1142 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001143
1144 // Attach metadata to indirect call sites indicating the set of functions
1145 // they may target at run-time. This should follow IPSCCP.
1146 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001147 }
1148
1149 // Now deduce any function attributes based in the current code.
1150 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1151 PostOrderFunctionAttrsPass()));
1152
1153 // Do RPO function attribute inference across the module to forward-propagate
1154 // attributes where applicable.
1155 // FIXME: Is this really an optimization rather than a canonicalization?
1156 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1157
Eric Christopher721eaef2019-02-26 20:33:22 +00001158 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001159 MPM.addPass(GlobalSplitPass());
1160
1161 // Run whole program optimization of virtual call when the list of callees
1162 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001163 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001164
1165 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001166 if (Level == 1) {
1167 // The LowerTypeTestsPass needs to run to lower type metadata and the
1168 // type.test intrinsics. The pass does nothing if CFI is disabled.
1169 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001170 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001171 }
Davide Italiano089a9122017-01-24 00:57:39 +00001172
1173 // Optimize globals to try and fold them into constants.
1174 MPM.addPass(GlobalOptPass());
1175
1176 // Promote any localized globals to SSA registers.
1177 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1178
1179 // Linking modules together can lead to duplicate global constant, only
1180 // keep one copy of each constant.
1181 MPM.addPass(ConstantMergePass());
1182
1183 // Remove unused arguments from functions.
1184 MPM.addPass(DeadArgumentEliminationPass());
1185
1186 // Reduce the code after globalopt and ipsccp. Both can open up significant
1187 // simplification opportunities, and both can propagate functions through
1188 // function pointers. When this happens, we often have to resolve varargs
1189 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001190 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001191 if (Level == O3)
1192 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001193 PeepholeFPM.addPass(InstCombinePass());
1194 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1195
1196 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001197
1198 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1199 // generally clean up exception handling overhead. It isn't clear this is
1200 // valuable as the inliner doesn't currently care whether it is inlining an
1201 // invoke or a call.
1202 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001203 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1204 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001205
1206 // Optimize globals again after we ran the inliner.
1207 MPM.addPass(GlobalOptPass());
1208
1209 // Garbage collect dead functions.
1210 // FIXME: Add ArgumentPromotion pass after once it's ported.
1211 MPM.addPass(GlobalDCEPass());
1212
1213 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001214 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001215 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001216 invokePeepholeEPCallbacks(FPM, Level);
1217
Davide Italiano089a9122017-01-24 00:57:39 +00001218 FPM.addPass(JumpThreadingPass());
1219
Rong Xudb29a3a2019-03-04 20:21:27 +00001220 // Do a post inline PGO instrumentation and use pass. This is a context
1221 // sensitive PGO pass.
1222 if (PGOOpt) {
1223 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1224 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1225 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1226 PGOOpt->ProfileRemappingFile);
1227 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1228 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1229 /* IsCS */ true, PGOOpt->ProfileFile,
1230 PGOOpt->ProfileRemappingFile);
1231 }
1232
Davide Italiano089a9122017-01-24 00:57:39 +00001233 // Break up allocas
1234 FPM.addPass(SROA());
1235
Robert Lougherf2158a82019-03-20 19:08:18 +00001236 // LTO provides additional opportunities for tailcall elimination due to
1237 // link-time inlining, and visibility of nocapture attribute.
1238 FPM.addPass(TailCallElimPass());
1239
Davide Italiano089a9122017-01-24 00:57:39 +00001240 // Run a few AA driver optimizations here and now to cleanup the code.
1241 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1242
1243 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1244 PostOrderFunctionAttrsPass()));
1245 // FIXME: here we run IP alias analysis in the legacy PM.
1246
1247 FunctionPassManager MainFPM;
1248
1249 // FIXME: once we fix LoopPass Manager, add LICM here.
1250 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001251 if (RunNewGVN)
1252 MainFPM.addPass(NewGVNPass());
1253 else
1254 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001255
1256 // Remove dead memcpy()'s.
1257 MainFPM.addPass(MemCpyOptPass());
1258
1259 // Nuke dead stores.
1260 MainFPM.addPass(DSEPass());
1261
1262 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001263 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001264 // loopVectorize. Enable them once the remaining issue with LPM
1265 // are sorted out.
1266
1267 MainFPM.addPass(InstCombinePass());
1268 MainFPM.addPass(SimplifyCFGPass());
1269 MainFPM.addPass(SCCPPass());
1270 MainFPM.addPass(InstCombinePass());
1271 MainFPM.addPass(BDCEPass());
1272
1273 // FIXME: We may want to run SLPVectorizer here.
1274 // After vectorization, assume intrinsics may tell us more
1275 // about pointer alignments.
1276#if 0
1277 MainFPM.add(AlignmentFromAssumptionsPass());
1278#endif
1279
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001280 // FIXME: Conditionally run LoadCombine here, after it's ported
1281 // (in case we still have this pass, given its questionable usefulness).
1282
Davide Italiano089a9122017-01-24 00:57:39 +00001283 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001284 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001285 MainFPM.addPass(JumpThreadingPass());
1286 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1287
1288 // Create a function that performs CFI checks for cross-DSO calls with
1289 // targets in the current module.
1290 MPM.addPass(CrossDSOCFIPass());
1291
1292 // Lower type metadata and the type.test intrinsic. This pass supports
1293 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1294 // to be run at link time if CFI is enabled. This pass does nothing if
1295 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001296 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001297
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001298 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1299 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1300 if (EnableHotColdSplit)
1301 MPM.addPass(HotColdSplittingPass());
1302
Davide Italiano089a9122017-01-24 00:57:39 +00001303 // Add late LTO optimization passes.
1304 // Delete basic blocks, which optimization passes may have killed.
1305 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1306
1307 // Drop bodies of available eternally objects to improve GlobalDCE.
1308 MPM.addPass(EliminateAvailableExternallyPass());
1309
1310 // Now that we have optimized the program, discard unreachable functions.
1311 MPM.addPass(GlobalDCEPass());
1312
Eric Christopher86e2f162019-05-03 00:15:23 +00001313 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001314 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001315}
1316
Chandler Carruth060ad612016-12-23 20:38:19 +00001317AAManager PassBuilder::buildDefaultAAPipeline() {
1318 AAManager AA;
1319
1320 // The order in which these are registered determines their priority when
1321 // being queried.
1322
1323 // First we register the basic alias analysis that provides the majority of
1324 // per-function local AA logic. This is a stateless, on-demand local set of
1325 // AA techniques.
1326 AA.registerFunctionAnalysis<BasicAA>();
1327
1328 // Next we query fast, specialized alias analyses that wrap IR-embedded
1329 // information about aliasing.
1330 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1331 AA.registerFunctionAnalysis<TypeBasedAA>();
1332
1333 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001334 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1335 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001336 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001337 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001338
1339 return AA;
1340}
1341
Chandler Carruth241bf242016-08-03 07:44:48 +00001342static Optional<int> parseRepeatPassName(StringRef Name) {
1343 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1344 return None;
1345 int Count;
1346 if (Name.getAsInteger(0, Count) || Count <= 0)
1347 return None;
1348 return Count;
1349}
1350
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001351static Optional<int> parseDevirtPassName(StringRef Name) {
1352 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1353 return None;
1354 int Count;
1355 if (Name.getAsInteger(0, Count) || Count <= 0)
1356 return None;
1357 return Count;
1358}
1359
Fedor Sergeevb7871402019-01-10 10:01:53 +00001360static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1361 if (!Name.consume_front(PassName))
1362 return false;
1363 // normal pass name w/o parameters == default parameters
1364 if (Name.empty())
1365 return true;
1366 return Name.startswith("<") && Name.endswith(">");
1367}
1368
1369namespace {
1370
1371/// This performs customized parsing of pass name with parameters.
1372///
1373/// We do not need parametrization of passes in textual pipeline very often,
1374/// yet on a rare occasion ability to specify parameters right there can be
1375/// useful.
1376///
1377/// \p Name - parameterized specification of a pass from a textual pipeline
1378/// is a string in a form of :
1379/// PassName '<' parameter-list '>'
1380///
1381/// Parameter list is being parsed by the parser callable argument, \p Parser,
1382/// It takes a string-ref of parameters and returns either StringError or a
1383/// parameter list in a form of a custom parameters type, all wrapped into
1384/// Expected<> template class.
1385///
1386template <typename ParametersParseCallableT>
1387auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1388 StringRef PassName) -> decltype(Parser(StringRef{})) {
1389 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1390
1391 StringRef Params = Name;
1392 if (!Params.consume_front(PassName)) {
1393 assert(false &&
1394 "unable to strip pass name from parametrized pass specification");
1395 }
1396 if (Params.empty())
1397 return ParametersT{};
1398 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1399 assert(false && "invalid format for parametrized pass name");
1400 }
1401
1402 Expected<ParametersT> Result = Parser(Params);
1403 assert((Result || Result.template errorIsA<StringError>()) &&
1404 "Pass parameter parser can only return StringErrors.");
1405 return std::move(Result);
1406}
1407
1408/// Parser of parameters for LoopUnroll pass.
1409Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1410 LoopUnrollOptions UnrollOpts;
1411 while (!Params.empty()) {
1412 StringRef ParamName;
1413 std::tie(ParamName, Params) = Params.split(';');
1414 int OptLevel = StringSwitch<int>(ParamName)
1415 .Case("O0", 0)
1416 .Case("O1", 1)
1417 .Case("O2", 2)
1418 .Case("O3", 3)
1419 .Default(-1);
1420 if (OptLevel >= 0) {
1421 UnrollOpts.setOptLevel(OptLevel);
1422 continue;
1423 }
1424
1425 bool Enable = !ParamName.consume_front("no-");
1426 if (ParamName == "partial") {
1427 UnrollOpts.setPartial(Enable);
1428 } else if (ParamName == "peeling") {
1429 UnrollOpts.setPeeling(Enable);
1430 } else if (ParamName == "runtime") {
1431 UnrollOpts.setRuntime(Enable);
1432 } else if (ParamName == "upperbound") {
1433 UnrollOpts.setUpperBound(Enable);
1434 } else {
1435 return make_error<StringError>(
1436 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1437 inconvertibleErrorCode());
1438 }
1439 }
1440 return UnrollOpts;
1441}
1442
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001443Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1444 MemorySanitizerOptions Result;
1445 while (!Params.empty()) {
1446 StringRef ParamName;
1447 std::tie(ParamName, Params) = Params.split(';');
1448
1449 if (ParamName == "recover") {
1450 Result.Recover = true;
1451 } else if (ParamName == "kernel") {
1452 Result.Kernel = true;
1453 } else if (ParamName.consume_front("track-origins=")) {
1454 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1455 return make_error<StringError>(
1456 formatv("invalid argument to MemorySanitizer pass track-origins "
1457 "parameter: '{0}' ",
1458 ParamName)
1459 .str(),
1460 inconvertibleErrorCode());
1461 } else {
1462 return make_error<StringError>(
1463 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1464 .str(),
1465 inconvertibleErrorCode());
1466 }
1467 }
1468 return Result;
1469}
1470
Serguei Katkovf5432832019-04-15 08:57:53 +00001471/// Parser of parameters for SimplifyCFG pass.
1472Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1473 SimplifyCFGOptions Result;
1474 while (!Params.empty()) {
1475 StringRef ParamName;
1476 std::tie(ParamName, Params) = Params.split(';');
1477
1478 bool Enable = !ParamName.consume_front("no-");
1479 if (ParamName == "forward-switch-cond") {
1480 Result.forwardSwitchCondToPhi(Enable);
1481 } else if (ParamName == "switch-to-lookup") {
1482 Result.convertSwitchToLookupTable(Enable);
1483 } else if (ParamName == "keep-loops") {
1484 Result.needCanonicalLoops(Enable);
1485 } else if (ParamName == "sink-common-insts") {
1486 Result.sinkCommonInsts(Enable);
1487 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1488 APInt BonusInstThreshold;
1489 if (ParamName.getAsInteger(0, BonusInstThreshold))
1490 return make_error<StringError>(
1491 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1492 "parameter: '{0}' ",
1493 ParamName).str(),
1494 inconvertibleErrorCode());
1495 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1496 } else {
1497 return make_error<StringError>(
1498 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1499 inconvertibleErrorCode());
1500 }
1501 }
1502 return Result;
1503}
1504
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001505/// Parser of parameters for LoopVectorize pass.
1506Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1507 LoopVectorizeOptions Opts;
1508 while (!Params.empty()) {
1509 StringRef ParamName;
1510 std::tie(ParamName, Params) = Params.split(';');
1511
1512 bool Enable = !ParamName.consume_front("no-");
1513 if (ParamName == "interleave-forced-only") {
1514 Opts.setInterleaveOnlyWhenForced(Enable);
1515 } else if (ParamName == "vectorize-forced-only") {
1516 Opts.setVectorizeOnlyWhenForced(Enable);
1517 } else {
1518 return make_error<StringError>(
1519 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1520 inconvertibleErrorCode());
1521 }
1522 }
1523 return Opts;
1524}
1525
Serguei Katkov40a3b962019-04-22 10:35:07 +00001526Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1527 bool Result = false;
1528 while (!Params.empty()) {
1529 StringRef ParamName;
1530 std::tie(ParamName, Params) = Params.split(';');
1531
1532 bool Enable = !ParamName.consume_front("no-");
1533 if (ParamName == "nontrivial") {
1534 Result = Enable;
1535 } else {
1536 return make_error<StringError>(
1537 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1538 .str(),
1539 inconvertibleErrorCode());
1540 }
1541 }
1542 return Result;
1543}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001544} // namespace
1545
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001546/// Tests whether a pass name starts with a valid prefix for a default pipeline
1547/// alias.
1548static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1549 return Name.startswith("default") || Name.startswith("thinlto") ||
1550 Name.startswith("lto");
1551}
1552
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001553/// Tests whether registered callbacks will accept a given pass name.
1554///
1555/// When parsing a pipeline text, the type of the outermost pipeline may be
1556/// omitted, in which case the type is automatically determined from the first
1557/// pass name in the text. This may be a name that is handled through one of the
1558/// callbacks. We check this through the oridinary parsing callbacks by setting
1559/// up a dummy PassManager in order to not force the client to also handle this
1560/// type of query.
1561template <typename PassManagerT, typename CallbacksT>
1562static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1563 if (!Callbacks.empty()) {
1564 PassManagerT DummyPM;
1565 for (auto &CB : Callbacks)
1566 if (CB(Name, DummyPM, {}))
1567 return true;
1568 }
1569 return false;
1570}
1571
1572template <typename CallbacksT>
1573static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001574 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001575 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001576 return DefaultAliasRegex.match(Name);
1577
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001578 // Explicitly handle pass manager names.
1579 if (Name == "module")
1580 return true;
1581 if (Name == "cgscc")
1582 return true;
1583 if (Name == "function")
1584 return true;
1585
Chandler Carruth241bf242016-08-03 07:44:48 +00001586 // Explicitly handle custom-parsed pass names.
1587 if (parseRepeatPassName(Name))
1588 return true;
1589
Chandler Carruth74a8a222016-06-17 07:15:29 +00001590#define MODULE_PASS(NAME, CREATE_PASS) \
1591 if (Name == NAME) \
1592 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001593#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001594 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001595 return true;
1596#include "PassRegistry.def"
1597
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001598 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001599}
1600
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001601template <typename CallbacksT>
1602static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001603 // Explicitly handle pass manager names.
1604 if (Name == "cgscc")
1605 return true;
1606 if (Name == "function")
1607 return true;
1608
Chandler Carruth241bf242016-08-03 07:44:48 +00001609 // Explicitly handle custom-parsed pass names.
1610 if (parseRepeatPassName(Name))
1611 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001612 if (parseDevirtPassName(Name))
1613 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001614
Chandler Carruth74a8a222016-06-17 07:15:29 +00001615#define CGSCC_PASS(NAME, CREATE_PASS) \
1616 if (Name == NAME) \
1617 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001618#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001619 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001620 return true;
1621#include "PassRegistry.def"
1622
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001623 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001624}
1625
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001626template <typename CallbacksT>
1627static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001628 // Explicitly handle pass manager names.
1629 if (Name == "function")
1630 return true;
1631 if (Name == "loop")
1632 return true;
1633
Chandler Carruth241bf242016-08-03 07:44:48 +00001634 // Explicitly handle custom-parsed pass names.
1635 if (parseRepeatPassName(Name))
1636 return true;
1637
Chandler Carruth74a8a222016-06-17 07:15:29 +00001638#define FUNCTION_PASS(NAME, CREATE_PASS) \
1639 if (Name == NAME) \
1640 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001641#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1642 if (checkParametrizedPassName(Name, NAME)) \
1643 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001644#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001645 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001646 return true;
1647#include "PassRegistry.def"
1648
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001649 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001650}
1651
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001652template <typename CallbacksT>
1653static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001654 // Explicitly handle pass manager names.
1655 if (Name == "loop")
1656 return true;
1657
Chandler Carruth241bf242016-08-03 07:44:48 +00001658 // Explicitly handle custom-parsed pass names.
1659 if (parseRepeatPassName(Name))
1660 return true;
1661
Chandler Carruth74a8a222016-06-17 07:15:29 +00001662#define LOOP_PASS(NAME, CREATE_PASS) \
1663 if (Name == NAME) \
1664 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001665#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1666 if (checkParametrizedPassName(Name, NAME)) \
1667 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001668#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1669 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1670 return true;
1671#include "PassRegistry.def"
1672
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001673 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001674}
1675
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001676Optional<std::vector<PassBuilder::PipelineElement>>
1677PassBuilder::parsePipelineText(StringRef Text) {
1678 std::vector<PipelineElement> ResultPipeline;
1679
1680 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1681 &ResultPipeline};
1682 for (;;) {
1683 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1684 size_t Pos = Text.find_first_of(",()");
1685 Pipeline.push_back({Text.substr(0, Pos), {}});
1686
1687 // If we have a single terminating name, we're done.
1688 if (Pos == Text.npos)
1689 break;
1690
1691 char Sep = Text[Pos];
1692 Text = Text.substr(Pos + 1);
1693 if (Sep == ',')
1694 // Just a name ending in a comma, continue.
1695 continue;
1696
1697 if (Sep == '(') {
1698 // Push the inner pipeline onto the stack to continue processing.
1699 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1700 continue;
1701 }
1702
1703 assert(Sep == ')' && "Bogus separator!");
1704 // When handling the close parenthesis, we greedily consume them to avoid
1705 // empty strings in the pipeline.
1706 do {
1707 // If we try to pop the outer pipeline we have unbalanced parentheses.
1708 if (PipelineStack.size() == 1)
1709 return None;
1710
1711 PipelineStack.pop_back();
1712 } while (Text.consume_front(")"));
1713
1714 // Check if we've finished parsing.
1715 if (Text.empty())
1716 break;
1717
1718 // Otherwise, the end of an inner pipeline always has to be followed by
1719 // a comma, and then we can continue.
1720 if (!Text.consume_front(","))
1721 return None;
1722 }
1723
1724 if (PipelineStack.size() > 1)
1725 // Unbalanced paretheses.
1726 return None;
1727
1728 assert(PipelineStack.back() == &ResultPipeline &&
1729 "Wrong pipeline at the bottom of the stack!");
1730 return {std::move(ResultPipeline)};
1731}
1732
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001733Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1734 const PipelineElement &E,
1735 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001736 auto &Name = E.Name;
1737 auto &InnerPipeline = E.InnerPipeline;
1738
1739 // First handle complex passes like the pass managers which carry pipelines.
1740 if (!InnerPipeline.empty()) {
1741 if (Name == "module") {
1742 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001743 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1744 VerifyEachPass, DebugLogging))
1745 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001746 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001747 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001748 }
1749 if (Name == "cgscc") {
1750 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001751 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1752 DebugLogging))
1753 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001754 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001755 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001756 }
1757 if (Name == "function") {
1758 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001759 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1760 VerifyEachPass, DebugLogging))
1761 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001762 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001763 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001764 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001765 if (auto Count = parseRepeatPassName(Name)) {
1766 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001767 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1768 VerifyEachPass, DebugLogging))
1769 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001770 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001771 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001772 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001773
1774 for (auto &C : ModulePipelineParsingCallbacks)
1775 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001776 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001777
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001778 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001779 return make_error<StringError>(
1780 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1781 inconvertibleErrorCode());
1782 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001783 }
1784
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001785 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001786 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001787 SmallVector<StringRef, 3> Matches;
1788 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001789 return make_error<StringError>(
1790 formatv("unknown default pipeline alias '{0}'", Name).str(),
1791 inconvertibleErrorCode());
1792
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001793 assert(Matches.size() == 3 && "Must capture two matched strings!");
1794
Jordan Rosef85a95f2016-07-25 18:34:51 +00001795 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001796 .Case("O0", O0)
1797 .Case("O1", O1)
1798 .Case("O2", O2)
1799 .Case("O3", O3)
1800 .Case("Os", Os)
1801 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001802 if (L == O0)
1803 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001804 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001805
1806 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001807 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001808 } else if (Matches[1] == "thinlto-pre-link") {
1809 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1810 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001811 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001812 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001813 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001814 } else {
1815 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001816 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001817 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001818 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001819 }
1820
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001821 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001822#define MODULE_PASS(NAME, CREATE_PASS) \
1823 if (Name == NAME) { \
1824 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001825 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001826 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001827#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1828 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001829 MPM.addPass( \
1830 RequireAnalysisPass< \
1831 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001832 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001833 } \
1834 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001835 MPM.addPass(InvalidateAnalysisPass< \
1836 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001837 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001838 }
1839#include "PassRegistry.def"
1840
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001841 for (auto &C : ModulePipelineParsingCallbacks)
1842 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001843 return Error::success();
1844 return make_error<StringError>(
1845 formatv("unknown module pass '{0}'", Name).str(),
1846 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001847}
1848
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001849Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1850 const PipelineElement &E, bool VerifyEachPass,
1851 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001852 auto &Name = E.Name;
1853 auto &InnerPipeline = E.InnerPipeline;
1854
1855 // First handle complex passes like the pass managers which carry pipelines.
1856 if (!InnerPipeline.empty()) {
1857 if (Name == "cgscc") {
1858 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001859 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1860 VerifyEachPass, DebugLogging))
1861 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001862 // Add the nested pass manager with the appropriate adaptor.
1863 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001864 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001865 }
1866 if (Name == "function") {
1867 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001868 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1869 VerifyEachPass, DebugLogging))
1870 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001871 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001872 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001873 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001874 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001875 if (auto Count = parseRepeatPassName(Name)) {
1876 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001877 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1878 VerifyEachPass, DebugLogging))
1879 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001880 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001881 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001882 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001883 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1884 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001885 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1886 VerifyEachPass, DebugLogging))
1887 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001888 CGPM.addPass(
1889 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001890 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001891 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001892
1893 for (auto &C : CGSCCPipelineParsingCallbacks)
1894 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001895 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001896
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001897 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001898 return make_error<StringError>(
1899 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1900 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001901 }
1902
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001903// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001904#define CGSCC_PASS(NAME, CREATE_PASS) \
1905 if (Name == NAME) { \
1906 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001907 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001908 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001909#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1910 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001911 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001912 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001913 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1914 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001915 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001916 } \
1917 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001918 CGPM.addPass(InvalidateAnalysisPass< \
1919 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001920 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001921 }
1922#include "PassRegistry.def"
1923
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001924 for (auto &C : CGSCCPipelineParsingCallbacks)
1925 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001926 return Error::success();
1927 return make_error<StringError>(
1928 formatv("unknown cgscc pass '{0}'", Name).str(),
1929 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001930}
1931
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001932Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1933 const PipelineElement &E,
1934 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001935 auto &Name = E.Name;
1936 auto &InnerPipeline = E.InnerPipeline;
1937
1938 // First handle complex passes like the pass managers which carry pipelines.
1939 if (!InnerPipeline.empty()) {
1940 if (Name == "function") {
1941 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001942 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1943 VerifyEachPass, DebugLogging))
1944 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001945 // Add the nested pass manager with the appropriate adaptor.
1946 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001947 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001948 }
1949 if (Name == "loop") {
1950 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001951 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1952 DebugLogging))
1953 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001954 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001955 FPM.addPass(
1956 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001957 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001958 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001959 if (auto Count = parseRepeatPassName(Name)) {
1960 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001961 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1962 VerifyEachPass, DebugLogging))
1963 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001964 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001965 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001966 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001967
1968 for (auto &C : FunctionPipelineParsingCallbacks)
1969 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001970 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001971
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001972 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001973 return make_error<StringError>(
1974 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1975 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001976 }
1977
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001978// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001979#define FUNCTION_PASS(NAME, CREATE_PASS) \
1980 if (Name == NAME) { \
1981 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001982 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001983 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001984#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1985 if (checkParametrizedPassName(Name, NAME)) { \
1986 auto Params = parsePassParameters(PARSER, Name, NAME); \
1987 if (!Params) \
1988 return Params.takeError(); \
1989 FPM.addPass(CREATE_PASS(Params.get())); \
1990 return Error::success(); \
1991 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001992#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1993 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001994 FPM.addPass( \
1995 RequireAnalysisPass< \
1996 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001997 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001998 } \
1999 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00002000 FPM.addPass(InvalidateAnalysisPass< \
2001 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002002 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002003 }
2004#include "PassRegistry.def"
2005
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002006 for (auto &C : FunctionPipelineParsingCallbacks)
2007 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002008 return Error::success();
2009 return make_error<StringError>(
2010 formatv("unknown function pass '{0}'", Name).str(),
2011 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002012}
2013
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002014Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2015 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002016 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002017 auto &InnerPipeline = E.InnerPipeline;
2018
2019 // First handle complex passes like the pass managers which carry pipelines.
2020 if (!InnerPipeline.empty()) {
2021 if (Name == "loop") {
2022 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002023 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2024 VerifyEachPass, DebugLogging))
2025 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002026 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002027 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002028 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002029 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002030 if (auto Count = parseRepeatPassName(Name)) {
2031 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002032 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2033 VerifyEachPass, DebugLogging))
2034 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002035 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002036 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002037 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002038
2039 for (auto &C : LoopPipelineParsingCallbacks)
2040 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002041 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002042
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002043 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002044 return make_error<StringError>(
2045 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2046 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002047 }
2048
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002049// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002050#define LOOP_PASS(NAME, CREATE_PASS) \
2051 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002052 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002053 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002054 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002055#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2056 if (checkParametrizedPassName(Name, NAME)) { \
2057 auto Params = parsePassParameters(PARSER, Name, NAME); \
2058 if (!Params) \
2059 return Params.takeError(); \
2060 LPM.addPass(CREATE_PASS(Params.get())); \
2061 return Error::success(); \
2062 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002063#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2064 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002065 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002066 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2067 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2068 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002069 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002070 } \
2071 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002072 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002073 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002074 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002075 }
2076#include "PassRegistry.def"
2077
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002078 for (auto &C : LoopPipelineParsingCallbacks)
2079 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002080 return Error::success();
2081 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2082 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002083}
2084
Chandler Carruthedf59962016-02-18 09:45:17 +00002085bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002086#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2087 if (Name == NAME) { \
2088 AA.registerModuleAnalysis< \
2089 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2090 return true; \
2091 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002092#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2093 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002094 AA.registerFunctionAnalysis< \
2095 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002096 return true; \
2097 }
2098#include "PassRegistry.def"
2099
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002100 for (auto &C : AAParsingCallbacks)
2101 if (C(Name, AA))
2102 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002103 return false;
2104}
2105
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002106Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002107 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002108 bool VerifyEachPass,
2109 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002110 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002111 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2112 return Err;
2113 // FIXME: No verifier support for Loop passes!
2114 }
2115 return Error::success();
2116}
2117
2118Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2119 ArrayRef<PipelineElement> Pipeline,
2120 bool VerifyEachPass,
2121 bool DebugLogging) {
2122 for (const auto &Element : Pipeline) {
2123 if (auto Err =
2124 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2125 return Err;
2126 if (VerifyEachPass)
2127 FPM.addPass(VerifierPass());
2128 }
2129 return Error::success();
2130}
2131
2132Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2133 ArrayRef<PipelineElement> Pipeline,
2134 bool VerifyEachPass,
2135 bool DebugLogging) {
2136 for (const auto &Element : Pipeline) {
2137 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2138 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002139 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002140 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002141 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002142}
2143
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002144void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2145 FunctionAnalysisManager &FAM,
2146 CGSCCAnalysisManager &CGAM,
2147 ModuleAnalysisManager &MAM) {
2148 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2149 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002150 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2151 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2152 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2153 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2154 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2155}
2156
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002157Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2158 ArrayRef<PipelineElement> Pipeline,
2159 bool VerifyEachPass,
2160 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002161 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002162 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2163 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002164 if (VerifyEachPass)
2165 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002166 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002167 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002168}
2169
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002170// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002171// FIXME: Should this routine accept a TargetMachine or require the caller to
2172// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002173Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2174 StringRef PipelineText,
2175 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002176 auto Pipeline = parsePipelineText(PipelineText);
2177 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002178 return make_error<StringError>(
2179 formatv("invalid pipeline '{0}'", PipelineText).str(),
2180 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002181
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002182 // If the first name isn't at the module layer, wrap the pipeline up
2183 // automatically.
2184 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002185
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002186 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2187 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002188 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002189 } else if (isFunctionPassName(FirstName,
2190 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002191 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002192 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002193 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002194 } else {
2195 for (auto &C : TopLevelPipelineParsingCallbacks)
2196 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002197 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002198
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002199 // Unknown pass or pipeline name!
2200 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2201 return make_error<StringError>(
2202 formatv("unknown {0} name '{1}'",
2203 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2204 .str(),
2205 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002206 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002207 }
2208
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002209 if (auto Err =
2210 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2211 return Err;
2212 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002213}
Chandler Carruthedf59962016-02-18 09:45:17 +00002214
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002215// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002216Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2217 StringRef PipelineText,
2218 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002219 auto Pipeline = parsePipelineText(PipelineText);
2220 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002221 return make_error<StringError>(
2222 formatv("invalid pipeline '{0}'", PipelineText).str(),
2223 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002224
2225 StringRef FirstName = Pipeline->front().Name;
2226 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002227 return make_error<StringError>(
2228 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2229 PipelineText)
2230 .str(),
2231 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002232
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002233 if (auto Err =
2234 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2235 return Err;
2236 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002237}
2238
2239// Primary pass pipeline description parsing routine for a \c
2240// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002241Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2242 StringRef PipelineText,
2243 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002244 auto Pipeline = parsePipelineText(PipelineText);
2245 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002246 return make_error<StringError>(
2247 formatv("invalid pipeline '{0}'", PipelineText).str(),
2248 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002249
2250 StringRef FirstName = Pipeline->front().Name;
2251 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002252 return make_error<StringError>(
2253 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2254 PipelineText)
2255 .str(),
2256 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002257
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002258 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2259 DebugLogging))
2260 return Err;
2261 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002262}
2263
2264// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002265Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2266 StringRef PipelineText,
2267 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002268 auto Pipeline = parsePipelineText(PipelineText);
2269 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002270 return make_error<StringError>(
2271 formatv("invalid pipeline '{0}'", PipelineText).str(),
2272 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002273
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002274 if (auto Err =
2275 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2276 return Err;
2277
2278 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002279}
2280
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002281Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002282 // If the pipeline just consists of the word 'default' just replace the AA
2283 // manager with our default one.
2284 if (PipelineText == "default") {
2285 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002286 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002287 }
2288
Chandler Carruthedf59962016-02-18 09:45:17 +00002289 while (!PipelineText.empty()) {
2290 StringRef Name;
2291 std::tie(Name, PipelineText) = PipelineText.split(',');
2292 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002293 return make_error<StringError>(
2294 formatv("unknown alias analysis name '{0}'", Name).str(),
2295 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002296 }
2297
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002298 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002299}