blob: 5ec94ea6f40ab093288397e6f3703aa6181845a8 [file] [log] [blame]
Chandler Carruth23491362015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth4e728be2014-01-11 08:16:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10///
Chandler Carruth23491362015-03-07 09:02:36 +000011/// This file provides the implementation of the PassBuilder based on our
12/// static pass registry as well as related functionality. It also provides
13/// helpers to aid in analyzing, debugging, and testing passes and pass
14/// pipelines.
Chandler Carruth4e728be2014-01-11 08:16:35 +000015///
16//===----------------------------------------------------------------------===//
17
Chandler Carruth23491362015-03-07 09:02:36 +000018#include "llvm/Passes/PassBuilder.h"
Chandler Carruthf7ae2f52016-02-28 22:16:03 +000019#include "llvm/ADT/StringSwitch.h"
Chandler Carruth26bf6ea2016-02-13 23:32:00 +000020#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth89a08aa2016-02-20 03:46:03 +000021#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasper8de3a542016-12-19 08:22:17 +000022#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth6f603ac2016-02-13 23:46:24 +000023#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Lida713ca2016-05-05 21:13:27 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li454f7fa2016-05-05 02:59:57 +000025#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini8dff0d82016-09-16 16:56:30 +000026#include "llvm/Analysis/CFGPrinter.h"
George Burgess IV3b5b98a2016-07-06 00:26:41 +000027#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
28#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth57418d82014-04-21 11:12:00 +000029#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruthf1b2c7b2016-03-10 11:24:11 +000030#include "llvm/Analysis/CallGraph.h"
Michael Kuperstein3445cc72016-04-18 23:55:01 +000031#include "llvm/Analysis/DemandedBits.h"
Chandler Carruthb6b8f762016-05-12 22:19:39 +000032#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng15969222016-02-25 17:54:15 +000033#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruthf51faf02016-03-11 09:15:11 +000034#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen78ee4b62016-07-16 22:51:33 +000035#include "llvm/Analysis/IVUsers.h"
Chandler Carruth57732bf2014-02-06 04:37:03 +000036#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva9ce41c32016-06-13 22:01:25 +000037#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li10b22c82016-07-02 21:18:40 +000038#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carrutha3751202015-01-20 10:58:50 +000039#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthc5266b52016-03-10 00:55:30 +000040#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berline0f5ddb2017-04-11 20:06:36 +000041#include "llvm/Analysis/MemorySSA.h"
Teresa Johnson3143f332016-08-12 13:53:02 +000042#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet3b8950a2017-10-09 23:19:02 +000043#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawn106ffb92018-06-28 14:13:06 +000044#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng5d7472e2016-02-25 17:54:07 +000045#include "llvm/Analysis/PostDominators.h"
Easwaran Raman7ef349f2016-06-03 22:54:26 +000046#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengedc89ca2016-02-25 17:54:25 +000047#include "llvm/Analysis/RegionInfo.h"
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +000048#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth10ab5d92016-02-20 04:01:45 +000049#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruth580e4662016-02-20 04:03:06 +000050#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Bukac29e36f2018-11-26 21:57:47 +000051#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruthe2ffd022015-01-15 11:39:46 +000052#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth7724e8e2015-02-01 10:11:22 +000053#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth3b194092016-02-20 04:04:52 +000054#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kupersteinf3f8fc62016-06-24 20:13:42 +000055#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi302c35d2016-07-08 03:32:49 +000056#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth8c3a02f2015-01-14 10:19:28 +000057#include "llvm/IR/Dominators.h"
Chandler Carrutha5952572014-01-12 12:15:39 +000058#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth4e728be2014-01-11 08:16:35 +000059#include "llvm/IR/PassManager.h"
Chandler Carruth1d9ab252014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carrutha5952572014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevff886492018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruthf7ae2f52016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruth7724e8e2015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudc6483fb2018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruthb699f7b2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruth1648cea2017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpson7d6a3b62017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano0a517712016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano0dd611b2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silva466d0a32016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italianoe44aed72016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruth6a1ce8e2015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruthe9afeb02016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson385d7062016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano82cad6f2016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a9ed302016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano02ca2cb2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumarf7ae0df2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruthd9796422015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth54cffa12016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bognerc3ce5d92016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoeb066402016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman78b1ab72016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italiano2d1483c2016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikied140aea2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bognere39e3a42015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Raman283d9782018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italiano7c798722016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruth6a1ce8e2015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffe4956e302019-01-03 13:42:44 +000091#include "llvm/Transforms/Instrumentation.h"
Chandler Carruth8dd352a2017-11-14 01:30:04 +000092#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Bukac29e36f2018-11-26 21:57:47 +000093#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchic38c8502018-09-04 17:19:13 +000094#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruthb2b950d2018-06-29 23:36:03 +000095#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
96#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffe4956e302019-01-03 13:42:44 +000097#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
Philip Pfaffe6dbe2252019-01-16 09:28:01 +000098#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
David Blaikiea10309c2018-03-23 22:11:06 +000099#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Justin Bogneraf019982015-10-30 23:13:18 +0000100#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silva570b29d2016-06-15 06:18:01 +0000101#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italianoabf016e2016-05-25 01:57:04 +0000102#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Limf4beb752017-11-03 20:41:16 +0000103#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemetc476e172016-07-18 16:29:17 +0000104#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silva9afbd6f2016-07-06 23:26:29 +0000105#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner04d28142016-04-22 19:40:41 +0000106#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner9c81a3f2016-05-17 21:38:13 +0000107#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel193e8982017-09-09 13:38:18 +0000108#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruth80c55f22015-02-01 10:51:23 +0000109#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein840a0dd2016-06-24 23:32:02 +0000110#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman7ef349f2016-06-03 22:54:26 +0000111#include "llvm/Transforms/Scalar/GVN.h"
Davide Italianod4b40fa2016-06-14 00:49:23 +0000112#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruthc68d25f2017-01-11 09:43:56 +0000113#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Dasa55495a2016-06-05 18:01:19 +0000114#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev116f1ad2018-03-15 11:01:19 +0000115#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruthb2b950d2018-06-29 23:36:03 +0000116#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva9897e752016-06-14 00:51:09 +0000117#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chene06fe022016-07-12 22:42:24 +0000118#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruthc68d25f2017-01-11 09:43:56 +0000119#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnsonf970c6e2016-08-13 04:11:27 +0000120#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limfa907d32016-07-14 18:28:29 +0000121#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemet9b7ecbe2016-07-18 16:29:27 +0000122#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chen2ba4d7a2016-07-12 18:45:51 +0000123#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruth77818502018-05-25 01:32:36 +0000124#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruth90fe7e72017-01-27 01:32:26 +0000125#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruthc68d25f2017-01-11 09:43:56 +0000126#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko1dd101b2017-01-25 16:00:44 +0000127#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bogner0b059c12016-05-03 22:02:31 +0000128#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognercc5bcb52016-05-03 21:47:32 +0000129#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruth017c62c2017-01-20 08:42:19 +0000130#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chene7eb2d52016-07-18 21:41:50 +0000131#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Greene1012712018-07-01 12:47:30 +0000132#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvad8c90ea2016-07-19 23:54:23 +0000133#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano74309892016-05-13 22:52:35 +0000134#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruthd4f6d112015-01-24 11:13:02 +0000135#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kuperstein093715a2016-07-28 22:08:41 +0000136#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevc05ba542018-12-07 14:39:46 +0000137#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silvacf989e52016-06-14 02:44:55 +0000138#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianoe92bed32016-06-17 19:10:09 +0000139#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi3a4fa312016-07-21 22:28:52 +0000140#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoee1439d2016-12-22 16:35:02 +0000141#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano613d8072016-05-25 23:38:53 +0000142#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc943cfa2016-04-26 23:39:29 +0000143#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeevf1b0fdf2017-12-15 09:32:11 +0000144#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italianod77d4c02016-05-18 15:18:25 +0000145#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruthe73e5b42015-09-12 09:09:14 +0000146#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmencdf701a2018-11-21 14:00:17 +0000147#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1d4cf6e2017-04-27 18:45:20 +0000148#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruth6a1ce8e2015-12-27 08:13:45 +0000149#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bogner9d0b7e92016-04-22 19:54:10 +0000150#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruth6efdd0f2017-11-28 11:32:31 +0000151#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kuperstein3a6d4372016-08-01 21:48:33 +0000152#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silvaf79d9782016-07-06 23:48:41 +0000153#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse9a395de2018-12-12 17:32:52 +0000154#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li438355c2016-06-15 21:51:30 +0000155#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mia6c7a032016-07-22 18:04:25 +0000156#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson1f630242019-01-04 19:04:54 +0000157#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborg5765d842017-11-14 21:09:45 +0000158#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Raman33933df2016-06-09 19:44:46 +0000159#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xufe89a6b2016-10-18 21:36:27 +0000160#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianofff81b22016-07-09 03:03:01 +0000161#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein69f04072016-08-12 17:28:27 +0000162#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italiano84645e02016-06-14 03:22:22 +0000163#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini8dff0d82016-09-16 16:56:30 +0000164#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kupersteinb3391842016-07-25 20:52:00 +0000165#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavinb2bc0c52018-12-07 08:23:37 +0000166#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silva89419a62016-07-09 22:56:50 +0000167#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silvaeb2d4252016-07-09 03:11:29 +0000168#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italiano84645e02016-06-14 03:22:22 +0000169
Chandler Carruth4e728be2014-01-11 08:16:35 +0000170using namespace llvm;
171
Chandler Carruth1f7ef682017-02-12 05:38:04 +0000172static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
173 cl::ReallyHidden, cl::init(4));
Xinliang David Lib9e09152017-05-22 16:41:57 +0000174static cl::opt<bool>
175 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
176 cl::Hidden, cl::ZeroOrMore,
177 cl::desc("Run Partial inlinining pass"));
Chandler Carruth1f7ef682017-02-12 05:38:04 +0000178
Davide Italianoefb6b102017-05-22 23:41:40 +0000179static cl::opt<bool>
Davide Italianod88c7f02017-05-22 23:47:11 +0000180 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italianoefb6b102017-05-22 23:41:40 +0000181 cl::Hidden, cl::ZeroOrMore,
182 cl::desc("Run NewGVN instead of GVN"));
183
Geoff Berry47e23552017-06-10 15:20:03 +0000184static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry607969f2017-06-27 22:25:02 +0000185 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
186 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry47e23552017-06-10 15:20:03 +0000187
Chandler Carruthbde56a92017-04-27 00:28:03 +0000188static cl::opt<bool> EnableGVNHoist(
Eric Christopher2f730992018-10-01 18:57:08 +0000189 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
190 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthbde56a92017-04-27 00:28:03 +0000191
Davide Italiano653044e2017-06-03 23:18:29 +0000192static cl::opt<bool> EnableGVNSink(
193 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
194 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
195
David Greene1012712018-07-01 12:47:30 +0000196static cl::opt<bool> EnableUnrollAndJam(
197 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
198 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
199
Easwaran Raman283d9782018-01-09 19:39:35 +0000200static cl::opt<bool> EnableSyntheticCounts(
201 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
202 cl::desc("Run synthetic function entry count generation "
203 "pass"));
204
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000205static Regex DefaultAliasRegex(
206 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruthf7ae2f52016-02-28 22:16:03 +0000207
Hiroshi Yamauchic38c8502018-09-04 17:19:13 +0000208static cl::opt<bool>
209 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
210 cl::desc("Enable control height reduction optimization (CHR)"));
211
Aditya Kumarf7ae0df2018-10-03 05:55:20 +0000212extern cl::opt<bool> EnableHotColdSplit;
213
Chandler Carruth2ffea512016-12-22 06:59:15 +0000214static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
215 switch (Level) {
216 case PassBuilder::O0:
217 case PassBuilder::O1:
218 case PassBuilder::O2:
219 case PassBuilder::O3:
220 return false;
221
222 case PassBuilder::Os:
223 case PassBuilder::Oz:
224 return true;
225 }
226 llvm_unreachable("Invalid optimization level!");
227}
228
Chandler Carruth4e728be2014-01-11 08:16:35 +0000229namespace {
230
Adrian Prantl26b584c2018-05-01 15:54:18 +0000231/// No-op module pass which does nothing.
Chandler Carruth4e728be2014-01-11 08:16:35 +0000232struct NoOpModulePass {
Sean Silva2fb9a982016-08-09 00:28:38 +0000233 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth04d0fe92016-06-17 00:11:01 +0000234 return PreservedAnalyses::all();
235 }
Chandler Carruthb56749c2014-01-11 11:52:05 +0000236 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth4e728be2014-01-11 08:16:35 +0000237};
238
Adrian Prantl26b584c2018-05-01 15:54:18 +0000239/// No-op module analysis.
Chandler Carruth18e9a2b2016-03-11 10:33:22 +0000240class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
241 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruth33d56812016-11-23 17:53:26 +0000242 static AnalysisKey Key;
Chandler Carruthe95015f2016-03-11 10:22:49 +0000243
244public:
Chandler Carruth5b12a2f2015-01-06 02:50:06 +0000245 struct Result {};
Sean Silva2fb9a982016-08-09 00:28:38 +0000246 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth5b12a2f2015-01-06 02:50:06 +0000247 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth5b12a2f2015-01-06 02:50:06 +0000248};
249
Adrian Prantl26b584c2018-05-01 15:54:18 +0000250/// No-op CGSCC pass which does nothing.
Chandler Carruth57418d82014-04-21 11:12:00 +0000251struct NoOpCGSCCPass {
Chandler Carruth377af8d2016-08-24 09:37:14 +0000252 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
253 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth57418d82014-04-21 11:12:00 +0000254 return PreservedAnalyses::all();
255 }
256 static StringRef name() { return "NoOpCGSCCPass"; }
257};
258
Adrian Prantl26b584c2018-05-01 15:54:18 +0000259/// No-op CGSCC analysis.
Chandler Carruth18e9a2b2016-03-11 10:33:22 +0000260class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
261 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruth33d56812016-11-23 17:53:26 +0000262 static AnalysisKey Key;
Chandler Carruthe95015f2016-03-11 10:22:49 +0000263
264public:
Chandler Carruth5b12a2f2015-01-06 02:50:06 +0000265 struct Result {};
Chandler Carruth377af8d2016-08-24 09:37:14 +0000266 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth04d0fe92016-06-17 00:11:01 +0000267 return Result();
268 }
Chandler Carruth5b12a2f2015-01-06 02:50:06 +0000269 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth5b12a2f2015-01-06 02:50:06 +0000270};
271
Adrian Prantl26b584c2018-05-01 15:54:18 +0000272/// No-op function pass which does nothing.
Chandler Carruthe7687652014-01-12 09:34:22 +0000273struct NoOpFunctionPass {
Sean Silva20b343c2016-08-09 00:28:15 +0000274 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth04d0fe92016-06-17 00:11:01 +0000275 return PreservedAnalyses::all();
276 }
Chandler Carruthe7687652014-01-12 09:34:22 +0000277 static StringRef name() { return "NoOpFunctionPass"; }
278};
279
Adrian Prantl26b584c2018-05-01 15:54:18 +0000280/// No-op function analysis.
Chandler Carruth18e9a2b2016-03-11 10:33:22 +0000281class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
282 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruth33d56812016-11-23 17:53:26 +0000283 static AnalysisKey Key;
Chandler Carruthe95015f2016-03-11 10:22:49 +0000284
285public:
Chandler Carruth5b12a2f2015-01-06 02:50:06 +0000286 struct Result {};
Sean Silva20b343c2016-08-09 00:28:15 +0000287 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth5b12a2f2015-01-06 02:50:06 +0000288 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth5b12a2f2015-01-06 02:50:06 +0000289};
290
Adrian Prantl26b584c2018-05-01 15:54:18 +0000291/// No-op loop pass which does nothing.
Justin Bognerda5e9242016-02-25 07:23:08 +0000292struct NoOpLoopPass {
Chandler Carruthd27a39a2017-01-11 06:23:21 +0000293 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
294 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth04d0fe92016-06-17 00:11:01 +0000295 return PreservedAnalyses::all();
296 }
Justin Bognerda5e9242016-02-25 07:23:08 +0000297 static StringRef name() { return "NoOpLoopPass"; }
298};
299
Adrian Prantl26b584c2018-05-01 15:54:18 +0000300/// No-op loop analysis.
Chandler Carruth18e9a2b2016-03-11 10:33:22 +0000301class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
302 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruth33d56812016-11-23 17:53:26 +0000303 static AnalysisKey Key;
Chandler Carruthe95015f2016-03-11 10:22:49 +0000304
305public:
Justin Bognerda5e9242016-02-25 07:23:08 +0000306 struct Result {};
Chandler Carruthd27a39a2017-01-11 06:23:21 +0000307 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
308 return Result();
309 }
Justin Bognerda5e9242016-02-25 07:23:08 +0000310 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognerda5e9242016-02-25 07:23:08 +0000311};
312
Chandler Carruth33d56812016-11-23 17:53:26 +0000313AnalysisKey NoOpModuleAnalysis::Key;
314AnalysisKey NoOpCGSCCAnalysis::Key;
315AnalysisKey NoOpFunctionAnalysis::Key;
316AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthe95015f2016-03-11 10:22:49 +0000317
Chandler Carruth4e728be2014-01-11 08:16:35 +0000318} // End anonymous namespace.
319
Philip Pfaffe19045612017-07-10 10:57:55 +0000320void PassBuilder::invokePeepholeEPCallbacks(
321 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
322 for (auto &C : PeepholeEPCallbacks)
323 C(FPM, Level);
324}
325
Chandler Carruth23491362015-03-07 09:02:36 +0000326void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruthbd6882c2016-06-17 07:15:29 +0000327#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth67a41f02016-02-18 09:45:17 +0000328 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruth2bbc5ab2015-01-06 02:21:37 +0000329#include "PassRegistry.def"
Philip Pfaffe19045612017-07-10 10:57:55 +0000330
331 for (auto &C : ModuleAnalysisRegistrationCallbacks)
332 C(MAM);
Chandler Carruth2bbc5ab2015-01-06 02:21:37 +0000333}
334
Chandler Carruth23491362015-03-07 09:02:36 +0000335void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruthbd6882c2016-06-17 07:15:29 +0000336#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth67a41f02016-02-18 09:45:17 +0000337 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruth2bbc5ab2015-01-06 02:21:37 +0000338#include "PassRegistry.def"
Philip Pfaffe19045612017-07-10 10:57:55 +0000339
340 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
341 C(CGAM);
Chandler Carruth2bbc5ab2015-01-06 02:21:37 +0000342}
343
Chandler Carruth23491362015-03-07 09:02:36 +0000344void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruthbd6882c2016-06-17 07:15:29 +0000345#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth67a41f02016-02-18 09:45:17 +0000346 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruth2bbc5ab2015-01-06 02:21:37 +0000347#include "PassRegistry.def"
Philip Pfaffe19045612017-07-10 10:57:55 +0000348
349 for (auto &C : FunctionAnalysisRegistrationCallbacks)
350 C(FAM);
Chandler Carruth2bbc5ab2015-01-06 02:21:37 +0000351}
352
Justin Bognerda5e9242016-02-25 07:23:08 +0000353void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruthbd6882c2016-06-17 07:15:29 +0000354#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognerda5e9242016-02-25 07:23:08 +0000355 LAM.registerPass([&] { return CREATE_PASS; });
356#include "PassRegistry.def"
Philip Pfaffe19045612017-07-10 10:57:55 +0000357
358 for (auto &C : LoopAnalysisRegistrationCallbacks)
359 C(LAM);
Justin Bognerda5e9242016-02-25 07:23:08 +0000360}
361
Chandler Carruth2ffea512016-12-22 06:59:15 +0000362FunctionPassManager
363PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen7b5ab7f2017-07-30 04:55:39 +0000364 ThinLTOPhase Phase,
365 bool DebugLogging) {
Chandler Carruth2ffea512016-12-22 06:59:15 +0000366 assert(Level != O0 && "Must request optimizations!");
367 FunctionPassManager FPM(DebugLogging);
368
369 // Form SSA out of local memory accesses after breaking apart aggregates into
370 // scalars.
371 FPM.addPass(SROA());
372
373 // Catch trivial redundancies
Geoff Berry47e23552017-06-10 15:20:03 +0000374 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruth2ffea512016-12-22 06:59:15 +0000375
Davide Italiano9cd1e1f82017-06-01 23:08:14 +0000376 // Hoisting of scalars and load expressions.
377 if (EnableGVNHoist)
378 FPM.addPass(GVNHoistPass());
379
Davide Italiano653044e2017-06-03 23:18:29 +0000380 // Global value numbering based sinking.
381 if (EnableGVNSink) {
382 FPM.addPass(GVNSinkPass());
383 FPM.addPass(SimplifyCFGPass());
384 }
385
Chandler Carruth2ffea512016-12-22 06:59:15 +0000386 // Speculative execution if the target has divergent branches; otherwise nop.
387 FPM.addPass(SpeculativeExecutionPass());
388
389 // Optimize based on known information about branches, and cleanup afterward.
390 FPM.addPass(JumpThreadingPass());
391 FPM.addPass(CorrelatedValuePropagationPass());
392 FPM.addPass(SimplifyCFGPass());
Amjad Aboudc6483fb2018-01-25 12:06:32 +0000393 if (Level == O3)
394 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruth2ffea512016-12-22 06:59:15 +0000395 FPM.addPass(InstCombinePass());
396
397 if (!isOptimizingForSize(Level))
398 FPM.addPass(LibCallsShrinkWrapPass());
399
Philip Pfaffe19045612017-07-10 10:57:55 +0000400 invokePeepholeEPCallbacks(FPM, Level);
401
Rong Xu2a015932017-10-23 22:21:29 +0000402 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
403 // using the size value profile. Don't perform this when optimizing for size.
404 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
405 !isOptimizingForSize(Level))
406 FPM.addPass(PGOMemOPSizeOpt());
407
Chandler Carruth2ffea512016-12-22 06:59:15 +0000408 FPM.addPass(TailCallElimPass());
409 FPM.addPass(SimplifyCFGPass());
410
411 // Form canonically associated expression trees, and simplify the trees using
412 // basic mathematical properties. For example, this will form (nearly)
413 // minimal multiplication trees.
414 FPM.addPass(ReassociatePass());
415
416 // Add the primary loop simplification pipeline.
417 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruthc96b7cb2018-05-30 02:46:45 +0000418 // some function passes in between them. These can and should be removed
419 // and/or replaced by scheduling the loop pass equivalents in the correct
420 // positions. But those equivalent passes aren't powerful enough yet.
421 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
422 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
423 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
424 // `LoopInstSimplify`.
Chandler Carruth2ffea512016-12-22 06:59:15 +0000425 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
426
Chandler Carruthc96b7cb2018-05-30 02:46:45 +0000427 // Simplify the loop body. We do this initially to clean up after other loop
428 // passes run, either when iterating on a loop or on inner loops with
429 // implications on the outer loop.
430 LPM1.addPass(LoopInstSimplifyPass());
431 LPM1.addPass(LoopSimplifyCFGPass());
432
Chandler Carruth2ffea512016-12-22 06:59:15 +0000433 // Rotate Loop - disable header duplication at -Oz
434 LPM1.addPass(LoopRotatePass(Level != Oz));
435 LPM1.addPass(LICMPass());
Chandler Carruth88001202017-05-26 01:24:11 +0000436 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruthe1c01cc2017-01-26 23:21:17 +0000437 LPM2.addPass(IndVarSimplifyPass());
438 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe19045612017-07-10 10:57:55 +0000439
440 for (auto &C : LateLoopOptimizationsEPCallbacks)
441 C(LPM2, Level);
442
Chandler Carruthe1c01cc2017-01-26 23:21:17 +0000443 LPM2.addPass(LoopDeletionPass());
Dehao Chen7b5ab7f2017-07-30 04:55:39 +0000444 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen59bf0ba2017-07-07 20:53:10 +0000445 // because it changes IR to makes profile annotation in back compile
446 // inaccurate.
Dehao Chen7b5ab7f2017-07-30 04:55:39 +0000447 if (Phase != ThinLTOPhase::PreLink ||
448 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnson99dd11f2017-08-02 20:35:29 +0000449 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruthe1c01cc2017-01-26 23:21:17 +0000450
Philip Pfaffe19045612017-07-10 10:57:55 +0000451 for (auto &C : LoopOptimizerEndEPCallbacks)
452 C(LPM2, Level);
453
Chandler Carruth88c0fa92017-02-09 23:54:57 +0000454 // We provide the opt remark emitter pass for LICM to use. We only need to do
455 // this once as it is immutable.
456 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeevffbb3d02017-12-29 08:16:06 +0000457 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruth2ffea512016-12-22 06:59:15 +0000458 FPM.addPass(SimplifyCFGPass());
459 FPM.addPass(InstCombinePass());
Fedor Sergeevffbb3d02017-12-29 08:16:06 +0000460 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruth2ffea512016-12-22 06:59:15 +0000461
462 // Eliminate redundancies.
463 if (Level != O1) {
464 // These passes add substantial compile time so skip them at O1.
465 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italianoefb6b102017-05-22 23:41:40 +0000466 if (RunNewGVN)
467 FPM.addPass(NewGVNPass());
468 else
469 FPM.addPass(GVN());
Chandler Carruth2ffea512016-12-22 06:59:15 +0000470 }
471
472 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
473 FPM.addPass(MemCpyOptPass());
474
475 // Sparse conditional constant propagation.
476 // FIXME: It isn't clear why we do this *after* loop passes rather than
477 // before...
478 FPM.addPass(SCCPPass());
479
480 // Delete dead bit computations (instcombine runs after to fold away the dead
481 // computations, and then ADCE will run later to exploit any new DCE
482 // opportunities that creates).
483 FPM.addPass(BDCEPass());
484
485 // Run instcombine after redundancy and dead bit elimination to exploit
486 // opportunities opened up by them.
487 FPM.addPass(InstCombinePass());
Philip Pfaffe19045612017-07-10 10:57:55 +0000488 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruth2ffea512016-12-22 06:59:15 +0000489
490 // Re-consider control flow based optimizations after redundancy elimination,
491 // redo DCE, etc.
492 FPM.addPass(JumpThreadingPass());
493 FPM.addPass(CorrelatedValuePropagationPass());
494 FPM.addPass(DSEPass());
Fedor Sergeevffbb3d02017-12-29 08:16:06 +0000495 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruth2ffea512016-12-22 06:59:15 +0000496
Philip Pfaffe19045612017-07-10 10:57:55 +0000497 for (auto &C : ScalarOptimizerLateEPCallbacks)
498 C(FPM, Level);
499
Chandler Carruth2ffea512016-12-22 06:59:15 +0000500 // Finally, do an expensive DCE pass to catch all the dead code exposed by
501 // the simplifications and basic cleanup after all the simplifications.
502 FPM.addPass(ADCEPass());
503 FPM.addPass(SimplifyCFGPass());
504 FPM.addPass(InstCombinePass());
Philip Pfaffe19045612017-07-10 10:57:55 +0000505 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruth2ffea512016-12-22 06:59:15 +0000506
Hiroshi Yamauchic38c8502018-09-04 17:19:13 +0000507 if (EnableCHR && Level == O3 && PGOOpt &&
508 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
509 FPM.addPass(ControlHeightReductionPass());
510
Chandler Carruth2ffea512016-12-22 06:59:15 +0000511 return FPM;
512}
513
Philip Pfaffe19045612017-07-10 10:57:55 +0000514void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
515 PassBuilder::OptimizationLevel Level,
516 bool RunProfileGen,
517 std::string ProfileGenFile,
Richard Smith63ec2562018-10-10 23:13:47 +0000518 std::string ProfileUseFile,
519 std::string ProfileRemappingFile) {
Davide Italiano0125c632017-02-13 15:26:22 +0000520 // Generally running simplification passes and the inliner with an high
521 // threshold results in smaller executables, but there may be cases where
522 // the size grows, so let's be conservative here and skip this simplification
523 // at -Os/Oz.
524 if (!isOptimizingForSize(Level)) {
525 InlineParams IP;
526
527 // In the old pass manager, this is a cl::opt. Should still this be one?
528 IP.DefaultThreshold = 75;
529
530 // FIXME: The hint threshold has the same value used by the regular inliner.
531 // This should probably be lowered after performance testing.
532 // FIXME: this comment is cargo culted from the old pass manager, revisit).
533 IP.HintThreshold = 325;
534
535 CGSCCPassManager CGPipeline(DebugLogging);
536
537 CGPipeline.addPass(InlinerPass(IP));
538
539 FunctionPassManager FPM;
540 FPM.addPass(SROA());
541 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
542 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
543 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe19045612017-07-10 10:57:55 +0000544 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano0125c632017-02-13 15:26:22 +0000545
Davide Italiano0125c632017-02-13 15:26:22 +0000546 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
547
548 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
549 }
550
Chandler Carruth4fde77f2017-05-25 07:15:09 +0000551 // Delete anything that is now dead to make sure that we don't instrument
552 // dead code. Instrumentation can end up keeping dead code around and
553 // dramatically increase code size.
554 MPM.addPass(GlobalDCEPass());
555
Davide Italiano0125c632017-02-13 15:26:22 +0000556 if (RunProfileGen) {
557 MPM.addPass(PGOInstrumentationGen());
558
Xinliang David Li0a14fbb2017-06-25 00:26:43 +0000559 FunctionPassManager FPM;
Fedor Sergeevffbb3d02017-12-29 08:16:06 +0000560 FPM.addPass(
561 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Li0a14fbb2017-06-25 00:26:43 +0000562 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
563
Davide Italiano0125c632017-02-13 15:26:22 +0000564 // Add the profile lowering pass.
565 InstrProfOptions Options;
566 if (!ProfileGenFile.empty())
567 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Li0a14fbb2017-06-25 00:26:43 +0000568 Options.DoCounterPromotion = true;
Davide Italiano0125c632017-02-13 15:26:22 +0000569 MPM.addPass(InstrProfiling(Options));
570 }
571
572 if (!ProfileUseFile.empty())
Richard Smith63ec2562018-10-10 23:13:47 +0000573 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano0125c632017-02-13 15:26:22 +0000574}
575
Easwaran Raman44596762017-06-28 13:33:49 +0000576static InlineParams
577getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
578 auto O3 = PassBuilder::O3;
579 unsigned OptLevel = Level > O3 ? 2 : Level;
580 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
581 return getInlineParams(OptLevel, SizeLevel);
582}
583
Chandler Carruth2ffea512016-12-22 06:59:15 +0000584ModulePassManager
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000585PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen7b5ab7f2017-07-30 04:55:39 +0000586 ThinLTOPhase Phase,
587 bool DebugLogging) {
Chandler Carruth2ffea512016-12-22 06:59:15 +0000588 ModulePassManager MPM(DebugLogging);
589
Chandler Carruth2ffea512016-12-22 06:59:15 +0000590 // Do basic inference of function attributes from known properties of system
591 // libraries and other oracles.
592 MPM.addPass(InferFunctionAttrsPass());
593
594 // Create an early function pass manager to cleanup the output of the
595 // frontend.
Chandler Carruthf7ae2f52016-02-28 22:16:03 +0000596 FunctionPassManager EarlyFPM(DebugLogging);
597 EarlyFPM.addPass(SimplifyCFGPass());
598 EarlyFPM.addPass(SROA());
599 EarlyFPM.addPass(EarlyCSEPass());
600 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Limf4beb752017-11-03 20:41:16 +0000601 if (Level == O3)
602 EarlyFPM.addPass(CallSiteSplittingPass());
603
Dehao Chen6858db52017-08-07 20:23:20 +0000604 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
605 // to convert bitcast to direct calls so that they can be inlined during the
606 // profile annotation prepration step.
607 // More details about SamplePGO design can be found in:
608 // https://research.google.com/pubs/pub45290.html
609 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
610 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
611 Phase == ThinLTOPhase::PostLink)
612 EarlyFPM.addPass(InstCombinePass());
Chandler Carruthf7ae2f52016-02-28 22:16:03 +0000613 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruth2ffea512016-12-22 06:59:15 +0000614
Dehao Chen6858db52017-08-07 20:23:20 +0000615 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
616 // Annotate sample profile right after early FPM to ensure freshness of
617 // the debug info.
Dehao Chen61b70462017-10-01 05:24:51 +0000618 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
Richard Smith63ec2562018-10-10 23:13:47 +0000619 PGOOpt->ProfileRemappingFile,
Dehao Chen61b70462017-10-01 05:24:51 +0000620 Phase == ThinLTOPhase::PreLink));
Dehao Chen6858db52017-08-07 20:23:20 +0000621 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
622 // for the profile annotation to be accurate in the ThinLTO backend.
623 if (Phase != ThinLTOPhase::PreLink)
624 // We perform early indirect call promotion here, before globalopt.
625 // This is important for the ThinLTO backend phase because otherwise
626 // imported available_externally functions look unreferenced and are
627 // removed.
628 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
629 true));
630 }
631
Malcolm Parsons5fc96282018-01-24 10:33:39 +0000632 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruth2ffea512016-12-22 06:59:15 +0000633 // and prior to optimizing globals.
634 // FIXME: This position in the pipeline hasn't been carefully considered in
635 // years, it should be re-analyzed.
636 MPM.addPass(IPSCCPPass());
637
Matthew Simpson7d6a3b62017-10-25 13:40:08 +0000638 // Attach metadata to indirect call sites indicating the set of functions
639 // they may target at run-time. This should follow IPSCCP.
640 MPM.addPass(CalledValuePropagationPass());
641
Chandler Carruth2ffea512016-12-22 06:59:15 +0000642 // Optimize globals to try and fold them into constants.
643 MPM.addPass(GlobalOptPass());
644
645 // Promote any localized globals to SSA registers.
646 // FIXME: Should this instead by a run of SROA?
647 // FIXME: We should probably run instcombine and simplify-cfg afterward to
648 // delete control flows that are dead once globals have been folded to
649 // constants.
650 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
651
652 // Remove any dead arguments exposed by cleanups and constand folding
653 // globals.
654 MPM.addPass(DeadArgumentEliminationPass());
655
656 // Create a small function pass pipeline to cleanup after all the global
657 // optimizations.
658 FunctionPassManager GlobalCleanupPM(DebugLogging);
659 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe19045612017-07-10 10:57:55 +0000660 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
661
Chandler Carruth2ffea512016-12-22 06:59:15 +0000662 GlobalCleanupPM.addPass(SimplifyCFGPass());
663 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
664
Dehao Chencbd28412017-08-02 01:28:31 +0000665 // Add all the requested passes for instrumentation PGO, if requested.
666 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
667 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
668 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith63ec2562018-10-10 23:13:47 +0000669 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
670 PGOOpt->ProfileRemappingFile);
Dehao Chencbd28412017-08-02 01:28:31 +0000671 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000672 }
Davide Italiano0125c632017-02-13 15:26:22 +0000673
Easwaran Raman283d9782018-01-09 19:39:35 +0000674 // Synthesize function entry counts for non-PGO compilation.
675 if (EnableSyntheticCounts && !PGOOpt)
676 MPM.addPass(SyntheticCountsPropagation());
677
Chandler Carruth9c241092017-02-12 05:34:04 +0000678 // Require the GlobalsAA analysis for the module so we can query it within
679 // the CGSCC pipeline.
680 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruth2ffea512016-12-22 06:59:15 +0000681
Easwaran Ramande37aad2017-05-04 16:58:45 +0000682 // Require the ProfileSummaryAnalysis for the module so we can query it within
683 // the inliner pass.
684 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
685
Chandler Carruth2ffea512016-12-22 06:59:15 +0000686 // Now begin the main postorder CGSCC pipeline.
687 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
688 // manager and trying to emulate its precise behavior. Much of this doesn't
689 // make a lot of sense and we should revisit the core CGSCC structure.
690 CGSCCPassManager MainCGPipeline(DebugLogging);
691
692 // Note: historically, the PruneEH pass was run first to deduce nounwind and
693 // generally clean up exception handling overhead. It isn't clear this is
694 // valuable as the inliner doesn't currently care whether it is inlining an
695 // invoke or a call.
696
697 // Run the inliner first. The theory is that we are walking bottom-up and so
698 // the callees have already been fully optimized, and we want to inline them
699 // into the callers so that our optimizations can reflect that.
Dehao Chen7b5ab7f2017-07-30 04:55:39 +0000700 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen59bf0ba2017-07-07 20:53:10 +0000701 // because it makes profile annotation in the backend inaccurate.
702 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen7b5ab7f2017-07-30 04:55:39 +0000703 if (Phase == ThinLTOPhase::PreLink &&
704 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen59bf0ba2017-07-07 20:53:10 +0000705 IP.HotCallSiteThreshold = 0;
706 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruth2ffea512016-12-22 06:59:15 +0000707
708 // Now deduce any function attributes based in the current code.
709 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
710
Chandler Carruth88c0fa92017-02-09 23:54:57 +0000711 // When at O3 add argument promotion to the pass pipeline.
712 // FIXME: It isn't at all clear why this should be limited to O3.
713 if (Level == O3)
714 MainCGPipeline.addPass(ArgumentPromotionPass());
715
Chandler Carruth2ffea512016-12-22 06:59:15 +0000716 // Lastly, add the core function simplification pipeline nested inside the
717 // CGSCC walk.
718 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen7b5ab7f2017-07-30 04:55:39 +0000719 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruth2ffea512016-12-22 06:59:15 +0000720
Teresa Johnson70fc21b2018-10-23 22:57:40 +0000721 // We only want to do hot cold splitting once for ThinLTO, during the
722 // post-link ThinLTO.
723 if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink)
Aditya Kumar0ee7db42018-10-21 18:11:56 +0000724 MPM.addPass(HotColdSplittingPass());
725
Philip Pfaffe19045612017-07-10 10:57:55 +0000726 for (auto &C : CGSCCOptimizerLateEPCallbacks)
727 C(MainCGPipeline, Level);
728
Chandler Carruth1f7ef682017-02-12 05:38:04 +0000729 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
730 // to detect when we devirtualize indirect calls and iterate the SCC passes
731 // in that case to try and catch knock-on inlining or function attrs
732 // opportunities. Then we add it to the module pipeline by walking the SCCs
733 // in postorder (or bottom-up).
Chandler Carruth2ffea512016-12-22 06:59:15 +0000734 MPM.addPass(
Chandler Carruth1f7ef682017-02-12 05:38:04 +0000735 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth83bfb552017-08-11 05:47:13 +0000736 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruth2ffea512016-12-22 06:59:15 +0000737
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000738 return MPM;
739}
740
741ModulePassManager
742PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
743 bool DebugLogging) {
744 ModulePassManager MPM(DebugLogging);
745
746 // Optimize globals now that the module is fully simplified.
747 MPM.addPass(GlobalOptPass());
Davide Italiano6bfe1d92017-10-05 18:36:01 +0000748 MPM.addPass(GlobalDCEPass());
Chandler Carruth2ffea512016-12-22 06:59:15 +0000749
Xinliang David Lib9e09152017-05-22 16:41:57 +0000750 // Run partial inlining pass to partially inline functions that have
751 // large bodies.
752 if (RunPartialInlining)
753 MPM.addPass(PartialInlinerPass());
754
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000755 // Remove avail extern fns and globals definitions since we aren't compiling
756 // an object file for later LTO. For LTO we want to preserve these so they
757 // are eligible for inlining at link-time. Note if they are unreferenced they
758 // will be removed by GlobalDCE later, so this only impacts referenced
759 // available externally globals. Eventually they will be suppressed during
760 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
761 // may make globals referenced by available external functions dead and saves
762 // running remaining passes on the eliminated functions.
Chandler Carruth2ffea512016-12-22 06:59:15 +0000763 MPM.addPass(EliminateAvailableExternallyPass());
764
765 // Do RPO function attribute inference across the module to forward-propagate
766 // attributes where applicable.
767 // FIXME: Is this really an optimization rather than a canonicalization?
768 MPM.addPass(ReversePostOrderFunctionAttrsPass());
769
Chandler Carruth9c241092017-02-12 05:34:04 +0000770 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruth2ffea512016-12-22 06:59:15 +0000771 // useful as the above will have inlined, DCE'ed, and function-attr
772 // propagated everything. We should at this point have a reasonably minimal
773 // and richly annotated call graph. By computing aliasing and mod/ref
774 // information for all local globals here, the late loop passes and notably
775 // the vectorizer will be able to use them to help recognize vectorizable
776 // memory operations.
Chandler Carruth9c241092017-02-12 05:34:04 +0000777 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruth2ffea512016-12-22 06:59:15 +0000778
779 FunctionPassManager OptimizePM(DebugLogging);
780 OptimizePM.addPass(Float2IntPass());
781 // FIXME: We need to run some loop optimizations to re-rotate loops after
782 // simplify-cfg and others undo their rotation.
783
784 // Optimize the loop execution. These passes operate on entire loop nests
785 // rather than on each loop in an inside-out manner, and so they are actually
786 // function passes.
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000787
Philip Pfaffe19045612017-07-10 10:57:55 +0000788 for (auto &C : VectorizerStartEPCallbacks)
789 C(OptimizePM, Level);
790
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000791 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeevffbb3d02017-12-29 08:16:06 +0000792 OptimizePM.addPass(
793 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000794
795 // Distribute loops to allow partial vectorization. I.e. isolate dependences
796 // into separate loop that would otherwise inhibit vectorization. This is
797 // currently only performed for loops marked with the metadata
798 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruth2ffea512016-12-22 06:59:15 +0000799 OptimizePM.addPass(LoopDistributePass());
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000800
801 // Now run the core loop vectorizer.
Chandler Carruth2ffea512016-12-22 06:59:15 +0000802 OptimizePM.addPass(LoopVectorizePass());
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000803
Chandler Carruth90fe7e72017-01-27 01:32:26 +0000804 // Eliminate loads by forwarding stores from the previous iteration to loads
805 // of the current iteration.
806 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000807
808 // Cleanup after the loop optimization passes.
Chandler Carruth2ffea512016-12-22 06:59:15 +0000809 OptimizePM.addPass(InstCombinePass());
810
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000811 // Now that we've formed fast to execute loop structures, we do further
812 // optimizations. These are run afterward as they might block doing complex
813 // analyses and transforms such as what are needed for loop vectorization.
814
Sanjay Patel70348702017-12-14 22:05:20 +0000815 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
816 // GVN, loop transforms, and others have already run, so it's now better to
817 // convert to more optimized IR using more aggressive simplify CFG options.
818 // The extra sinking transform can create larger basic blocks, so do this
819 // before SLP vectorization.
820 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
821 forwardSwitchCondToPhi(true).
822 convertSwitchToLookupTable(true).
823 needCanonicalLoops(false).
824 sinkCommonInsts(true)));
825
Chandler Carruth2ffea512016-12-22 06:59:15 +0000826 // Optimize parallel scalar instruction chains into SIMD instructions.
827 OptimizePM.addPass(SLPVectorizerPass());
828
Chandler Carruth2ffea512016-12-22 06:59:15 +0000829 OptimizePM.addPass(InstCombinePass());
830
831 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000832 // execution resources of an out-of-order processor. We also then need to
833 // clean up redundancies and loop invariant code.
834 // FIXME: It would be really good to use a loop-integrated instruction
835 // combiner for cleanup here so that the unrolling and LICM can be pipelined
836 // across the loop nests.
David Greene1012712018-07-01 12:47:30 +0000837 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
838 if (EnableUnrollAndJam) {
839 OptimizePM.addPass(
840 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
841 }
Fedor Sergeev2f9c8a02018-10-31 14:33:14 +0000842 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse9a395de2018-12-12 17:32:52 +0000843 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000844 OptimizePM.addPass(InstCombinePass());
Chandler Carruth88c0fa92017-02-09 23:54:57 +0000845 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeevffbb3d02017-12-29 08:16:06 +0000846 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruth2ffea512016-12-22 06:59:15 +0000847
848 // Now that we've vectorized and unrolled loops, we may have more refined
849 // alignment information, try to re-derive it here.
850 OptimizePM.addPass(AlignmentFromAssumptionsPass());
851
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000852 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
853 // canonicalization pass that enables other optimizations. As a result,
854 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
855 // result too early.
856 OptimizePM.addPass(LoopSinkPass());
857
858 // And finally clean up LCSSA form before generating code.
Chandler Carruthb2b950d2018-06-29 23:36:03 +0000859 OptimizePM.addPass(InstSimplifyPass());
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000860
Sanjay Patel193e8982017-09-09 13:38:18 +0000861 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
862 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
863 // flattening of blocks.
864 OptimizePM.addPass(DivRemPairsPass());
865
Filipe Cabecinhas70c9b6a2017-04-26 12:02:41 +0000866 // LoopSink (and other loop passes since the last simplifyCFG) might have
867 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
868 OptimizePM.addPass(SimplifyCFGPass());
869
Chandler Carruth6efdd0f2017-11-28 11:32:31 +0000870 // Optimize PHIs by speculating around them when profitable. Note that this
871 // pass needs to be run after any PRE or similar pass as it is essentially
872 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
873 OptimizePM.addPass(SpeculateAroundPHIsPass());
874
Philip Pfaffe0c20a4d2018-11-12 11:17:07 +0000875 for (auto &C : OptimizerLastEPCallbacks)
876 C(OptimizePM, Level);
877
Chandler Carruthf8e4cd6c2017-01-27 00:50:21 +0000878 // Add the core optimizing pipeline.
Chandler Carruth2ffea512016-12-22 06:59:15 +0000879 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
880
Michael J. Spencer3da6ce52018-07-16 00:28:24 +0000881 MPM.addPass(CGProfilePass());
882
Chandler Carruth2ffea512016-12-22 06:59:15 +0000883 // Now we need to do some global optimization transforms.
884 // FIXME: It would seem like these should come first in the optimization
885 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
886 // ordering here.
887 MPM.addPass(GlobalDCEPass());
888 MPM.addPass(ConstantMergePass());
889
890 return MPM;
Chandler Carruthf7ae2f52016-02-28 22:16:03 +0000891}
892
Chandler Carruth2ffea512016-12-22 06:59:15 +0000893ModulePassManager
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000894PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
895 bool DebugLogging) {
896 assert(Level != O0 && "Must request optimizations for the default pipeline!");
897
898 ModulePassManager MPM(DebugLogging);
899
900 // Force any function attributes we want the rest of the pipeline to observe.
901 MPM.addPass(ForceFunctionAttrsPass());
902
David Blaikie0ac87472018-01-23 01:25:20 +0000903 // Apply module pipeline start EP callback.
904 for (auto &C : PipelineStartEPCallbacks)
905 C(MPM);
906
Dehao Chen6858db52017-08-07 20:23:20 +0000907 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chen04fe17a2017-07-29 04:10:24 +0000908 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
909
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000910 // Add the core simplification pipeline.
Dehao Chen7b5ab7f2017-07-30 04:55:39 +0000911 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
912 DebugLogging));
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000913
914 // Now add the optimization pipeline.
915 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
916
917 return MPM;
918}
919
920ModulePassManager
921PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
922 bool DebugLogging) {
923 assert(Level != O0 && "Must request optimizations for the default pipeline!");
924
925 ModulePassManager MPM(DebugLogging);
926
927 // Force any function attributes we want the rest of the pipeline to observe.
928 MPM.addPass(ForceFunctionAttrsPass());
929
Dehao Chen6858db52017-08-07 20:23:20 +0000930 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chen04fe17a2017-07-29 04:10:24 +0000931 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
932
David Blaikie0ac87472018-01-23 01:25:20 +0000933 // Apply module pipeline start EP callback.
934 for (auto &C : PipelineStartEPCallbacks)
935 C(MPM);
936
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000937 // If we are planning to perform ThinLTO later, we don't bloat the code with
938 // unrolling/vectorization/... now. Just simplify the module as much as we
939 // can.
Dehao Chen7b5ab7f2017-07-30 04:55:39 +0000940 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
941 DebugLogging));
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000942
943 // Run partial inlining pass to partially inline functions that have
944 // large bodies.
945 // FIXME: It isn't clear whether this is really the right place to run this
946 // in ThinLTO. Because there is another canonicalization and simplification
947 // phase that will run after the thin link, running this here ends up with
948 // less information than will be available later and it may grow functions in
949 // ways that aren't beneficial.
950 if (RunPartialInlining)
951 MPM.addPass(PartialInlinerPass());
952
953 // Reduce the size of the IR as much as possible.
954 MPM.addPass(GlobalOptPass());
955
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000956 return MPM;
957}
958
Teresa Johnson2a478d42018-07-19 14:51:32 +0000959ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
960 OptimizationLevel Level, bool DebugLogging,
961 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000962 ModulePassManager MPM(DebugLogging);
963
Teresa Johnson2a478d42018-07-19 14:51:32 +0000964 if (ImportSummary) {
965 // These passes import type identifier resolutions for whole-program
966 // devirtualization and CFI. They must run early because other passes may
967 // disturb the specific instruction patterns that these passes look for,
968 // creating dependencies on resolutions that may not appear in the summary.
969 //
970 // For example, GVN may transform the pattern assume(type.test) appearing in
971 // two basic blocks into assume(phi(type.test, type.test)), which would
972 // transform a dependency on a WPD resolution into a dependency on a type
973 // identifier resolution for CFI.
974 //
975 // Also, WPD has access to more precise information than ICP and can
976 // devirtualize more effectively, so it should operate on the IR first.
977 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
978 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
979 }
980
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000981 // Force any function attributes we want the rest of the pipeline to observe.
982 MPM.addPass(ForceFunctionAttrsPass());
983
984 // During the ThinLTO backend phase we perform early indirect call promotion
985 // here, before globalopt. Otherwise imported available_externally functions
986 // look unreferenced and are removed.
Dehao Chen6858db52017-08-07 20:23:20 +0000987 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
988 // with SamplePGO.
Dehao Chena3b8ce32017-08-10 05:10:32 +0000989 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen6858db52017-08-07 20:23:20 +0000990 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
991 false /* SamplePGO */));
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000992
993 // Add the core simplification pipeline.
Dehao Chen7b5ab7f2017-07-30 04:55:39 +0000994 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
995 DebugLogging));
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000996
997 // Now add the optimization pipeline.
998 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
999
1000 return MPM;
1001}
1002
1003ModulePassManager
Chandler Carruth2ffea512016-12-22 06:59:15 +00001004PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1005 bool DebugLogging) {
1006 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001007 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruth2ffea512016-12-22 06:59:15 +00001008 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001009}
1010
Teresa Johnson2a478d42018-07-19 14:51:32 +00001011ModulePassManager
1012PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1013 ModuleSummaryIndex *ExportSummary) {
Chandler Carruth2ffea512016-12-22 06:59:15 +00001014 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1015 ModulePassManager MPM(DebugLogging);
1016
Xin Tongeb1caa72018-11-15 18:06:42 +00001017 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1018 // Load sample profile before running the LTO optimization pipeline.
1019 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1020 PGOOpt->ProfileRemappingFile,
1021 false /* ThinLTOPhase::PreLink */));
1022 }
1023
Davide Italiano6fe089f2017-01-24 00:57:39 +00001024 // Remove unused virtual tables to improve the quality of code generated by
1025 // whole-program devirtualization and bitset lowering.
1026 MPM.addPass(GlobalDCEPass());
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001027
Davide Italiano6fe089f2017-01-24 00:57:39 +00001028 // Force any function attributes we want the rest of the pipeline to observe.
1029 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruth2ffea512016-12-22 06:59:15 +00001030
Davide Italiano6fe089f2017-01-24 00:57:39 +00001031 // Do basic inference of function attributes from known properties of system
1032 // libraries and other oracles.
1033 MPM.addPass(InferFunctionAttrsPass());
1034
1035 if (Level > 1) {
Jun Bum Limf4beb752017-11-03 20:41:16 +00001036 FunctionPassManager EarlyFPM(DebugLogging);
1037 EarlyFPM.addPass(CallSiteSplittingPass());
1038 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1039
Davide Italiano6fe089f2017-01-24 00:57:39 +00001040 // Indirect call promotion. This should promote all the targets that are
1041 // left by the earlier promotion pass that promotes intra-module targets.
1042 // This two-step promotion is to save the compile time. For LTO, it should
1043 // produce the same result as if we only do promotion here.
Dehao Chenade84072017-06-29 23:33:05 +00001044 MPM.addPass(PGOIndirectCallPromotion(
1045 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano6fe089f2017-01-24 00:57:39 +00001046 // Propagate constants at call sites into the functions they call. This
1047 // opens opportunities for globalopt (and inlining) by substituting function
1048 // pointers passed as arguments to direct uses of functions.
1049 MPM.addPass(IPSCCPPass());
Matthew Simpson7d6a3b62017-10-25 13:40:08 +00001050
1051 // Attach metadata to indirect call sites indicating the set of functions
1052 // they may target at run-time. This should follow IPSCCP.
1053 MPM.addPass(CalledValuePropagationPass());
Davide Italiano6fe089f2017-01-24 00:57:39 +00001054 }
1055
1056 // Now deduce any function attributes based in the current code.
1057 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1058 PostOrderFunctionAttrsPass()));
1059
1060 // Do RPO function attribute inference across the module to forward-propagate
1061 // attributes where applicable.
1062 // FIXME: Is this really an optimization rather than a canonicalization?
1063 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1064
1065 // Use inragne annotations on GEP indices to split globals where beneficial.
1066 MPM.addPass(GlobalSplitPass());
1067
1068 // Run whole program optimization of virtual call when the list of callees
1069 // is fixed.
Teresa Johnson2a478d42018-07-19 14:51:32 +00001070 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano6fe089f2017-01-24 00:57:39 +00001071
1072 // Stop here at -O1.
Teresa Johnson2a478d42018-07-19 14:51:32 +00001073 if (Level == 1) {
1074 // The LowerTypeTestsPass needs to run to lower type metadata and the
1075 // type.test intrinsics. The pass does nothing if CFI is disabled.
1076 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano6fe089f2017-01-24 00:57:39 +00001077 return MPM;
Teresa Johnson2a478d42018-07-19 14:51:32 +00001078 }
Davide Italiano6fe089f2017-01-24 00:57:39 +00001079
1080 // Optimize globals to try and fold them into constants.
1081 MPM.addPass(GlobalOptPass());
1082
1083 // Promote any localized globals to SSA registers.
1084 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1085
1086 // Linking modules together can lead to duplicate global constant, only
1087 // keep one copy of each constant.
1088 MPM.addPass(ConstantMergePass());
1089
1090 // Remove unused arguments from functions.
1091 MPM.addPass(DeadArgumentEliminationPass());
1092
1093 // Reduce the code after globalopt and ipsccp. Both can open up significant
1094 // simplification opportunities, and both can propagate functions through
1095 // function pointers. When this happens, we often have to resolve varargs
1096 // calls, etc, so let instcombine do this.
Philip Pfaffe19045612017-07-10 10:57:55 +00001097 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudc6483fb2018-01-25 12:06:32 +00001098 if (Level == O3)
1099 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe19045612017-07-10 10:57:55 +00001100 PeepholeFPM.addPass(InstCombinePass());
1101 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1102
1103 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano6fe089f2017-01-24 00:57:39 +00001104
1105 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1106 // generally clean up exception handling overhead. It isn't clear this is
1107 // valuable as the inliner doesn't currently care whether it is inlining an
1108 // invoke or a call.
1109 // Run the inliner now.
Easwaran Raman44596762017-06-28 13:33:49 +00001110 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1111 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano6fe089f2017-01-24 00:57:39 +00001112
1113 // Optimize globals again after we ran the inliner.
1114 MPM.addPass(GlobalOptPass());
1115
1116 // Garbage collect dead functions.
1117 // FIXME: Add ArgumentPromotion pass after once it's ported.
1118 MPM.addPass(GlobalDCEPass());
1119
1120 FunctionPassManager FPM(DebugLogging);
Davide Italiano6fe089f2017-01-24 00:57:39 +00001121 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano6fe089f2017-01-24 00:57:39 +00001122 FPM.addPass(InstCombinePass());
Philip Pfaffe19045612017-07-10 10:57:55 +00001123 invokePeepholeEPCallbacks(FPM, Level);
1124
Davide Italiano6fe089f2017-01-24 00:57:39 +00001125 FPM.addPass(JumpThreadingPass());
1126
1127 // Break up allocas
1128 FPM.addPass(SROA());
1129
1130 // Run a few AA driver optimizations here and now to cleanup the code.
1131 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1132
1133 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1134 PostOrderFunctionAttrsPass()));
1135 // FIXME: here we run IP alias analysis in the legacy PM.
1136
1137 FunctionPassManager MainFPM;
1138
1139 // FIXME: once we fix LoopPass Manager, add LICM here.
1140 // FIXME: once we provide support for enabling MLSM, add it here.
1141 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italianoefb6b102017-05-22 23:41:40 +00001142 if (RunNewGVN)
1143 MainFPM.addPass(NewGVNPass());
1144 else
1145 MainFPM.addPass(GVN());
Davide Italiano6fe089f2017-01-24 00:57:39 +00001146
1147 // Remove dead memcpy()'s.
1148 MainFPM.addPass(MemCpyOptPass());
1149
1150 // Nuke dead stores.
1151 MainFPM.addPass(DSEPass());
1152
1153 // FIXME: at this point, we run a bunch of loop passes:
1154 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1155 // loopVectorize. Enable them once the remaining issue with LPM
1156 // are sorted out.
1157
1158 MainFPM.addPass(InstCombinePass());
1159 MainFPM.addPass(SimplifyCFGPass());
1160 MainFPM.addPass(SCCPPass());
1161 MainFPM.addPass(InstCombinePass());
1162 MainFPM.addPass(BDCEPass());
1163
1164 // FIXME: We may want to run SLPVectorizer here.
1165 // After vectorization, assume intrinsics may tell us more
1166 // about pointer alignments.
1167#if 0
1168 MainFPM.add(AlignmentFromAssumptionsPass());
1169#endif
1170
Philip Pfaffe19045612017-07-10 10:57:55 +00001171 // FIXME: Conditionally run LoadCombine here, after it's ported
1172 // (in case we still have this pass, given its questionable usefulness).
1173
Davide Italiano6fe089f2017-01-24 00:57:39 +00001174 MainFPM.addPass(InstCombinePass());
Philip Pfaffe19045612017-07-10 10:57:55 +00001175 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano6fe089f2017-01-24 00:57:39 +00001176 MainFPM.addPass(JumpThreadingPass());
1177 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1178
1179 // Create a function that performs CFI checks for cross-DSO calls with
1180 // targets in the current module.
1181 MPM.addPass(CrossDSOCFIPass());
1182
1183 // Lower type metadata and the type.test intrinsic. This pass supports
1184 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1185 // to be run at link time if CFI is enabled. This pass does nothing if
1186 // CFI is disabled.
Teresa Johnson2a478d42018-07-19 14:51:32 +00001187 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano6fe089f2017-01-24 00:57:39 +00001188
1189 // Add late LTO optimization passes.
1190 // Delete basic blocks, which optimization passes may have killed.
1191 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1192
1193 // Drop bodies of available eternally objects to improve GlobalDCE.
1194 MPM.addPass(EliminateAvailableExternallyPass());
1195
1196 // Now that we have optimized the program, discard unreachable functions.
1197 MPM.addPass(GlobalDCEPass());
1198
1199 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruth2ffea512016-12-22 06:59:15 +00001200 return MPM;
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001201}
1202
Chandler Carruth759dd392016-12-23 20:38:19 +00001203AAManager PassBuilder::buildDefaultAAPipeline() {
1204 AAManager AA;
1205
1206 // The order in which these are registered determines their priority when
1207 // being queried.
1208
1209 // First we register the basic alias analysis that provides the majority of
1210 // per-function local AA logic. This is a stateless, on-demand local set of
1211 // AA techniques.
1212 AA.registerFunctionAnalysis<BasicAA>();
1213
1214 // Next we query fast, specialized alias analyses that wrap IR-embedded
1215 // information about aliasing.
1216 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1217 AA.registerFunctionAnalysis<TypeBasedAA>();
1218
1219 // Add support for querying global aliasing information when available.
Chandler Carruth356e45b2016-12-24 05:11:17 +00001220 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1221 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruth9c241092017-02-12 05:34:04 +00001222 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth759dd392016-12-23 20:38:19 +00001223 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth759dd392016-12-23 20:38:19 +00001224
1225 return AA;
1226}
1227
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001228static Optional<int> parseRepeatPassName(StringRef Name) {
1229 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1230 return None;
1231 int Count;
1232 if (Name.getAsInteger(0, Count) || Count <= 0)
1233 return None;
1234 return Count;
1235}
1236
Chandler Carruth86d53652016-12-28 11:07:33 +00001237static Optional<int> parseDevirtPassName(StringRef Name) {
1238 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1239 return None;
1240 int Count;
1241 if (Name.getAsInteger(0, Count) || Count <= 0)
1242 return None;
1243 return Count;
1244}
1245
Fedor Sergeev4f41c192019-01-10 10:01:53 +00001246static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1247 if (!Name.consume_front(PassName))
1248 return false;
1249 // normal pass name w/o parameters == default parameters
1250 if (Name.empty())
1251 return true;
1252 return Name.startswith("<") && Name.endswith(">");
1253}
1254
1255namespace {
1256
1257/// This performs customized parsing of pass name with parameters.
1258///
1259/// We do not need parametrization of passes in textual pipeline very often,
1260/// yet on a rare occasion ability to specify parameters right there can be
1261/// useful.
1262///
1263/// \p Name - parameterized specification of a pass from a textual pipeline
1264/// is a string in a form of :
1265/// PassName '<' parameter-list '>'
1266///
1267/// Parameter list is being parsed by the parser callable argument, \p Parser,
1268/// It takes a string-ref of parameters and returns either StringError or a
1269/// parameter list in a form of a custom parameters type, all wrapped into
1270/// Expected<> template class.
1271///
1272template <typename ParametersParseCallableT>
1273auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1274 StringRef PassName) -> decltype(Parser(StringRef{})) {
1275 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1276
1277 StringRef Params = Name;
1278 if (!Params.consume_front(PassName)) {
1279 assert(false &&
1280 "unable to strip pass name from parametrized pass specification");
1281 }
1282 if (Params.empty())
1283 return ParametersT{};
1284 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1285 assert(false && "invalid format for parametrized pass name");
1286 }
1287
1288 Expected<ParametersT> Result = Parser(Params);
1289 assert((Result || Result.template errorIsA<StringError>()) &&
1290 "Pass parameter parser can only return StringErrors.");
1291 return std::move(Result);
1292}
1293
1294/// Parser of parameters for LoopUnroll pass.
1295Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1296 LoopUnrollOptions UnrollOpts;
1297 while (!Params.empty()) {
1298 StringRef ParamName;
1299 std::tie(ParamName, Params) = Params.split(';');
1300 int OptLevel = StringSwitch<int>(ParamName)
1301 .Case("O0", 0)
1302 .Case("O1", 1)
1303 .Case("O2", 2)
1304 .Case("O3", 3)
1305 .Default(-1);
1306 if (OptLevel >= 0) {
1307 UnrollOpts.setOptLevel(OptLevel);
1308 continue;
1309 }
1310
1311 bool Enable = !ParamName.consume_front("no-");
1312 if (ParamName == "partial") {
1313 UnrollOpts.setPartial(Enable);
1314 } else if (ParamName == "peeling") {
1315 UnrollOpts.setPeeling(Enable);
1316 } else if (ParamName == "runtime") {
1317 UnrollOpts.setRuntime(Enable);
1318 } else if (ParamName == "upperbound") {
1319 UnrollOpts.setUpperBound(Enable);
1320 } else {
1321 return make_error<StringError>(
1322 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1323 inconvertibleErrorCode());
1324 }
1325 }
1326 return UnrollOpts;
1327}
1328
1329} // namespace
1330
Chandler Carruthdf1cbec2017-06-01 11:39:39 +00001331/// Tests whether a pass name starts with a valid prefix for a default pipeline
1332/// alias.
1333static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1334 return Name.startswith("default") || Name.startswith("thinlto") ||
1335 Name.startswith("lto");
1336}
1337
Philip Pfaffe19045612017-07-10 10:57:55 +00001338/// Tests whether registered callbacks will accept a given pass name.
1339///
1340/// When parsing a pipeline text, the type of the outermost pipeline may be
1341/// omitted, in which case the type is automatically determined from the first
1342/// pass name in the text. This may be a name that is handled through one of the
1343/// callbacks. We check this through the oridinary parsing callbacks by setting
1344/// up a dummy PassManager in order to not force the client to also handle this
1345/// type of query.
1346template <typename PassManagerT, typename CallbacksT>
1347static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1348 if (!Callbacks.empty()) {
1349 PassManagerT DummyPM;
1350 for (auto &CB : Callbacks)
1351 if (CB(Name, DummyPM, {}))
1352 return true;
1353 }
1354 return false;
1355}
1356
1357template <typename CallbacksT>
1358static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001359 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruthdf1cbec2017-06-01 11:39:39 +00001360 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001361 return DefaultAliasRegex.match(Name);
1362
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001363 // Explicitly handle pass manager names.
1364 if (Name == "module")
1365 return true;
1366 if (Name == "cgscc")
1367 return true;
1368 if (Name == "function")
1369 return true;
1370
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001371 // Explicitly handle custom-parsed pass names.
1372 if (parseRepeatPassName(Name))
1373 return true;
1374
Chandler Carruthbd6882c2016-06-17 07:15:29 +00001375#define MODULE_PASS(NAME, CREATE_PASS) \
1376 if (Name == NAME) \
1377 return true;
Chandler Carrutha3376d22015-01-06 02:10:51 +00001378#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth17395fa2015-01-06 04:49:44 +00001379 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carrutha3376d22015-01-06 02:10:51 +00001380 return true;
1381#include "PassRegistry.def"
1382
Philip Pfaffe19045612017-07-10 10:57:55 +00001383 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth4e728be2014-01-11 08:16:35 +00001384}
1385
Philip Pfaffe19045612017-07-10 10:57:55 +00001386template <typename CallbacksT>
1387static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001388 // Explicitly handle pass manager names.
1389 if (Name == "cgscc")
1390 return true;
1391 if (Name == "function")
1392 return true;
1393
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001394 // Explicitly handle custom-parsed pass names.
1395 if (parseRepeatPassName(Name))
1396 return true;
Chandler Carruth86d53652016-12-28 11:07:33 +00001397 if (parseDevirtPassName(Name))
1398 return true;
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001399
Chandler Carruthbd6882c2016-06-17 07:15:29 +00001400#define CGSCC_PASS(NAME, CREATE_PASS) \
1401 if (Name == NAME) \
1402 return true;
Chandler Carrutha3376d22015-01-06 02:10:51 +00001403#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth17395fa2015-01-06 04:49:44 +00001404 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carrutha3376d22015-01-06 02:10:51 +00001405 return true;
1406#include "PassRegistry.def"
1407
Philip Pfaffe19045612017-07-10 10:57:55 +00001408 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth57418d82014-04-21 11:12:00 +00001409}
1410
Philip Pfaffe19045612017-07-10 10:57:55 +00001411template <typename CallbacksT>
1412static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001413 // Explicitly handle pass manager names.
1414 if (Name == "function")
1415 return true;
1416 if (Name == "loop")
1417 return true;
1418
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001419 // Explicitly handle custom-parsed pass names.
1420 if (parseRepeatPassName(Name))
1421 return true;
1422
Chandler Carruthbd6882c2016-06-17 07:15:29 +00001423#define FUNCTION_PASS(NAME, CREATE_PASS) \
1424 if (Name == NAME) \
1425 return true;
Fedor Sergeev4f41c192019-01-10 10:01:53 +00001426#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1427 if (checkParametrizedPassName(Name, NAME)) \
1428 return true;
Chandler Carrutha3376d22015-01-06 02:10:51 +00001429#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth17395fa2015-01-06 04:49:44 +00001430 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carrutha3376d22015-01-06 02:10:51 +00001431 return true;
1432#include "PassRegistry.def"
1433
Philip Pfaffe19045612017-07-10 10:57:55 +00001434 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthe7687652014-01-12 09:34:22 +00001435}
1436
Philip Pfaffe19045612017-07-10 10:57:55 +00001437template <typename CallbacksT>
1438static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001439 // Explicitly handle pass manager names.
1440 if (Name == "loop")
1441 return true;
1442
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001443 // Explicitly handle custom-parsed pass names.
1444 if (parseRepeatPassName(Name))
1445 return true;
1446
Chandler Carruthbd6882c2016-06-17 07:15:29 +00001447#define LOOP_PASS(NAME, CREATE_PASS) \
1448 if (Name == NAME) \
1449 return true;
Justin Bognerda5e9242016-02-25 07:23:08 +00001450#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1451 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1452 return true;
1453#include "PassRegistry.def"
1454
Philip Pfaffe19045612017-07-10 10:57:55 +00001455 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognerda5e9242016-02-25 07:23:08 +00001456}
1457
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001458Optional<std::vector<PassBuilder::PipelineElement>>
1459PassBuilder::parsePipelineText(StringRef Text) {
1460 std::vector<PipelineElement> ResultPipeline;
1461
1462 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1463 &ResultPipeline};
1464 for (;;) {
1465 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1466 size_t Pos = Text.find_first_of(",()");
1467 Pipeline.push_back({Text.substr(0, Pos), {}});
1468
1469 // If we have a single terminating name, we're done.
1470 if (Pos == Text.npos)
1471 break;
1472
1473 char Sep = Text[Pos];
1474 Text = Text.substr(Pos + 1);
1475 if (Sep == ',')
1476 // Just a name ending in a comma, continue.
1477 continue;
1478
1479 if (Sep == '(') {
1480 // Push the inner pipeline onto the stack to continue processing.
1481 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1482 continue;
1483 }
1484
1485 assert(Sep == ')' && "Bogus separator!");
1486 // When handling the close parenthesis, we greedily consume them to avoid
1487 // empty strings in the pipeline.
1488 do {
1489 // If we try to pop the outer pipeline we have unbalanced parentheses.
1490 if (PipelineStack.size() == 1)
1491 return None;
1492
1493 PipelineStack.pop_back();
1494 } while (Text.consume_front(")"));
1495
1496 // Check if we've finished parsing.
1497 if (Text.empty())
1498 break;
1499
1500 // Otherwise, the end of an inner pipeline always has to be followed by
1501 // a comma, and then we can continue.
1502 if (!Text.consume_front(","))
1503 return None;
1504 }
1505
1506 if (PipelineStack.size() > 1)
1507 // Unbalanced paretheses.
1508 return None;
1509
1510 assert(PipelineStack.back() == &ResultPipeline &&
1511 "Wrong pipeline at the bottom of the stack!");
1512 return {std::move(ResultPipeline)};
1513}
1514
Fedor Sergeevff886492018-10-17 10:36:23 +00001515Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1516 const PipelineElement &E,
1517 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001518 auto &Name = E.Name;
1519 auto &InnerPipeline = E.InnerPipeline;
1520
1521 // First handle complex passes like the pass managers which carry pipelines.
1522 if (!InnerPipeline.empty()) {
1523 if (Name == "module") {
1524 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001525 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1526 VerifyEachPass, DebugLogging))
1527 return Err;
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001528 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevff886492018-10-17 10:36:23 +00001529 return Error::success();
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001530 }
1531 if (Name == "cgscc") {
1532 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001533 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1534 DebugLogging))
1535 return Err;
Chandler Carruth83bfb552017-08-11 05:47:13 +00001536 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevff886492018-10-17 10:36:23 +00001537 return Error::success();
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001538 }
1539 if (Name == "function") {
1540 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001541 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1542 VerifyEachPass, DebugLogging))
1543 return Err;
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001544 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevff886492018-10-17 10:36:23 +00001545 return Error::success();
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001546 }
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001547 if (auto Count = parseRepeatPassName(Name)) {
1548 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001549 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1550 VerifyEachPass, DebugLogging))
1551 return Err;
Chandler Carruth411e6162016-08-04 03:52:53 +00001552 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevff886492018-10-17 10:36:23 +00001553 return Error::success();
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001554 }
Philip Pfaffe19045612017-07-10 10:57:55 +00001555
1556 for (auto &C : ModulePipelineParsingCallbacks)
1557 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevff886492018-10-17 10:36:23 +00001558 return Error::success();
Philip Pfaffe19045612017-07-10 10:57:55 +00001559
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001560 // Normal passes can't have pipelines.
Fedor Sergeevff886492018-10-17 10:36:23 +00001561 return make_error<StringError>(
1562 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1563 inconvertibleErrorCode());
1564 ;
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001565 }
1566
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001567 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruthdf1cbec2017-06-01 11:39:39 +00001568 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001569 SmallVector<StringRef, 3> Matches;
1570 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevff886492018-10-17 10:36:23 +00001571 return make_error<StringError>(
1572 formatv("unknown default pipeline alias '{0}'", Name).str(),
1573 inconvertibleErrorCode());
1574
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001575 assert(Matches.size() == 3 && "Must capture two matched strings!");
1576
Jordan Rose569213a2016-07-25 18:34:51 +00001577 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe19045612017-07-10 10:57:55 +00001578 .Case("O0", O0)
1579 .Case("O1", O1)
1580 .Case("O2", O2)
1581 .Case("O3", O3)
1582 .Case("Os", Os)
1583 .Case("Oz", Oz);
Chandler Carruth2ffea512016-12-22 06:59:15 +00001584 if (L == O0)
1585 // At O0 we do nothing at all!
Fedor Sergeevff886492018-10-17 10:36:23 +00001586 return Error::success();
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001587
1588 if (Matches[1] == "default") {
Chandler Carruth2ffea512016-12-22 06:59:15 +00001589 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruthdf1cbec2017-06-01 11:39:39 +00001590 } else if (Matches[1] == "thinlto-pre-link") {
1591 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1592 } else if (Matches[1] == "thinlto") {
Teresa Johnson2a478d42018-07-19 14:51:32 +00001593 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001594 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruth2ffea512016-12-22 06:59:15 +00001595 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001596 } else {
1597 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson2a478d42018-07-19 14:51:32 +00001598 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001599 }
Fedor Sergeevff886492018-10-17 10:36:23 +00001600 return Error::success();
Chandler Carruthf7ae2f52016-02-28 22:16:03 +00001601 }
1602
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001603 // Finally expand the basic registered passes from the .inc file.
Chandler Carrutha21cd042014-04-21 08:08:50 +00001604#define MODULE_PASS(NAME, CREATE_PASS) \
1605 if (Name == NAME) { \
1606 MPM.addPass(CREATE_PASS); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001607 return Error::success(); \
Chandler Carrutha5952572014-01-12 12:15:39 +00001608 }
Chandler Carrutha3376d22015-01-06 02:10:51 +00001609#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1610 if (Name == "require<" NAME ">") { \
Chandler Carruth8c28aa12016-08-19 18:36:06 +00001611 MPM.addPass( \
1612 RequireAnalysisPass< \
1613 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001614 return Error::success(); \
Chandler Carruth17395fa2015-01-06 04:49:44 +00001615 } \
1616 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth7b1b31d2016-02-26 12:30:18 +00001617 MPM.addPass(InvalidateAnalysisPass< \
1618 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001619 return Error::success(); \
Chandler Carrutha3376d22015-01-06 02:10:51 +00001620 }
1621#include "PassRegistry.def"
1622
Philip Pfaffe19045612017-07-10 10:57:55 +00001623 for (auto &C : ModulePipelineParsingCallbacks)
1624 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevff886492018-10-17 10:36:23 +00001625 return Error::success();
1626 return make_error<StringError>(
1627 formatv("unknown module pass '{0}'", Name).str(),
1628 inconvertibleErrorCode());
Chandler Carruth4e728be2014-01-11 08:16:35 +00001629}
1630
Fedor Sergeevff886492018-10-17 10:36:23 +00001631Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1632 const PipelineElement &E, bool VerifyEachPass,
1633 bool DebugLogging) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001634 auto &Name = E.Name;
1635 auto &InnerPipeline = E.InnerPipeline;
1636
1637 // First handle complex passes like the pass managers which carry pipelines.
1638 if (!InnerPipeline.empty()) {
1639 if (Name == "cgscc") {
1640 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001641 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1642 VerifyEachPass, DebugLogging))
1643 return Err;
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001644 // Add the nested pass manager with the appropriate adaptor.
1645 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevff886492018-10-17 10:36:23 +00001646 return Error::success();
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001647 }
1648 if (Name == "function") {
1649 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001650 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1651 VerifyEachPass, DebugLogging))
1652 return Err;
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001653 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth83bfb552017-08-11 05:47:13 +00001654 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevff886492018-10-17 10:36:23 +00001655 return Error::success();
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001656 }
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001657 if (auto Count = parseRepeatPassName(Name)) {
1658 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001659 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1660 VerifyEachPass, DebugLogging))
1661 return Err;
Chandler Carruth411e6162016-08-04 03:52:53 +00001662 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevff886492018-10-17 10:36:23 +00001663 return Error::success();
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001664 }
Chandler Carruth86d53652016-12-28 11:07:33 +00001665 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1666 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001667 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1668 VerifyEachPass, DebugLogging))
1669 return Err;
Chandler Carruth83bfb552017-08-11 05:47:13 +00001670 CGPM.addPass(
1671 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevff886492018-10-17 10:36:23 +00001672 return Error::success();
Chandler Carruth86d53652016-12-28 11:07:33 +00001673 }
Philip Pfaffe19045612017-07-10 10:57:55 +00001674
1675 for (auto &C : CGSCCPipelineParsingCallbacks)
1676 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevff886492018-10-17 10:36:23 +00001677 return Error::success();
Philip Pfaffe19045612017-07-10 10:57:55 +00001678
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001679 // Normal passes can't have pipelines.
Fedor Sergeevff886492018-10-17 10:36:23 +00001680 return make_error<StringError>(
1681 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1682 inconvertibleErrorCode());
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001683 }
1684
Philip Pfaffe19045612017-07-10 10:57:55 +00001685// Now expand the basic registered passes from the .inc file.
Chandler Carruth57418d82014-04-21 11:12:00 +00001686#define CGSCC_PASS(NAME, CREATE_PASS) \
1687 if (Name == NAME) { \
1688 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001689 return Error::success(); \
Chandler Carruth57418d82014-04-21 11:12:00 +00001690 }
Chandler Carrutha3376d22015-01-06 02:10:51 +00001691#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1692 if (Name == "require<" NAME ">") { \
Chandler Carruth7b1b31d2016-02-26 12:30:18 +00001693 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth8c28aa12016-08-19 18:36:06 +00001694 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth377af8d2016-08-24 09:37:14 +00001695 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1696 CGSCCUpdateResult &>()); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001697 return Error::success(); \
Chandler Carruth17395fa2015-01-06 04:49:44 +00001698 } \
1699 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth7b1b31d2016-02-26 12:30:18 +00001700 CGPM.addPass(InvalidateAnalysisPass< \
1701 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001702 return Error::success(); \
Chandler Carrutha3376d22015-01-06 02:10:51 +00001703 }
1704#include "PassRegistry.def"
1705
Philip Pfaffe19045612017-07-10 10:57:55 +00001706 for (auto &C : CGSCCPipelineParsingCallbacks)
1707 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevff886492018-10-17 10:36:23 +00001708 return Error::success();
1709 return make_error<StringError>(
1710 formatv("unknown cgscc pass '{0}'", Name).str(),
1711 inconvertibleErrorCode());
Chandler Carruth57418d82014-04-21 11:12:00 +00001712}
1713
Fedor Sergeevff886492018-10-17 10:36:23 +00001714Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1715 const PipelineElement &E,
1716 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001717 auto &Name = E.Name;
1718 auto &InnerPipeline = E.InnerPipeline;
1719
1720 // First handle complex passes like the pass managers which carry pipelines.
1721 if (!InnerPipeline.empty()) {
1722 if (Name == "function") {
1723 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001724 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1725 VerifyEachPass, DebugLogging))
1726 return Err;
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001727 // Add the nested pass manager with the appropriate adaptor.
1728 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevff886492018-10-17 10:36:23 +00001729 return Error::success();
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001730 }
1731 if (Name == "loop") {
1732 LoopPassManager LPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001733 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1734 DebugLogging))
1735 return Err;
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001736 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeevffbb3d02017-12-29 08:16:06 +00001737 FPM.addPass(
1738 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevff886492018-10-17 10:36:23 +00001739 return Error::success();
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001740 }
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001741 if (auto Count = parseRepeatPassName(Name)) {
1742 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001743 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1744 VerifyEachPass, DebugLogging))
1745 return Err;
Chandler Carruth411e6162016-08-04 03:52:53 +00001746 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevff886492018-10-17 10:36:23 +00001747 return Error::success();
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001748 }
Philip Pfaffe19045612017-07-10 10:57:55 +00001749
1750 for (auto &C : FunctionPipelineParsingCallbacks)
1751 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevff886492018-10-17 10:36:23 +00001752 return Error::success();
Philip Pfaffe19045612017-07-10 10:57:55 +00001753
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001754 // Normal passes can't have pipelines.
Fedor Sergeevff886492018-10-17 10:36:23 +00001755 return make_error<StringError>(
1756 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1757 inconvertibleErrorCode());
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001758 }
1759
Philip Pfaffe19045612017-07-10 10:57:55 +00001760// Now expand the basic registered passes from the .inc file.
Chandler Carrutha21cd042014-04-21 08:08:50 +00001761#define FUNCTION_PASS(NAME, CREATE_PASS) \
1762 if (Name == NAME) { \
1763 FPM.addPass(CREATE_PASS); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001764 return Error::success(); \
Chandler Carrutha5952572014-01-12 12:15:39 +00001765 }
Fedor Sergeev4f41c192019-01-10 10:01:53 +00001766#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1767 if (checkParametrizedPassName(Name, NAME)) { \
1768 auto Params = parsePassParameters(PARSER, Name, NAME); \
1769 if (!Params) \
1770 return Params.takeError(); \
1771 FPM.addPass(CREATE_PASS(Params.get())); \
1772 return Error::success(); \
1773 }
Chandler Carrutha3376d22015-01-06 02:10:51 +00001774#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1775 if (Name == "require<" NAME ">") { \
Chandler Carruth8c28aa12016-08-19 18:36:06 +00001776 FPM.addPass( \
1777 RequireAnalysisPass< \
1778 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001779 return Error::success(); \
Chandler Carruth17395fa2015-01-06 04:49:44 +00001780 } \
1781 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth7b1b31d2016-02-26 12:30:18 +00001782 FPM.addPass(InvalidateAnalysisPass< \
1783 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001784 return Error::success(); \
Chandler Carrutha3376d22015-01-06 02:10:51 +00001785 }
1786#include "PassRegistry.def"
1787
Philip Pfaffe19045612017-07-10 10:57:55 +00001788 for (auto &C : FunctionPipelineParsingCallbacks)
1789 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevff886492018-10-17 10:36:23 +00001790 return Error::success();
1791 return make_error<StringError>(
1792 formatv("unknown function pass '{0}'", Name).str(),
1793 inconvertibleErrorCode());
Chandler Carruthe7687652014-01-12 09:34:22 +00001794}
1795
Fedor Sergeevff886492018-10-17 10:36:23 +00001796Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1797 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001798 StringRef Name = E.Name;
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001799 auto &InnerPipeline = E.InnerPipeline;
1800
1801 // First handle complex passes like the pass managers which carry pipelines.
1802 if (!InnerPipeline.empty()) {
1803 if (Name == "loop") {
1804 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001805 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1806 VerifyEachPass, DebugLogging))
1807 return Err;
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001808 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthd4bcc6c2016-08-03 09:14:03 +00001809 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevff886492018-10-17 10:36:23 +00001810 return Error::success();
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001811 }
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001812 if (auto Count = parseRepeatPassName(Name)) {
1813 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevff886492018-10-17 10:36:23 +00001814 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1815 VerifyEachPass, DebugLogging))
1816 return Err;
Chandler Carruth411e6162016-08-04 03:52:53 +00001817 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevff886492018-10-17 10:36:23 +00001818 return Error::success();
Chandler Carruth91b6bfa2016-08-03 07:44:48 +00001819 }
Philip Pfaffe19045612017-07-10 10:57:55 +00001820
1821 for (auto &C : LoopPipelineParsingCallbacks)
1822 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevff886492018-10-17 10:36:23 +00001823 return Error::success();
Philip Pfaffe19045612017-07-10 10:57:55 +00001824
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001825 // Normal passes can't have pipelines.
Fedor Sergeevff886492018-10-17 10:36:23 +00001826 return make_error<StringError>(
1827 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1828 inconvertibleErrorCode());
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001829 }
1830
Philip Pfaffe19045612017-07-10 10:57:55 +00001831// Now expand the basic registered passes from the .inc file.
Justin Bognerda5e9242016-02-25 07:23:08 +00001832#define LOOP_PASS(NAME, CREATE_PASS) \
1833 if (Name == NAME) { \
Chandler Carruthd4bcc6c2016-08-03 09:14:03 +00001834 LPM.addPass(CREATE_PASS); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001835 return Error::success(); \
Justin Bognerda5e9242016-02-25 07:23:08 +00001836 }
1837#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1838 if (Name == "require<" NAME ">") { \
Chandler Carruthd4bcc6c2016-08-03 09:14:03 +00001839 LPM.addPass(RequireAnalysisPass< \
Chandler Carruthd27a39a2017-01-11 06:23:21 +00001840 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1841 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1842 LPMUpdater &>()); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001843 return Error::success(); \
Justin Bognerda5e9242016-02-25 07:23:08 +00001844 } \
1845 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthd4bcc6c2016-08-03 09:14:03 +00001846 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth7b1b31d2016-02-26 12:30:18 +00001847 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevff886492018-10-17 10:36:23 +00001848 return Error::success(); \
Justin Bognerda5e9242016-02-25 07:23:08 +00001849 }
1850#include "PassRegistry.def"
1851
Philip Pfaffe19045612017-07-10 10:57:55 +00001852 for (auto &C : LoopPipelineParsingCallbacks)
1853 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevff886492018-10-17 10:36:23 +00001854 return Error::success();
1855 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1856 inconvertibleErrorCode());
Justin Bognerda5e9242016-02-25 07:23:08 +00001857}
1858
Chandler Carruth67a41f02016-02-18 09:45:17 +00001859bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruthf51faf02016-03-11 09:15:11 +00001860#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1861 if (Name == NAME) { \
1862 AA.registerModuleAnalysis< \
1863 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1864 return true; \
1865 }
Chandler Carruth67a41f02016-02-18 09:45:17 +00001866#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1867 if (Name == NAME) { \
Chandler Carruth1ce194e2016-02-26 12:17:54 +00001868 AA.registerFunctionAnalysis< \
1869 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruth67a41f02016-02-18 09:45:17 +00001870 return true; \
1871 }
1872#include "PassRegistry.def"
1873
Philip Pfaffe19045612017-07-10 10:57:55 +00001874 for (auto &C : AAParsingCallbacks)
1875 if (C(Name, AA))
1876 return true;
Chandler Carruth67a41f02016-02-18 09:45:17 +00001877 return false;
1878}
1879
Fedor Sergeevff886492018-10-17 10:36:23 +00001880Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001881 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth23491362015-03-07 09:02:36 +00001882 bool VerifyEachPass,
1883 bool DebugLogging) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001884 for (const auto &Element : Pipeline) {
Fedor Sergeevff886492018-10-17 10:36:23 +00001885 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1886 return Err;
1887 // FIXME: No verifier support for Loop passes!
1888 }
1889 return Error::success();
1890}
1891
1892Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1893 ArrayRef<PipelineElement> Pipeline,
1894 bool VerifyEachPass,
1895 bool DebugLogging) {
1896 for (const auto &Element : Pipeline) {
1897 if (auto Err =
1898 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1899 return Err;
1900 if (VerifyEachPass)
1901 FPM.addPass(VerifierPass());
1902 }
1903 return Error::success();
1904}
1905
1906Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1907 ArrayRef<PipelineElement> Pipeline,
1908 bool VerifyEachPass,
1909 bool DebugLogging) {
1910 for (const auto &Element : Pipeline) {
1911 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1912 return Err;
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001913 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth57418d82014-04-21 11:12:00 +00001914 }
Fedor Sergeevff886492018-10-17 10:36:23 +00001915 return Error::success();
Chandler Carruth57418d82014-04-21 11:12:00 +00001916}
1917
NAKAMURA Takumi0d8f8a02016-05-16 10:13:37 +00001918void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1919 FunctionAnalysisManager &FAM,
1920 CGSCCAnalysisManager &CGAM,
1921 ModuleAnalysisManager &MAM) {
1922 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1923 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumi0d8f8a02016-05-16 10:13:37 +00001924 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1925 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1926 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1927 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1928 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1929}
1930
Fedor Sergeevff886492018-10-17 10:36:23 +00001931Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1932 ArrayRef<PipelineElement> Pipeline,
1933 bool VerifyEachPass,
1934 bool DebugLogging) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001935 for (const auto &Element : Pipeline) {
Fedor Sergeevff886492018-10-17 10:36:23 +00001936 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1937 return Err;
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001938 if (VerifyEachPass)
1939 MPM.addPass(VerifierPass());
Chandler Carruth4e728be2014-01-11 08:16:35 +00001940 }
Fedor Sergeevff886492018-10-17 10:36:23 +00001941 return Error::success();
Chandler Carruth4e728be2014-01-11 08:16:35 +00001942}
1943
Philip Pfaffe19045612017-07-10 10:57:55 +00001944// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth4e728be2014-01-11 08:16:35 +00001945// FIXME: Should this routine accept a TargetMachine or require the caller to
1946// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevff886492018-10-17 10:36:23 +00001947Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1948 StringRef PipelineText,
1949 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001950 auto Pipeline = parsePipelineText(PipelineText);
1951 if (!Pipeline || Pipeline->empty())
Fedor Sergeevff886492018-10-17 10:36:23 +00001952 return make_error<StringError>(
1953 formatv("invalid pipeline '{0}'", PipelineText).str(),
1954 inconvertibleErrorCode());
Chandler Carruth4e728be2014-01-11 08:16:35 +00001955
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001956 // If the first name isn't at the module layer, wrap the pipeline up
1957 // automatically.
1958 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth4e728be2014-01-11 08:16:35 +00001959
Philip Pfaffe19045612017-07-10 10:57:55 +00001960 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1961 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001962 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe19045612017-07-10 10:57:55 +00001963 } else if (isFunctionPassName(FirstName,
1964 FunctionPipelineParsingCallbacks)) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001965 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe19045612017-07-10 10:57:55 +00001966 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth3d1a4702016-08-03 03:21:41 +00001967 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe19045612017-07-10 10:57:55 +00001968 } else {
1969 for (auto &C : TopLevelPipelineParsingCallbacks)
1970 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevff886492018-10-17 10:36:23 +00001971 return Error::success();
Philip Pfaffe19045612017-07-10 10:57:55 +00001972
Fedor Sergeevff886492018-10-17 10:36:23 +00001973 // Unknown pass or pipeline name!
1974 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1975 return make_error<StringError>(
1976 formatv("unknown {0} name '{1}'",
1977 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1978 .str(),
1979 inconvertibleErrorCode());
Philip Pfaffe19045612017-07-10 10:57:55 +00001980 }
Chandler Carruth57418d82014-04-21 11:12:00 +00001981 }
1982
Fedor Sergeevff886492018-10-17 10:36:23 +00001983 if (auto Err =
1984 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1985 return Err;
1986 return Error::success();
Chandler Carruth4e728be2014-01-11 08:16:35 +00001987}
Chandler Carruth67a41f02016-02-18 09:45:17 +00001988
Philip Pfaffe19045612017-07-10 10:57:55 +00001989// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevff886492018-10-17 10:36:23 +00001990Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1991 StringRef PipelineText,
1992 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe19045612017-07-10 10:57:55 +00001993 auto Pipeline = parsePipelineText(PipelineText);
1994 if (!Pipeline || Pipeline->empty())
Fedor Sergeevff886492018-10-17 10:36:23 +00001995 return make_error<StringError>(
1996 formatv("invalid pipeline '{0}'", PipelineText).str(),
1997 inconvertibleErrorCode());
Philip Pfaffe19045612017-07-10 10:57:55 +00001998
1999 StringRef FirstName = Pipeline->front().Name;
2000 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevff886492018-10-17 10:36:23 +00002001 return make_error<StringError>(
2002 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2003 PipelineText)
2004 .str(),
2005 inconvertibleErrorCode());
Philip Pfaffe19045612017-07-10 10:57:55 +00002006
Fedor Sergeevff886492018-10-17 10:36:23 +00002007 if (auto Err =
2008 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2009 return Err;
2010 return Error::success();
Philip Pfaffe19045612017-07-10 10:57:55 +00002011}
2012
2013// Primary pass pipeline description parsing routine for a \c
2014// FunctionPassManager
Fedor Sergeevff886492018-10-17 10:36:23 +00002015Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2016 StringRef PipelineText,
2017 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe19045612017-07-10 10:57:55 +00002018 auto Pipeline = parsePipelineText(PipelineText);
2019 if (!Pipeline || Pipeline->empty())
Fedor Sergeevff886492018-10-17 10:36:23 +00002020 return make_error<StringError>(
2021 formatv("invalid pipeline '{0}'", PipelineText).str(),
2022 inconvertibleErrorCode());
Philip Pfaffe19045612017-07-10 10:57:55 +00002023
2024 StringRef FirstName = Pipeline->front().Name;
2025 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevff886492018-10-17 10:36:23 +00002026 return make_error<StringError>(
2027 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2028 PipelineText)
2029 .str(),
2030 inconvertibleErrorCode());
Philip Pfaffe19045612017-07-10 10:57:55 +00002031
Fedor Sergeevff886492018-10-17 10:36:23 +00002032 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2033 DebugLogging))
2034 return Err;
2035 return Error::success();
Philip Pfaffe19045612017-07-10 10:57:55 +00002036}
2037
2038// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevff886492018-10-17 10:36:23 +00002039Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2040 StringRef PipelineText,
2041 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe19045612017-07-10 10:57:55 +00002042 auto Pipeline = parsePipelineText(PipelineText);
2043 if (!Pipeline || Pipeline->empty())
Fedor Sergeevff886492018-10-17 10:36:23 +00002044 return make_error<StringError>(
2045 formatv("invalid pipeline '{0}'", PipelineText).str(),
2046 inconvertibleErrorCode());
Philip Pfaffe19045612017-07-10 10:57:55 +00002047
Fedor Sergeevff886492018-10-17 10:36:23 +00002048 if (auto Err =
2049 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2050 return Err;
2051
2052 return Error::success();
Philip Pfaffe19045612017-07-10 10:57:55 +00002053}
2054
Fedor Sergeevff886492018-10-17 10:36:23 +00002055Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth759dd392016-12-23 20:38:19 +00002056 // If the pipeline just consists of the word 'default' just replace the AA
2057 // manager with our default one.
2058 if (PipelineText == "default") {
2059 AA = buildDefaultAAPipeline();
Fedor Sergeevff886492018-10-17 10:36:23 +00002060 return Error::success();
Chandler Carruth759dd392016-12-23 20:38:19 +00002061 }
2062
Chandler Carruth67a41f02016-02-18 09:45:17 +00002063 while (!PipelineText.empty()) {
2064 StringRef Name;
2065 std::tie(Name, PipelineText) = PipelineText.split(',');
2066 if (!parseAAPassName(AA, Name))
Fedor Sergeevff886492018-10-17 10:36:23 +00002067 return make_error<StringError>(
2068 formatv("unknown alias analysis name '{0}'", Name).str(),
2069 inconvertibleErrorCode());
Chandler Carruth67a41f02016-02-18 09:45:17 +00002070 }
2071
Fedor Sergeevff886492018-10-17 10:36:23 +00002072 return Error::success();
Chandler Carruth67a41f02016-02-18 09:45:17 +00002073}