Polly 24.0.0git
RegisterPasses.cpp
Go to the documentation of this file.
1//===------ RegisterPasses.cpp - Add the Polly Passes to default passes --===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file composes the individual LLVM-IR passes provided by Polly to a
10// functional polyhedral optimizer. The polyhedral optimizer is automatically
11// made available to LLVM based compilers by loading the Polly shared library
12// into such a compiler.
13//
14// The Polly optimizer is made available by executing a static constructor that
15// registers the individual Polly passes in the LLVM pass manager builder. The
16// passes are registered such that the default behaviour of the compiler is not
17// changed, but that the flag '-polly' provided at optimization level '-O3'
18// enables additional polyhedral optimizations.
19//===----------------------------------------------------------------------===//
20
26#include "polly/DeLICM.h"
29#include "polly/ForwardOpTree.h"
30#include "polly/JSONExporter.h"
32#include "polly/Options.h"
36#include "polly/ScopDetection.h"
38#include "polly/ScopInfo.h"
39#include "polly/ScopInliner.h"
40#include "polly/Simplify.h"
43#include "llvm/Analysis/CFGPrinter.h"
44#include "llvm/Config/llvm-config.h" // for LLVM_VERSION_STRING
45#include "llvm/IR/LegacyPassManager.h"
46#include "llvm/IR/PassManager.h"
47#include "llvm/IR/Verifier.h"
48#include "llvm/Passes/PassBuilder.h"
49#include "llvm/Plugins/PassPlugin.h"
50#include "llvm/Support/CommandLine.h"
51#include "llvm/Support/Error.h"
52#include "llvm/Support/TargetSelect.h"
53#include "llvm/Support/raw_ostream.h"
54#include "llvm/Transforms/IPO.h"
55
56using namespace llvm;
57using namespace polly;
58
59namespace cl = llvm::cl;
60using namespace polly;
61
62using llvm::FunctionPassManager;
63using llvm::OptimizationLevel;
64using llvm::PassBuilder;
65using llvm::PassInstrumentationCallbacks;
66
67cl::OptionCategory PollyCategory("Polly Options",
68 "Configure the polly loop optimizer");
69
70namespace polly {
71static cl::opt<bool>
72 PollyEnabled("polly",
73 cl::desc("Enable the polly optimizer (with -O1, -O2 or -O3)"),
74 cl::cat(PollyCategory));
75
76static cl::opt<bool> PollyDetectOnly(
77 "polly-only-scop-detection",
78 cl::desc("Only run scop detection, but no other optimizations"),
79 cl::cat(PollyCategory));
80
82
84
85static cl::opt<PassPositionChoice> PassPosition(
86 "polly-position", cl::desc("Where to run polly in the pass pipeline"),
87 cl::values(clEnumValN(POSITION_EARLY, "early", "Before everything"),
88 clEnumValN(POSITION_BEFORE_VECTORIZER, "before-vectorizer",
89 "Right before the vectorizer")),
90 cl::Hidden, cl::init(POSITION_BEFORE_VECTORIZER), cl::cat(PollyCategory));
91
92static cl::opt<OptimizerChoice>
93 Optimizer("polly-optimizer", cl::desc("Select the scheduling optimizer"),
94 cl::values(clEnumValN(OPTIMIZER_NONE, "none", "No optimizer"),
95 clEnumValN(OPTIMIZER_ISL, "isl",
96 "The isl scheduling optimizer")),
97 cl::Hidden, cl::init(OPTIMIZER_ISL), cl::cat(PollyCategory));
98
100static cl::opt<CodeGenChoice> CodeGeneration(
101 "polly-code-generation", cl::desc("How much code-generation to perform"),
102 cl::values(clEnumValN(CODEGEN_FULL, "full", "AST and IR generation"),
103 clEnumValN(CODEGEN_AST, "ast", "Only AST generation"),
104 clEnumValN(CODEGEN_NONE, "none", "No code generation")),
105 cl::Hidden, cl::init(CODEGEN_FULL), cl::cat(PollyCategory));
106
108
109static cl::opt<VectorizerChoice, true> Vectorizer(
110 "polly-vectorizer", cl::desc("Select the vectorization strategy"),
111 cl::values(
112 clEnumValN(VECTORIZER_NONE, "none", "No Vectorization"),
113 clEnumValN(
114 VECTORIZER_STRIPMINE, "stripmine",
115 "Strip-mine outer loops for the loop-vectorizer to trigger")),
116 cl::location(PollyVectorizerChoice), cl::init(VECTORIZER_NONE),
117 cl::cat(PollyCategory));
118
119static cl::opt<bool> ImportJScop(
120 "polly-import",
121 cl::desc("Import the polyhedral description of the detected Scops"),
122 cl::Hidden, cl::cat(PollyCategory));
123
124static cl::opt<bool> FullyIndexedStaticExpansion(
125 "polly-enable-mse",
126 cl::desc("Fully expand the memory accesses of the detected Scops"),
127 cl::Hidden, cl::cat(PollyCategory));
128
129static cl::opt<bool> ExportJScop(
130 "polly-export",
131 cl::desc("Export the polyhedral description of the detected Scops"),
132 cl::Hidden, cl::cat(PollyCategory));
133
134static cl::opt<bool> DeadCodeElim("polly-run-dce",
135 cl::desc("Run the dead code elimination"),
136 cl::Hidden, cl::cat(PollyCategory));
137
138static cl::opt<bool> PollyViewer(
139 "polly-show",
140 cl::desc("Highlight the code regions that will be optimized in a "
141 "(CFG BBs and LLVM-IR instructions)"),
142 cl::cat(PollyCategory));
143
144static cl::opt<bool> PollyOnlyViewer(
145 "polly-show-only",
146 cl::desc("Highlight the code regions that will be optimized in "
147 "a (CFG only BBs)"),
148 cl::init(false), cl::cat(PollyCategory));
149
150static cl::opt<bool>
151 PollyPrinter("polly-dot", cl::desc("Enable the Polly DOT printer in -O3"),
152 cl::Hidden, cl::value_desc("Run the Polly DOT printer at -O3"),
153 cl::init(false), cl::cat(PollyCategory));
154
155static cl::opt<bool> PollyOnlyPrinter(
156 "polly-dot-only",
157 cl::desc("Enable the Polly DOT printer in -O3 (no BB content)"), cl::Hidden,
158 cl::value_desc("Run the Polly DOT printer at -O3 (no BB content"),
159 cl::init(false), cl::cat(PollyCategory));
160
161static cl::opt<bool>
162 CFGPrinter("polly-view-cfg",
163 cl::desc("Show the Polly CFG right after code generation"),
164 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
165
166static cl::opt<bool>
167 EnableForwardOpTree("polly-enable-optree",
168 cl::desc("Enable operand tree forwarding"), cl::Hidden,
169 cl::init(true), cl::cat(PollyCategory));
170
171static cl::opt<bool>
172 DumpBefore("polly-dump-before",
173 cl::desc("Dump module before Polly transformations into a file "
174 "suffixed with \"-before\""),
175 cl::init(false), cl::cat(PollyCategory));
176
177static cl::list<std::string> DumpBeforeFile(
178 "polly-dump-before-file",
179 cl::desc("Dump module before Polly transformations to the given file"),
180 cl::cat(PollyCategory));
181
182static cl::opt<bool>
183 DumpAfter("polly-dump-after",
184 cl::desc("Dump module after Polly transformations into a file "
185 "suffixed with \"-after\""),
186 cl::init(false), cl::cat(PollyCategory));
187
188static cl::list<std::string> DumpAfterFile(
189 "polly-dump-after-file",
190 cl::desc("Dump module after Polly transformations to the given file"),
191 cl::cat(PollyCategory));
192
193static cl::opt<bool>
194 EnableDeLICM("polly-enable-delicm",
195 cl::desc("Eliminate scalar loop carried dependences"),
196 cl::Hidden, cl::init(true), cl::cat(PollyCategory));
197
198static cl::opt<bool>
199 EnableSimplify("polly-enable-simplify",
200 cl::desc("Simplify SCoP after optimizations"),
201 cl::init(true), cl::cat(PollyCategory));
202
203static cl::opt<bool> EnablePruneUnprofitable(
204 "polly-enable-prune-unprofitable",
205 cl::desc("Bail out on unprofitable SCoPs before rescheduling"), cl::Hidden,
206 cl::init(true), cl::cat(PollyCategory));
207
208static cl::opt<bool>
209 PollyPrintDetect("polly-print-detect",
210 cl::desc("Polly - Print static control parts (SCoPs)"),
211 cl::cat(PollyCategory));
212
213static cl::opt<bool>
214 PollyPrintScops("polly-print-scops",
215 cl::desc("Print polyhedral description of all regions"),
216 cl::cat(PollyCategory));
217
218static cl::opt<bool> PollyPrintDeps("polly-print-deps",
219 cl::desc("Polly - Print dependences"),
220 cl::cat(PollyCategory));
221
223
225 // FIXME: PollyTrackFailures is user-controlled, should not be set
226 // programmatically.
228 PollyTrackFailures = true;
229
232}
233
234/// Parser of parameters for LoopVectorize pass.
235static llvm::Expected<PollyPassOptions> parsePollyOptions(StringRef Params,
236 bool IsCustom) {
237 PassPhase PrevPhase = PassPhase::None;
238
239 bool EnableDefaultOpts = !IsCustom;
240 bool EnableEnd2End = !IsCustom;
241 std::optional<bool>
242 PassEnabled[static_cast<size_t>(PassPhase::PassPhaseLast) + 1];
243 PassPhase StopAfter = PassPhase::None;
244
245 // Passes enabled using command-line flags (can be overridden using
246 // 'polly<no-pass>')
248 PassEnabled[static_cast<size_t>(PassPhase::PrintDetect)] = true;
249 if (PollyPrintScops)
250 PassEnabled[static_cast<size_t>(PassPhase::PrintScopInfo)] = true;
251 if (PollyPrintDeps)
252 PassEnabled[static_cast<size_t>(PassPhase::PrintDependences)] = true;
253
254 if (PollyViewer)
255 PassEnabled[static_cast<size_t>(PassPhase::ViewScops)] = true;
256 if (PollyOnlyViewer)
257 PassEnabled[static_cast<size_t>(PassPhase::ViewScopsOnly)] = true;
258 if (PollyPrinter)
259 PassEnabled[static_cast<size_t>(PassPhase::DotScops)] = true;
261 PassEnabled[static_cast<size_t>(PassPhase::DotScopsOnly)] = true;
262 if (!EnableSimplify)
263 PassEnabled[static_cast<size_t>(PassPhase::Simplify0)] = false;
265 PassEnabled[static_cast<size_t>(PassPhase::Optree)] = false;
266 if (!EnableDeLICM)
267 PassEnabled[static_cast<size_t>(PassPhase::DeLICM)] = false;
268 if (!EnableSimplify)
269 PassEnabled[static_cast<size_t>(PassPhase::Simplify1)] = false;
270 if (ImportJScop)
271 PassEnabled[static_cast<size_t>(PassPhase::ImportJScop)] = true;
272 if (DeadCodeElim)
273 PassEnabled[static_cast<size_t>(PassPhase::DeadCodeElimination)] = true;
275 PassEnabled[static_cast<size_t>(PassPhase::MaximumStaticExtension)] = true;
277 PassEnabled[static_cast<size_t>(PassPhase::PruneUnprofitable)] = false;
278 switch (Optimizer) {
279 case OPTIMIZER_NONE:
280 // explicitly switched off
281 PassEnabled[static_cast<size_t>(PassPhase::Optimization)] = false;
282 break;
283 case OPTIMIZER_ISL:
284 // default: enabled
285 break;
286 }
287 if (ExportJScop)
288 PassEnabled[static_cast<size_t>(PassPhase::ExportJScop)] = true;
289 switch (CodeGeneration) {
290 case CODEGEN_AST:
291 PassEnabled[static_cast<size_t>(PassPhase::AstGen)] = true;
292 PassEnabled[static_cast<size_t>(PassPhase::CodeGen)] = false;
293 break;
294 case CODEGEN_FULL:
295 // default: ast and codegen enabled
296 break;
297 case CODEGEN_NONE:
298 PassEnabled[static_cast<size_t>(PassPhase::AstGen)] = false;
299 PassEnabled[static_cast<size_t>(PassPhase::CodeGen)] = false;
300 break;
301 }
302
303 while (!Params.empty()) {
304 StringRef Param;
305 std::tie(Param, Params) = Params.split(';');
306 auto [ParamName, ParamVal] = Param.split('=');
307
308 if (ParamName == "stopafter") {
309 StopAfter = parsePhase(ParamVal);
310 if (StopAfter == PassPhase::None)
311 return make_error<StringError>(
312 formatv("invalid stopafter parameter value '{0}'", ParamVal).str(),
313 inconvertibleErrorCode());
314 continue;
315 }
316
317 if (!ParamVal.empty())
318 return make_error<StringError>(
319 formatv("parameter '{0}' does not take value", ParamName).str(),
320 inconvertibleErrorCode());
321
322 bool Enabled = true;
323 if (ParamName.starts_with("no-")) {
324 Enabled = false;
325 ParamName = ParamName.drop_front(3);
326 }
327
328 if (ParamName == "default-opts") {
329 EnableDefaultOpts = Enabled;
330 continue;
331 }
332
333 if (ParamName == "end2end") {
334 EnableEnd2End = Enabled;
335 continue;
336 }
337
338 PassPhase Phase;
339
340 // Shortcut for both simplifys at the same time
341 if (ParamName == "simplify") {
342 PassEnabled[static_cast<size_t>(PassPhase::Simplify0)] = Enabled;
343 PassEnabled[static_cast<size_t>(PassPhase::Simplify1)] = Enabled;
344 Phase = PassPhase::Simplify0;
345 } else {
346 Phase = parsePhase(ParamName);
347 if (Phase == PassPhase::None)
348 return make_error<StringError>(
349 formatv("invalid Polly parameter/phase name '{0}'", ParamName)
350 .str(),
351 inconvertibleErrorCode());
352
353 if (PrevPhase >= Phase)
354 return make_error<StringError>(
355 formatv("phases must not be repeated and enumerated in-order: "
356 "'{0}' listed before '{1}'",
357 getPhaseName(PrevPhase), getPhaseName(Phase))
358 .str(),
359 inconvertibleErrorCode());
360
361 PassEnabled[static_cast<size_t>(Phase)] = Enabled;
362 }
363 PrevPhase = Phase;
364 }
365
366 PollyPassOptions Opts;
367 Opts.ViewAll = ViewAll;
368 Opts.ViewFilter = ViewFilter;
370
371 // Implicitly enable dependent phases first. May be overriden explicitly
372 // on/off later.
373 for (PassPhase P : llvm::enum_seq_inclusive(PassPhase::PassPhaseFirst,
375 bool Enabled = PassEnabled[static_cast<size_t>(P)].value_or(false);
376 if (!Enabled)
377 continue;
378
379 if (static_cast<size_t>(PassPhase::Detection) < static_cast<size_t>(P))
381
382 if (static_cast<size_t>(PassPhase::ScopInfo) < static_cast<size_t>(P))
384
387
388 if (static_cast<size_t>(PassPhase::AstGen) < static_cast<size_t>(P))
390 }
391
392 if (EnableEnd2End)
393 Opts.enableEnd2End();
394
395 if (EnableDefaultOpts)
396 Opts.enableDefaultOpts();
397
398 for (PassPhase P : llvm::enum_seq_inclusive(PassPhase::PassPhaseFirst,
400 std::optional<bool> Enabled = PassEnabled[static_cast<size_t>(P)];
401
402 // Apply only if set explicitly.
403 if (Enabled.has_value())
404 Opts.setPhaseEnabled(P, *Enabled);
405 }
406
407 if (StopAfter != PassPhase::None)
408 Opts.disableAfter(StopAfter);
409
410 if (Error CheckResult = Opts.checkConsistency())
411 return CheckResult;
412
413 return Opts;
414}
415
416static llvm::Expected<PollyPassOptions>
417parsePollyDefaultOptions(StringRef Params) {
418 return parsePollyOptions(Params, false);
419}
420
421static llvm::Expected<PollyPassOptions>
422parsePollyCustomOptions(StringRef Params) {
423 return parsePollyOptions(Params, true);
424}
425
426/// Register Polly passes such that they form a polyhedral optimizer.
427///
428/// The individual Polly passes are registered in the pass manager such that
429/// they form a full polyhedral optimizer. The flow of the optimizer starts with
430/// a set of preparing transformations that canonicalize the LLVM-IR such that
431/// the LLVM-IR is easier for us to understand and to optimizes. On the
432/// canonicalized LLVM-IR we first run the ScopDetection pass, which detects
433/// static control flow regions. Those regions are then translated by the
434/// ScopInfo pass into a polyhedral representation. As a next step, a scheduling
435/// optimizer is run on the polyhedral representation and finally the optimized
436/// polyhedral representation is code generated back to LLVM-IR.
437///
438/// Besides this core functionality, we optionally schedule passes that provide
439/// a graphical view of the scops (Polly[Only]Viewer, Polly[Only]Printer), that
440/// allow the export/import of the polyhedral representation
441/// (JSCON[Exporter|Importer]) or that show the cfg after code generation.
442///
443/// For certain parts of the Polly optimizer, several alternatives are provided:
444///
445/// As scheduling optimizer we support the isl scheduling optimizer
446/// (http://freecode.com/projects/isl).
447/// It is also possible to run Polly with no optimizer. This mode is mainly
448/// provided to analyze the run and compile time changes caused by the
449/// scheduling optimizer.
450///
451/// Polly supports the isl internal code generator.
452
453/// Add the pass sequence required for Polly to the New Pass Manager.
454///
455/// @param PM The pass manager itself.
456/// @param Level The optimization level. Used for the cleanup of Polly's
457/// output.
458/// @param EnableForOpt Whether to add Polly IR transformations. If False, only
459/// the analysis passes are added, skipping Polly itself.
460/// The IR may still be modified.
461static void buildCommonPollyPipeline(LLVMContext &Context,
462 FunctionPassManager &PM,
463 OptimizationLevel Level,
464 IntrusiveRefCntPtr<vfs::FileSystem> FS,
465 bool EnableForOpt) {
466 PassBuilder PB(Context, /*TM=*/nullptr, /*PTO=*/std::nullopt,
467 /*PGOOpt=*/{},
468 /*PIC=*/nullptr, std::move(FS));
469
470 ExitOnError Err("Inconsistent Polly configuration: ");
471 PollyPassOptions &&Opts =
472 Err(parsePollyOptions(StringRef(), /*IsCustom=*/false));
473 PM.addPass(PollyFunctionPass(Opts));
474
475 PM.addPass(PB.buildFunctionSimplificationPipeline(
476 Level, llvm::ThinOrFullLTOPhase::None)); // Cleanup
477
478 if (CFGPrinter)
479 PM.addPass(llvm::CFGPrinterPass());
480}
481
482static void buildEarlyPollyPipeline(LLVMContext &Context,
483 llvm::ModulePassManager &MPM,
484 llvm::OptimizationLevel Level,
485 IntrusiveRefCntPtr<vfs::FileSystem> FS) {
486 bool EnableForOpt =
487 shouldEnablePollyForOptimization() && Level != OptimizationLevel::O0;
488 if (!shouldEnablePollyForDiagnostic() && !EnableForOpt)
489 return;
490
491 FunctionPassManager FPM = buildCanonicalicationPassesForNPM(MPM, Level);
492
493 if (DumpBefore || !DumpBeforeFile.empty()) {
494 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
495
496 if (DumpBefore)
497 MPM.addPass(DumpModulePass("-before", true));
498 for (auto &Filename : DumpBeforeFile)
499 MPM.addPass(DumpModulePass(Filename, false));
500
501 FPM = FunctionPassManager();
502 }
503
504 buildCommonPollyPipeline(Context, FPM, Level, std::move(FS), EnableForOpt);
505 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
506
507 if (DumpAfter)
508 MPM.addPass(DumpModulePass("-after", true));
509 for (auto &Filename : DumpAfterFile)
510 MPM.addPass(DumpModulePass(Filename, false));
511}
512
513static void buildLatePollyPipeline(LLVMContext &Context,
514 FunctionPassManager &PM,
515 llvm::OptimizationLevel Level,
516 IntrusiveRefCntPtr<vfs::FileSystem> FS) {
517 bool EnableForOpt =
518 shouldEnablePollyForOptimization() && Level != OptimizationLevel::O0;
519 if (!shouldEnablePollyForDiagnostic() && !EnableForOpt)
520 return;
521
522 if (DumpBefore)
523 PM.addPass(DumpFunctionPass("-before"));
524 if (!DumpBeforeFile.empty())
525 llvm::report_fatal_error(
526 "Option -polly-dump-before-file at -polly-position=late "
527 "not supported with NPM",
528 false);
529
530 buildCommonPollyPipeline(Context, PM, Level, std::move(FS), EnableForOpt);
531
532 if (DumpAfter)
533 PM.addPass(DumpFunctionPass("-after"));
534 if (!DumpAfterFile.empty())
535 llvm::report_fatal_error(
536 "Option -polly-dump-after-file at -polly-position=late "
537 "not supported with NPM",
538 false);
539}
540
541static llvm::Expected<std::monostate> parseNoOptions(StringRef Params) {
542 if (!Params.empty())
543 return make_error<StringError>(
544 formatv("'{0}' passed to pass that does not take any options", Params)
545 .str(),
546 inconvertibleErrorCode());
547
548 return std::monostate{};
549}
550
551static llvm::Expected<bool>
552parseCGPipeline(StringRef Name, llvm::CGSCCPassManager &CGPM,
553 PassInstrumentationCallbacks *PIC,
554 ArrayRef<PassBuilder::PipelineElement> Pipeline,
555 IntrusiveRefCntPtr<vfs::FileSystem> FS) {
556#define CGSCC_PASS(NAME, CREATE_PASS, PARSER) \
557 if (PassBuilder::checkParametrizedPassName(Name, NAME)) { \
558 auto Params = PassBuilder::parsePassParameters(PARSER, Name, NAME); \
559 if (!Params) \
560 return Params.takeError(); \
561 CGPM.addPass(CREATE_PASS); \
562 return true; \
563 }
564#include "PollyPasses.def"
565
566 return false;
567}
568
569static llvm::Expected<bool>
570parseFunctionPipeline(StringRef Name, FunctionPassManager &FPM,
571 PassInstrumentationCallbacks *PIC,
572 ArrayRef<PassBuilder::PipelineElement> Pipeline) {
573
574#define FUNCTION_PASS(NAME, CREATE_PASS, PARSER) \
575 if (PassBuilder::checkParametrizedPassName(Name, NAME)) { \
576 auto ExpectedOpts = PassBuilder::parsePassParameters(PARSER, Name, NAME); \
577 if (!ExpectedOpts) \
578 return ExpectedOpts.takeError(); \
579 auto &&Opts = *ExpectedOpts; \
580 (void)Opts; \
581 FPM.addPass(CREATE_PASS); \
582 return true; \
583 }
584
585#include "PollyPasses.def"
586 return false;
587}
588
589static llvm::Expected<bool>
590parseModulePipeline(StringRef Name, llvm::ModulePassManager &MPM,
591 PassInstrumentationCallbacks *PIC,
592 ArrayRef<PassBuilder::PipelineElement> Pipeline) {
593#define MODULE_PASS(NAME, CREATE_PASS, PARSER) \
594 if (PassBuilder::checkParametrizedPassName(Name, NAME)) { \
595 auto ExpectedOpts = PassBuilder::parsePassParameters(PARSER, Name, NAME); \
596 if (!ExpectedOpts) \
597 return ExpectedOpts.takeError(); \
598 auto &&Opts = *ExpectedOpts; \
599 (void)Opts; \
600 MPM.addPass(CREATE_PASS); \
601 return true; \
602 }
603
604#include "PollyPasses.def"
605
606 return false;
607}
608
609/// Register Polly to be available as an optimizer
610///
611///
612/// We can currently run Polly at two different points int the pass manager.
613/// a) very early, b) right before the vectorizer.
614///
615/// The default is currently a), to register Polly such that it runs as early as
616/// possible. This has several implications:
617///
618/// 1) We need to schedule more canonicalization passes
619///
620/// As nothing is run before Polly, it is necessary to run a set of preparing
621/// transformations before Polly to canonicalize the LLVM-IR and to allow
622/// Polly to detect and understand the code.
623///
624/// 2) We get the full -O3 optimization sequence after Polly
625///
626/// The LLVM-IR that is generated by Polly has been optimized on a high level,
627/// but it may be rather inefficient on the lower/scalar level. By scheduling
628/// Polly before all other passes, we have the full sequence of -O3
629/// optimizations behind us, such that inefficiencies on the low level can
630/// be optimized away.
631///
632/// We are currently evaluating the benefit or running Polly at b). b) is nice
633/// as everything is fully inlined and canonicalized, but we need to be able to
634/// handle LICMed code to make it useful.
635void registerPollyPasses(PassBuilder &PB) {
636 PassInstrumentationCallbacks *PIC = PB.getPassInstrumentationCallbacks();
637 IntrusiveRefCntPtr<vfs::FileSystem> FS = PB.getVirtualFileSystemPtr();
638 LLVMContext &Context = PB.getContext();
639
640#define MODULE_PASS(NAME, CREATE_PASS, PARSER) \
641 { \
642 std::remove_reference_t<decltype(*PARSER(StringRef()))> Opts; \
643 (void)Opts; \
644 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); \
645 }
646#define CGSCC_PASS(NAME, CREATE_PASS, PARSER) \
647 { \
648 std::remove_reference_t<decltype(*PARSER(StringRef()))> Opts; \
649 (void)Opts; \
650 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); \
651 }
652#define FUNCTION_PASS(NAME, CREATE_PASS, PARSER) \
653 { \
654 std::remove_reference_t<decltype(*PARSER(StringRef()))> Opts; \
655 (void)Opts; \
656 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); \
657 }
658#include "PollyPasses.def"
659
660 PB.registerPipelineParsingCallback(
661 [PIC](StringRef Name, FunctionPassManager &FPM,
662 ArrayRef<PassBuilder::PipelineElement> Pipeline) -> bool {
663 ExitOnError Err("Unable to parse Polly module pass: ");
664 return Err(parseFunctionPipeline(Name, FPM, PIC, Pipeline));
665 });
666 PB.registerPipelineParsingCallback(
667 [PIC, FS](StringRef Name, CGSCCPassManager &CGPM,
668 ArrayRef<PassBuilder::PipelineElement> Pipeline) -> bool {
669 ExitOnError Err("Unable to parse Polly call graph pass: ");
670 return Err(parseCGPipeline(Name, CGPM, PIC, Pipeline, FS));
671 });
672 PB.registerPipelineParsingCallback(
673 [PIC](StringRef Name, ModulePassManager &MPM,
674 ArrayRef<PassBuilder::PipelineElement> Pipeline) -> bool {
675 ExitOnError Err("Unable to parse Polly module pass: ");
676 return Err(parseModulePipeline(Name, MPM, PIC, Pipeline));
677 });
678
679 switch (PassPosition) {
680 case POSITION_EARLY:
681 PB.registerPipelineStartEPCallback(
682 [FS, &Context](ModulePassManager &MPM, OptimizationLevel Level) {
683 buildEarlyPollyPipeline(Context, MPM, Level, FS);
684 });
685 break;
687 PB.registerVectorizerStartEPCallback(
688 [FS, &Context](FunctionPassManager &FPM, OptimizationLevel Level) {
689 buildLatePollyPipeline(Context, FPM, Level, FS);
690 });
691 break;
692 }
693}
694} // namespace polly
695
696static Error parseArguments(ArrayRef<const char *> Args) {
697 SmallVector<const char *> Argv = {"Polly"};
698 append_range(Argv, Args);
699 std::string Msg;
700 raw_string_ostream OS(Msg);
701 if (!cl::ParseCommandLineOptions(Argv.size(), Argv.data(), "", &OS))
702 return createStringError(StringRef(Msg).trim());
703 return Error::success();
704}
705
706llvm::PassPluginLibraryInfo getPollyPluginInfo() {
707 llvm::PassPluginLibraryInfo Info = {LLVM_PLUGIN_API_VERSION, "Polly",
708 LLVM_VERSION_STRING,
710 Info.ParseArguments = parseArguments;
711 return Info;
712}
llvm::cl::OptionCategory PollyCategory
static Error parseArguments(ArrayRef< const char * > Args)
llvm::PassPluginLibraryInfo getPollyPluginInfo()
Options for the Polly pass.
Dependences::AnalysisLevel PrintDepsAnalysisLevel
void enableDefaultOpts()
Enabled the default optimization phases.
void setPhaseEnabled(PassPhase Phase, bool Enabled=true)
void enableEnd2End()
Enable all phases that are necessary for a roundtrip from LLVM-IR back to LLVM-IR.
void disableAfter(PassPhase Phase)
Disable all phases following Phase.
llvm::Error checkConsistency() const
Check whether the options are coherent relative to each other.
static __isl_give isl_union_map * append_range(__isl_take isl_union_map *umap, int extra)
const char * str
Definition isl_test.c:1880
static cl::opt< bool > ExportJScop("polly-export", cl::desc("Export the polyhedral description of the detected Scops"), cl::Hidden, cl::cat(PollyCategory))
static cl::opt< bool > FullyIndexedStaticExpansion("polly-enable-mse", cl::desc("Fully expand the memory accesses of the detected Scops"), cl::Hidden, cl::cat(PollyCategory))
@ POSITION_BEFORE_VECTORIZER
static llvm::Expected< PollyPassOptions > parsePollyCustomOptions(StringRef Params)
static cl::list< std::string > DumpBeforeFile("polly-dump-before-file", cl::desc("Dump module before Polly transformations to the given file"), cl::cat(PollyCategory))
static cl::opt< bool > PollyPrintDeps("polly-print-deps", cl::desc("Polly - Print dependences"), cl::cat(PollyCategory))
static bool shouldEnablePollyForDiagnostic()
static llvm::Expected< bool > parseFunctionPipeline(StringRef Name, FunctionPassManager &FPM, PassInstrumentationCallbacks *PIC, ArrayRef< PassBuilder::PipelineElement > Pipeline)
PassPhase parsePhase(StringRef Name)
static void buildLatePollyPipeline(LLVMContext &Context, FunctionPassManager &PM, llvm::OptimizationLevel Level, IntrusiveRefCntPtr< vfs::FileSystem > FS)
static cl::opt< VectorizerChoice, true > Vectorizer("polly-vectorizer", cl::desc("Select the vectorization strategy"), cl::values(clEnumValN(VECTORIZER_NONE, "none", "No Vectorization"), clEnumValN(VECTORIZER_STRIPMINE, "stripmine", "Strip-mine outer loops for the loop-vectorizer to trigger")), cl::location(PollyVectorizerChoice), cl::init(VECTORIZER_NONE), cl::cat(PollyCategory))
static cl::opt< bool > PollyOnlyViewer("polly-show-only", cl::desc("Highlight the code regions that will be optimized in " "a (CFG only BBs)"), cl::init(false), cl::cat(PollyCategory))
static void buildEarlyPollyPipeline(LLVMContext &Context, llvm::ModulePassManager &MPM, llvm::OptimizationLevel Level, IntrusiveRefCntPtr< vfs::FileSystem > FS)
static cl::opt< bool > EnableSimplify("polly-enable-simplify", cl::desc("Simplify SCoP after optimizations"), cl::init(true), cl::cat(PollyCategory))
bool PollyTrackFailures
StringRef getPhaseName(PassPhase Phase)
static cl::opt< bool > PollyPrintDetect("polly-print-detect", cl::desc("Polly - Print static control parts (SCoPs)"), cl::cat(PollyCategory))
static cl::opt< OptimizerChoice > Optimizer("polly-optimizer", cl::desc("Select the scheduling optimizer"), cl::values(clEnumValN(OPTIMIZER_NONE, "none", "No optimizer"), clEnumValN(OPTIMIZER_ISL, "isl", "The isl scheduling optimizer")), cl::Hidden, cl::init(OPTIMIZER_ISL), cl::cat(PollyCategory))
void registerPollyPasses(llvm::PassBuilder &PB)
static cl::opt< bool > PollyViewer("polly-show", cl::desc("Highlight the code regions that will be optimized in a " "(CFG BBs and LLVM-IR instructions)"), cl::cat(PollyCategory))
static cl::opt< bool > PollyPrinter("polly-dot", cl::desc("Enable the Polly DOT printer in -O3"), cl::Hidden, cl::value_desc("Run the Polly DOT printer at -O3"), cl::init(false), cl::cat(PollyCategory))
static cl::opt< bool > PollyEnabled("polly", cl::desc("Enable the polly optimizer (with -O1, -O2 or -O3)"), cl::cat(PollyCategory))
static llvm::Expected< bool > parseCGPipeline(StringRef Name, llvm::CGSCCPassManager &CGPM, PassInstrumentationCallbacks *PIC, ArrayRef< PassBuilder::PipelineElement > Pipeline, IntrusiveRefCntPtr< vfs::FileSystem > FS)
@ VECTORIZER_STRIPMINE
@ VECTORIZER_NONE
VectorizerChoice PollyVectorizerChoice
static cl::opt< bool > DumpBefore("polly-dump-before", cl::desc("Dump module before Polly transformations into a file " "suffixed with \"-before\""), cl::init(false), cl::cat(PollyCategory))
Dependences::AnalysisLevel OptAnalysisLevel
static llvm::Expected< PollyPassOptions > parsePollyDefaultOptions(StringRef Params)
static cl::opt< bool > EnableForwardOpTree("polly-enable-optree", cl::desc("Enable operand tree forwarding"), cl::Hidden, cl::init(true), cl::cat(PollyCategory))
static llvm::Expected< PollyPassOptions > parsePollyOptions(StringRef Params, bool IsCustom)
Parser of parameters for LoopVectorize pass.
static cl::opt< bool > DumpAfter("polly-dump-after", cl::desc("Dump module after Polly transformations into a file " "suffixed with \"-after\""), cl::init(false), cl::cat(PollyCategory))
static cl::opt< bool > PollyDetectOnly("polly-only-scop-detection", cl::desc("Only run scop detection, but no other optimizations"), cl::cat(PollyCategory))
static cl::opt< bool > CFGPrinter("polly-view-cfg", cl::desc("Show the Polly CFG right after code generation"), cl::Hidden, cl::init(false), cl::cat(PollyCategory))
static cl::opt< bool > DeadCodeElim("polly-run-dce", cl::desc("Run the dead code elimination"), cl::Hidden, cl::cat(PollyCategory))
bool dependsOnDependenceInfo(PassPhase Phase)
static cl::opt< bool > EnablePruneUnprofitable("polly-enable-prune-unprofitable", cl::desc("Bail out on unprofitable SCoPs before rescheduling"), cl::Hidden, cl::init(true), cl::cat(PollyCategory))
static cl::opt< bool > EnableDeLICM("polly-enable-delicm", cl::desc("Eliminate scalar loop carried dependences"), cl::Hidden, cl::init(true), cl::cat(PollyCategory))
PassPhase
Phases (in execution order) within the Polly pass.
static cl::opt< bool > PollyPrintScops("polly-print-scops", cl::desc("Print polyhedral description of all regions"), cl::cat(PollyCategory))
std::string ViewFilter
static cl::opt< bool > ImportJScop("polly-import", cl::desc("Import the polyhedral description of the detected Scops"), cl::Hidden, cl::cat(PollyCategory))
static cl::opt< bool > PollyOnlyPrinter("polly-dot-only", cl::desc("Enable the Polly DOT printer in -O3 (no BB content)"), cl::Hidden, cl::value_desc("Run the Polly DOT printer at -O3 (no BB content"), cl::init(false), cl::cat(PollyCategory))
llvm::FunctionPassManager buildCanonicalicationPassesForNPM(llvm::ModulePassManager &MPM, llvm::OptimizationLevel Level)
Schedule a set of canonicalization passes to prepare for Polly.
static cl::opt< PassPositionChoice > PassPosition("polly-position", cl::desc("Where to run polly in the pass pipeline"), cl::values(clEnumValN(POSITION_EARLY, "early", "Before everything"), clEnumValN(POSITION_BEFORE_VECTORIZER, "before-vectorizer", "Right before the vectorizer")), cl::Hidden, cl::init(POSITION_BEFORE_VECTORIZER), cl::cat(PollyCategory))
static cl::list< std::string > DumpAfterFile("polly-dump-after-file", cl::desc("Dump module after Polly transformations to the given file"), cl::cat(PollyCategory))
static bool shouldEnablePollyForOptimization()
static llvm::Expected< std::monostate > parseNoOptions(StringRef Params)
static void buildCommonPollyPipeline(LLVMContext &Context, FunctionPassManager &PM, OptimizationLevel Level, IntrusiveRefCntPtr< vfs::FileSystem > FS, bool EnableForOpt)
Register Polly passes such that they form a polyhedral optimizer.
static llvm::Expected< bool > parseModulePipeline(StringRef Name, llvm::ModulePassManager &MPM, PassInstrumentationCallbacks *PIC, ArrayRef< PassBuilder::PipelineElement > Pipeline)
static cl::opt< CodeGenChoice > CodeGeneration("polly-code-generation", cl::desc("How much code-generation to perform"), cl::values(clEnumValN(CODEGEN_FULL, "full", "AST and IR generation"), clEnumValN(CODEGEN_AST, "ast", "Only AST generation"), clEnumValN(CODEGEN_NONE, "none", "No code generation")), cl::Hidden, cl::init(CODEGEN_FULL), cl::cat(PollyCategory))
A pass that isolates a function into a new Module and writes it into a file.
A pass that prints the module into a file.