Polly 24.0.0git
IslAst.cpp
Go to the documentation of this file.
1//===- IslAst.cpp - isl code generator interface --------------------------===//
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// The isl code generator interface takes a Scop and generates an isl_ast. This
10// ist_ast can either be returned directly or it can be pretty printed to
11// stdout.
12//
13// A typical isl_ast output looks like this:
14//
15// for (c2 = max(0, ceild(n + m, 2); c2 <= min(511, floord(5 * n, 3)); c2++) {
16// bb2(c2);
17// }
18//
19// An in-depth discussion of our AST generation approach can be found in:
20//
21// Polyhedral AST generation is more than scanning polyhedra
22// Tobias Grosser, Sven Verdoolaege, Albert Cohen
23// ACM Transactions on Programming Languages and Systems (TOPLAS),
24// 37(4), July 2015
25// http://www.grosser.es/#pub-polyhedral-AST-generation
26//
27//===----------------------------------------------------------------------===//
28
32#include "polly/Options.h"
33#include "polly/ScopDetection.h"
34#include "polly/ScopInfo.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/IR/Function.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/raw_ostream.h"
40#include "isl/aff.h"
41#include "isl/ast.h"
42#include "isl/ast_build.h"
43#include "isl/id.h"
45#include "isl/printer.h"
46#include "isl/schedule.h"
47#include "isl/set.h"
48#include "isl/union_map.h"
49#include "isl/val.h"
50#include <cassert>
51#include <cstdlib>
52
54#define DEBUG_TYPE "polly-ast"
55
56using namespace llvm;
57using namespace polly;
58
60
61static cl::opt<bool>
62 PollyParallel("polly-parallel",
63 cl::desc("Generate thread parallel code (isl codegen only)"),
64 cl::cat(PollyCategory));
65
66static cl::opt<bool> PrintAccesses("polly-ast-print-accesses",
67 cl::desc("Print memory access functions"),
68 cl::cat(PollyCategory));
69
70static cl::opt<bool> PollyParallelForce(
71 "polly-parallel-force",
72 cl::desc(
73 "Force generation of thread parallel code ignoring any cost model"),
74 cl::cat(PollyCategory));
75
76static cl::opt<bool> UseContext("polly-ast-use-context",
77 cl::desc("Use context"), cl::Hidden,
78 cl::init(true), cl::cat(PollyCategory));
79
80static cl::opt<bool> DetectParallel("polly-ast-detect-parallel",
81 cl::desc("Detect parallelism"), cl::Hidden,
82 cl::cat(PollyCategory));
83
84extern cl::opt<bool> PollyVectorizeMetadata;
85
86static cl::opt<bool>
87 PollyPrintAst("polly-print-ast",
88 cl::desc("Print the ISL abstract syntax tree"),
89 cl::cat(PollyCategory));
90
91static cl::opt<unsigned long>
92 AstGenComputeout("polly-astgen-computeout",
93 cl::desc("Bound the AST generation by a maximal number of "
94 "ISL operations [0 means un-bounded]"),
95 cl::Hidden, cl::init(3000000), cl::cat(PollyCategory));
96STATISTIC(ScopsProcessed, "Number of SCoPs processed");
97STATISTIC(ScopsBeneficial, "Number of beneficial SCoPs");
98STATISTIC(BeneficialAffineLoops, "Number of beneficial affine loops");
99STATISTIC(BeneficialBoxedLoops, "Number of beneficial boxed loops");
100
101STATISTIC(NumForLoops, "Number of for-loops");
102STATISTIC(NumParallel, "Number of parallel for-loops");
103STATISTIC(NumInnermostParallel, "Number of innermost parallel for-loops");
104STATISTIC(NumOutermostParallel, "Number of outermost parallel for-loops");
105STATISTIC(NumReductionParallel, "Number of reduction-parallel for-loops");
106STATISTIC(NumExecutedInParallel, "Number of for-loops executed in parallel");
107STATISTIC(NumIfConditions, "Number of if-conditions");
108
109namespace polly {
110
111/// Temporary information used when building the ast.
113 /// Construct and initialize the helper struct for AST creation.
114 AstBuildUserInfo() = default;
115
116 /// The dependence information used for the parallelism check.
117 const Dependences *Deps = nullptr;
118
119 /// Flag to indicate that we are inside a parallel for node.
120 bool InParallelFor = false;
121
122 /// Flag to indicate that we are inside an SIMD node.
123 bool InSIMD = false;
124
125 /// The last iterator id created for the current SCoP.
127};
128} // namespace polly
129
130/// Free an IslAstUserPayload object pointed to by @p Ptr.
131static void freeIslAstUserPayload(void *Ptr) {
132 delete ((IslAstInfo::IslAstUserPayload *)Ptr);
133}
134
135/// Print a string @p str in a single line using @p Printer.
137 const std::string &str,
138 __isl_keep isl_pw_aff *PWA = nullptr) {
139 Printer = isl_printer_start_line(Printer);
140 Printer = isl_printer_print_str(Printer, str.c_str());
141 if (PWA)
142 Printer = isl_printer_print_pw_aff(Printer, PWA);
143 return isl_printer_end_line(Printer);
144}
145
146/// Return all broken reductions as a string of clauses (OpenMP style).
147static std::string getBrokenReductionsStr(const isl::ast_node &Node) {
148 IslAstInfo::MemoryAccessSet *BrokenReductions;
149 std::string str;
150
151 BrokenReductions = IslAstInfo::getBrokenReductions(Node);
152 if (!BrokenReductions || BrokenReductions->empty())
153 return "";
154
155 // Map each type of reduction to a comma separated list of the base addresses.
156 std::map<MemoryAccess::ReductionType, std::string> Clauses;
157 for (MemoryAccess *MA : *BrokenReductions)
158 if (MA->isWrite())
159 Clauses[MA->getReductionType()] +=
160 ", " + MA->getScopArrayInfo()->getName();
161
162 // Now print the reductions sorted by type. Each type will cause a clause
163 // like: reduction (+ : sum0, sum1, sum2)
164 for (const auto &ReductionClause : Clauses) {
165 str += " reduction (";
166 str += MemoryAccess::getReductionOperatorStr(ReductionClause.first);
167 // Remove the first two symbols (", ") to make the output look pretty.
168 str += " : " + ReductionClause.second.substr(2) + ")";
169 }
170
171 return str;
172}
173
174/// Callback executed for each for node in the ast in order to print it.
177 __isl_keep isl_ast_node *Node, void *) {
178 isl::pw_aff DD =
180 const std::string BrokenReductionsStr =
182 const std::string KnownParallelStr = "#pragma known-parallel";
183 const std::string DepDisPragmaStr = "#pragma minimal dependence distance: ";
184 const std::string SimdPragmaStr = "#pragma simd";
185 const std::string OmpPragmaStr = "#pragma omp parallel for";
186
187 if (!DD.is_null())
188 Printer = printLine(Printer, DepDisPragmaStr, DD.get());
189
191 Printer = printLine(Printer, SimdPragmaStr + BrokenReductionsStr);
192
194 Printer = printLine(Printer, OmpPragmaStr);
196 Printer = printLine(Printer, KnownParallelStr + BrokenReductionsStr);
197
198 return isl_ast_node_for_print(Node, Printer, Options);
199}
200
201/// Check if the current scheduling dimension is parallel.
202///
203/// In case the dimension is parallel we also check if any reduction
204/// dependences is broken when we exploit this parallelism. If so,
205/// @p IsReductionParallel will be set to true. The reduction dependences we use
206/// to check are actually the union of the transitive closure of the initial
207/// reduction dependences together with their reversal. Even though these
208/// dependences connect all iterations with each other (thus they are cyclic)
209/// we can perform the parallelism check as we are only interested in a zero
210/// (or non-zero) dependence distance on the dimension in question.
212 const Dependences *D,
213 IslAstUserPayload *NodeInfo) {
214 if (!D || !D->hasValidDependences())
215 return false;
216
217 isl::union_map Schedule = Build.get_schedule();
220
221 isl::boolean IsParallel = D->isKnownParallel(Schedule, Dep);
222 if (IsParallel.is_error())
223 return false;
224 if (IsParallel.is_false()) {
225 isl::union_map DepsAll =
228 isl::pw_aff MinimalDependenceDistance;
229 isl::boolean IsParallelWithDistance =
230 D->isKnownParallel(Schedule, DepsAll, &MinimalDependenceDistance);
231 if (IsParallelWithDistance.is_false())
232 NodeInfo->MinimalDependenceDistance = MinimalDependenceDistance;
233 return false;
234 }
235
237 if (D->isKnownParallel(Schedule, RedDeps).is_false())
238 NodeInfo->IsReductionParallel = true;
239
240 if (!NodeInfo->IsReductionParallel)
241 return true;
242
243 for (const auto &MaRedPair : D->getReductionDependences()) {
244 if (!MaRedPair.second)
245 continue;
246 isl::union_map MaRedDeps = isl::manage_copy(MaRedPair.second);
247 if (D->isKnownParallel(Schedule, MaRedDeps).is_false())
248 NodeInfo->BrokenReductions.insert(MaRedPair.first);
249 }
250 return true;
251}
252
253// This method is executed before the construction of a for node. It creates
254// an isl_id that is used to annotate the subsequently generated ast for nodes.
255//
256// In this function we also run the following analyses:
257//
258// - Detection of openmp parallel loops
259//
261 void *User) {
262 AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
263 IslAstUserPayload *Payload = new IslAstUserPayload();
264 isl_id *Id = isl_id_alloc(isl_ast_build_get_ctx(Build), "", Payload);
266 BuildInfo->LastForNodeId = Id;
267
269 BuildInfo->Deps, Payload);
270
271 // Test for parallelism only if we are not already inside a parallel loop
272 if (!BuildInfo->InParallelFor && !BuildInfo->InSIMD)
273 BuildInfo->InParallelFor = Payload->IsOutermostParallel =
274 Payload->IsParallel;
275
276 return Id;
277}
278
279// This method is executed after the construction of a for node.
280//
281// It performs the following actions:
282//
283// - Reset the 'InParallelFor' flag, as soon as we leave a for node,
284// that is marked as openmp parallel.
285//
288 void *User) {
290 assert(Id && "Post order visit assumes annotated for nodes");
292 assert(Payload && "Post order visit assumes annotated for nodes");
293
294 AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
295 assert(Payload->Build.is_null() && "Build environment already set");
296 Payload->Build = isl::manage_copy(Build);
297 Payload->IsInnermost = (Id == BuildInfo->LastForNodeId);
298
299 Payload->IsInnermostParallel =
300 Payload->IsInnermost && (BuildInfo->InSIMD || Payload->IsParallel);
301 if (Payload->IsOutermostParallel)
302 BuildInfo->InParallelFor = false;
303
304 isl_id_free(Id);
305 return Node;
306}
307
310 void *User) {
311 if (!MarkId)
312 return isl_stat_error;
313
314 AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
315 if (strcmp(isl_id_get_name(MarkId), "SIMD") == 0)
316 BuildInfo->InSIMD = true;
317
318 return isl_stat_ok;
319}
320
323 __isl_keep isl_ast_build *Build, void *User) {
325 AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
326 auto *Id = isl_ast_node_mark_get_id(Node);
327 if (!Id)
328 return Node;
329 if (strcmp(isl_id_get_name(Id), "SIMD") == 0)
330 BuildInfo->InSIMD = false;
331 isl_id_free(Id);
332 return Node;
333}
334
337 void *User) {
338 assert(!isl_ast_node_get_annotation(Node) && "Node already annotated");
339
340 IslAstUserPayload *Payload = new IslAstUserPayload();
341 isl_id *Id = isl_id_alloc(isl_ast_build_get_ctx(Build), "", Payload);
343
344 Payload->Build = isl::manage_copy(Build);
345
346 return isl_ast_node_set_annotation(Node, Id);
347}
348
349// Build alias check condition given a pair of minimal/maximal access.
351 const Scop::MinMaxAccessTy *It0,
352 const Scop::MinMaxAccessTy *It1) {
353
354 isl::pw_multi_aff AFirst = It0->first;
355 isl::pw_multi_aff ASecond = It0->second;
356 isl::pw_multi_aff BFirst = It1->first;
357 isl::pw_multi_aff BSecond = It1->second;
358
359 isl::id Left = AFirst.get_tuple_id(isl::dim::set);
360 isl::id Right = BFirst.get_tuple_id(isl::dim::set);
361
362 isl::ast_expr True =
364 isl::ast_expr False =
366
367 const ScopArrayInfo *BaseLeft =
369 const ScopArrayInfo *BaseRight =
371 if (BaseLeft && BaseLeft == BaseRight)
372 return True;
373
374 isl::set Params = S.getContext();
375
376 isl::ast_expr NonAliasGroup, MinExpr, MaxExpr;
377
378 // In the following, we first check if any accesses will be empty under
379 // the execution context of the scop and do not code generate them if this
380 // is the case as isl will fail to derive valid AST expressions for such
381 // accesses.
382
383 if (!AFirst.intersect_params(Params).domain().is_empty() &&
384 !BSecond.intersect_params(Params).domain().is_empty()) {
385 MinExpr = Build.access_from(AFirst).address_of();
386 MaxExpr = Build.access_from(BSecond).address_of();
387 NonAliasGroup = MaxExpr.le(MinExpr);
388 }
389
390 if (!BFirst.intersect_params(Params).domain().is_empty() &&
391 !ASecond.intersect_params(Params).domain().is_empty()) {
392 MinExpr = Build.access_from(BFirst).address_of();
393 MaxExpr = Build.access_from(ASecond).address_of();
394
395 isl::ast_expr Result = MaxExpr.le(MinExpr);
396 if (!NonAliasGroup.is_null())
397 NonAliasGroup = isl::manage(
398 isl_ast_expr_or(NonAliasGroup.release(), Result.release()));
399 else
400 NonAliasGroup = Result;
401 }
402
403 if (NonAliasGroup.is_null())
404 NonAliasGroup = True;
405
406 return NonAliasGroup;
407}
408
411
412 // The conditions that need to be checked at run-time for this scop are
413 // available as an isl_set in the runtime check context from which we can
414 // directly derive a run-time condition.
415 auto PosCond = Build.expr_from(S.getAssumedContext());
416 if (S.hasTrivialInvalidContext()) {
417 RunCondition = std::move(PosCond);
418 } else {
419 auto ZeroV = isl::val::zero(Build.ctx());
420 auto NegCond = Build.expr_from(S.getInvalidContext());
421 auto NotNegCond =
422 isl::ast_expr::from_val(std::move(ZeroV)).eq(std::move(NegCond));
424 isl::manage(isl_ast_expr_and(PosCond.release(), NotNegCond.release()));
425 }
426
427 // Create the alias checks from the minimal/maximal accesses in each alias
428 // group which consists of read only and non read only (read write) accesses.
429 // This operation is by construction quadratic in the read-write pointers and
430 // linear in the read only pointers in each alias group.
431 for (const Scop::MinMaxVectorPairTy &MinMaxAccessPair : S.getAliasGroups()) {
432 auto &MinMaxReadWrite = MinMaxAccessPair.first;
433 auto &MinMaxReadOnly = MinMaxAccessPair.second;
434 auto RWAccEnd = MinMaxReadWrite.end();
435
436 for (auto RWAccIt0 = MinMaxReadWrite.begin(); RWAccIt0 != RWAccEnd;
437 ++RWAccIt0) {
438 for (auto RWAccIt1 = RWAccIt0 + 1; RWAccIt1 != RWAccEnd; ++RWAccIt1)
440 RunCondition.release(),
441 buildCondition(S, Build, RWAccIt0, RWAccIt1).release()));
442 for (const Scop::MinMaxAccessTy &ROAccIt : MinMaxReadOnly)
444 RunCondition.release(),
445 buildCondition(S, Build, RWAccIt0, &ROAccIt).release()));
446 }
447 }
448
449 return RunCondition;
450}
451
452/// Simple cost analysis for a given SCoP.
453///
454/// TODO: Improve this analysis and extract it to make it usable in other
455/// places too.
456/// In order to improve the cost model we could either keep track of
457/// performed optimizations (e.g., tiling) or compute properties on the
458/// original as well as optimized SCoP (e.g., #stride-one-accesses).
459static bool benefitsFromPolly(Scop &Scop, bool PerformParallelTest) {
461 return true;
462
463 // Check if nothing interesting happened.
464 if (!PerformParallelTest && !Scop.isOptimized() &&
465 Scop.getAliasGroups().empty())
466 return false;
467
468 // The default assumption is that Polly improves the code.
469 return true;
470}
471
472/// Collect statistics for the syntax tree rooted at @p Ast.
473static void walkAstForStatistics(const isl::ast_node &Ast) {
474 assert(!Ast.is_null());
476 Ast.get(),
477 [](__isl_keep isl_ast_node *Node, void *User) -> isl_bool {
478 switch (isl_ast_node_get_type(Node)) {
479 case isl_ast_node_for:
480 NumForLoops++;
481 if (IslAstInfo::isParallel(isl::manage_copy(Node)))
482 NumParallel++;
483 if (IslAstInfo::isInnermostParallel(isl::manage_copy(Node)))
484 NumInnermostParallel++;
485 if (IslAstInfo::isOutermostParallel(isl::manage_copy(Node)))
486 NumOutermostParallel++;
487 if (IslAstInfo::isReductionParallel(isl::manage_copy(Node)))
488 NumReductionParallel++;
489 if (IslAstInfo::isExecutedInParallel(isl::manage_copy(Node)))
490 NumExecutedInParallel++;
491 break;
492
493 case isl_ast_node_if:
494 NumIfConditions++;
495 break;
496
497 default:
498 break;
499 }
500
501 // Continue traversing subtrees.
502 return isl_bool_true;
503 },
504 nullptr);
505}
506
508
510 : S(O.S), Ctx(O.Ctx), RunCondition(std::move(O.RunCondition)),
511 Root(std::move(O.Root)) {}
512
513void IslAst::init(const Dependences &D) {
514 bool PerformParallelTest = PollyParallel || DetectParallel ||
517 auto ScheduleTree = S.getScheduleTree();
518
519 // Skip AST and code generation if there was no benefit achieved.
520 if (!benefitsFromPolly(S, PerformParallelTest))
521 return;
522
523 auto ScopStats = S.getStatistics();
524 ScopsBeneficial++;
525 BeneficialAffineLoops += ScopStats.NumAffineLoops;
526 BeneficialBoxedLoops += ScopStats.NumBoxedLoops;
527
528 auto Ctx = S.getIslCtx();
531 isl_ast_build *Build;
532 AstBuildUserInfo BuildInfo;
533
534 if (UseContext)
535 Build = isl_ast_build_from_context(S.getContext().release());
536 else
538 isl_set_universe(S.getParamSpace().release()));
539
540 Build = isl_ast_build_set_at_each_domain(Build, AtEachDomain, nullptr);
541
542 if (PerformParallelTest) {
543 BuildInfo.Deps = &D;
544 BuildInfo.InParallelFor = false;
545 BuildInfo.InSIMD = false;
546
548 &BuildInfo);
549 Build =
551
553 &BuildInfo);
554
556 &BuildInfo);
557 }
558
560 // Apply IslMaxOperationsGuard on the API that starts the process of AST
561 // generation from the schedule tree. This is to avoid a timeout when the
562 // schedule tree is too big and complex.
563
564 {
565 IslMaxOperationsGuard MaxOpGuard(Ctx.get(), AstGenComputeout);
567 isl_ast_build_node_from_schedule(Build, S.getScheduleTree().release()));
568 if (MaxOpGuard.hasQuotaExceeded()) {
570 dbgs() << "AST generation for SCoP in function '"
571 << S.getFunction().getName()
572 << "' exceeded operation limit (operations). Skipping.\n");
573 }
574 }
575 if (!Root.is_null())
577
578 isl_ast_build_free(Build);
579}
580
582 IslAst Ast{Scop};
583 Ast.init(D);
584 return Ast;
585}
586
589
591isl::ast_expr IslAstInfo::getRunCondition() { return Ast.getRunCondition(); }
592
594 isl::id Id = Node.get_annotation();
595 if (Id.is_null())
596 return nullptr;
597 IslAstUserPayload *Payload = (IslAstUserPayload *)Id.get_user();
598 return Payload;
599}
600
602 IslAstUserPayload *Payload = getNodePayload(Node);
603 return Payload && Payload->IsInnermost;
604}
605
610
612 IslAstUserPayload *Payload = getNodePayload(Node);
613 return Payload && Payload->IsInnermostParallel;
614}
615
617 IslAstUserPayload *Payload = getNodePayload(Node);
618 return Payload && Payload->IsOutermostParallel;
619}
620
622 IslAstUserPayload *Payload = getNodePayload(Node);
623 return Payload && Payload->IsReductionParallel;
624}
625
627 if (!PollyParallel)
628 return false;
629
630 // Do not parallelize innermost loops.
631 //
632 // Parallelizing innermost loops is often not profitable, especially if
633 // they have a low number of iterations.
634 //
635 // TODO: Decide this based on the number of loop iterations that will be
636 // executed. This can possibly require run-time checks, which again
637 // raises the question of both run-time check overhead and code size
638 // costs.
639 if (!PollyParallelForce && isInnermost(Node))
640 return false;
641
642 return isOutermostParallel(Node) && !isReductionParallel(Node);
643}
644
646 IslAstUserPayload *Payload = getNodePayload(Node);
647 return Payload ? Payload->Build.get_schedule() : isl::union_map();
648}
649
652 IslAstUserPayload *Payload = getNodePayload(Node);
653 return Payload ? Payload->MinimalDependenceDistance : isl::pw_aff();
654}
655
658 IslAstUserPayload *Payload = getNodePayload(Node);
659 return Payload ? &Payload->BrokenReductions : nullptr;
660}
661
663 IslAstUserPayload *Payload = getNodePayload(Node);
664 return Payload ? Payload->Build : isl::ast_build();
665}
666
667static std::unique_ptr<IslAstInfo> runIslAst(
668 Scop &Scop,
669 function_ref<const Dependences &(Dependences::AnalysisLevel)> GetDeps) {
670 ScopsProcessed++;
671
672 const Dependences &D = GetDeps(Dependences::AL_Statement);
673
674 if (D.getSharedIslCtx() != Scop.getSharedIslCtx()) {
676 dbgs() << "Got dependence analysis for different SCoP/isl_ctx\n");
677 return {};
678 }
679
680 std::unique_ptr<IslAstInfo> Ast = std::make_unique<IslAstInfo>(Scop, D);
681
683 if (Ast)
684 Ast->print(dbgs());
685 });
686
687 return Ast;
688}
689
693 void *User) {
695 isl::ast_expr NodeExpr = AstNode.expr();
696 isl::ast_expr CallExpr = NodeExpr.get_op_arg(0);
697 isl::id CallExprId = CallExpr.get_id();
698 ScopStmt *AccessStmt = (ScopStmt *)CallExprId.get_user();
699
701 P = isl_printer_print_str(P, AccessStmt->getBaseName());
702 P = isl_printer_print_str(P, "(");
704 P = isl_printer_indent(P, 2);
705
706 for (MemoryAccess *MemAcc : *AccessStmt) {
708
709 if (MemAcc->isRead())
710 P = isl_printer_print_str(P, "/* read */ &");
711 else
712 P = isl_printer_print_str(P, "/* write */ ");
713
715 if (MemAcc->isAffine()) {
716 isl_pw_multi_aff *PwmaPtr =
717 MemAcc->applyScheduleToAccessRelation(Build.get_schedule()).release();
718 isl::pw_multi_aff Pwma = isl::manage(PwmaPtr);
719 isl::ast_expr AccessExpr = Build.access_from(Pwma);
720 P = isl_printer_print_ast_expr(P, AccessExpr.get());
721 } else {
723 P, MemAcc->getLatestScopArrayInfo()->getName().c_str());
724 P = isl_printer_print_str(P, "[*]");
725 }
727 }
728
729 P = isl_printer_indent(P, -2);
731 P = isl_printer_print_str(P, ");");
733
735 return P;
736}
737
738void IslAstInfo::print(raw_ostream &OS) {
739 isl_ast_print_options *Options;
740 isl::ast_node RootNode = Ast.getAst();
741 Function &F = S.getFunction();
742
743 OS << ":: isl ast :: " << F.getName() << " :: " << S.getNameStr() << "\n";
744
745 if (RootNode.is_null()) {
746 OS << ":: isl ast generation and code generation was skipped!\n\n";
747 OS << ":: This is either because no useful optimizations could be applied "
748 "(use -polly-process-unprofitable to enforce code generation) or "
749 "because earlier passes such as dependence analysis timed out (use "
750 "-polly-dependences-computeout=0 to set dependence analysis timeout "
751 "to infinity)\n\n";
752 return;
753 }
754
755 isl::ast_expr RunCondition = Ast.getRunCondition();
756 char *RtCStr, *AstStr;
757
758 Options = isl_ast_print_options_alloc(S.getIslCtx().get());
759
760 if (PrintAccesses)
761 Options =
763 Options = isl_ast_print_options_set_print_for(Options, cbPrintFor, nullptr);
764
765 isl_printer *P = isl_printer_to_str(S.getIslCtx().get());
767 P = isl_printer_print_ast_expr(P, RunCondition.get());
768 RtCStr = isl_printer_get_str(P);
769 P = isl_printer_flush(P);
770 P = isl_printer_indent(P, 4);
771 P = isl_ast_node_print(RootNode.get(), P, Options);
772 AstStr = isl_printer_get_str(P);
773
775 dbgs() << S.getContextStr() << "\n";
776 dbgs() << stringFromIslObj(S.getScheduleTree(), "null");
777 });
778 OS << "\nif (" << RtCStr << ")\n\n";
779 OS << AstStr << "\n";
780 OS << "else\n";
781 OS << " { /* original code */ }\n\n";
782
783 free(RtCStr);
784 free(AstStr);
785
787}
788
789std::unique_ptr<IslAstInfo>
791 auto GetDeps = [&](Dependences::AnalysisLevel Lvl) -> const Dependences & {
792 return DA.getDependences(Lvl);
793 };
794
795 std::unique_ptr<IslAstInfo> Result = runIslAst(S, GetDeps);
796 if (PollyPrintAst) {
797 outs() << "Printing analysis 'Polly - Generate an AST of the SCoP (isl)'"
798 << S.getName() << "' in function '" << S.getFunction().getName()
799 << "':\n";
800 if (Result)
801 Result->print(llvm::outs());
802 }
803 return Result;
804}
static cl::opt< bool > UseContext("polly-ast-use-context", cl::desc("Use context"), cl::Hidden, cl::init(true), cl::cat(PollyCategory))
static cl::opt< bool > PollyPrintAst("polly-print-ast", cl::desc("Print the ISL abstract syntax tree"), cl::cat(PollyCategory))
static cl::opt< unsigned long > AstGenComputeout("polly-astgen-computeout", cl::desc("Bound the AST generation by a maximal number of " "ISL operations [0 means un-bounded]"), cl::Hidden, cl::init(3000000), cl::cat(PollyCategory))
static isl::ast_expr buildCondition(Scop &S, isl::ast_build Build, const Scop::MinMaxAccessTy *It0, const Scop::MinMaxAccessTy *It1)
Definition IslAst.cpp:350
static cl::opt< bool > DetectParallel("polly-ast-detect-parallel", cl::desc("Detect parallelism"), cl::Hidden, cl::cat(PollyCategory))
static isl_printer * printLine(__isl_take isl_printer *Printer, const std::string &str, __isl_keep isl_pw_aff *PWA=nullptr)
Print a string str in a single line using Printer.
Definition IslAst.cpp:136
static __isl_give isl_id * astBuildBeforeFor(__isl_keep isl_ast_build *Build, void *User)
Definition IslAst.cpp:260
static __isl_give isl_ast_node * astBuildAfterMark(__isl_take isl_ast_node *Node, __isl_keep isl_ast_build *Build, void *User)
Definition IslAst.cpp:322
IslAstInfo::IslAstUserPayload IslAstUserPayload
Definition IslAst.cpp:59
static void walkAstForStatistics(const isl::ast_node &Ast)
Collect statistics for the syntax tree rooted at Ast.
Definition IslAst.cpp:473
static cl::opt< bool > PollyParallelForce("polly-parallel-force", cl::desc("Force generation of thread parallel code ignoring any cost model"), cl::cat(PollyCategory))
cl::opt< bool > PollyVectorizeMetadata
static bool benefitsFromPolly(Scop &Scop, bool PerformParallelTest)
Simple cost analysis for a given SCoP.
Definition IslAst.cpp:459
static __isl_give isl_ast_node * astBuildAfterFor(__isl_take isl_ast_node *Node, __isl_keep isl_ast_build *Build, void *User)
Definition IslAst.cpp:287
STATISTIC(ScopsProcessed, "Number of SCoPs processed")
static __isl_give isl_ast_node * AtEachDomain(__isl_take isl_ast_node *Node, __isl_keep isl_ast_build *Build, void *User)
Definition IslAst.cpp:335
static bool astScheduleDimIsParallel(const isl::ast_build &Build, const Dependences *D, IslAstUserPayload *NodeInfo)
Check if the current scheduling dimension is parallel.
Definition IslAst.cpp:211
static isl_printer * cbPrintFor(__isl_take isl_printer *Printer, __isl_take isl_ast_print_options *Options, __isl_keep isl_ast_node *Node, void *)
Callback executed for each for node in the ast in order to print it.
Definition IslAst.cpp:175
static cl::opt< bool > PrintAccesses("polly-ast-print-accesses", cl::desc("Print memory access functions"), cl::cat(PollyCategory))
static std::string getBrokenReductionsStr(const isl::ast_node &Node)
Return all broken reductions as a string of clauses (OpenMP style).
Definition IslAst.cpp:147
static isl_stat astBuildBeforeMark(__isl_keep isl_id *MarkId, __isl_keep isl_ast_build *Build, void *User)
Definition IslAst.cpp:308
static __isl_give isl_printer * cbPrintUser(__isl_take isl_printer *P, __isl_take isl_ast_print_options *O, __isl_keep isl_ast_node *Node, void *User)
Definition IslAst.cpp:690
static cl::opt< bool > PollyParallel("polly-parallel", cl::desc("Generate thread parallel code (isl codegen only)"), cl::cat(PollyCategory))
static void freeIslAstUserPayload(void *Ptr)
Free an IslAstUserPayload object pointed to by Ptr.
Definition IslAst.cpp:131
static std::unique_ptr< IslAstInfo > runIslAst(Scop &Scop, function_ref< const Dependences &(Dependences::AnalysisLevel)> GetDeps)
Definition IslAst.cpp:667
llvm::cl::OptionCategory PollyCategory
#define POLLY_DEBUG(X)
Definition PollyDebug.h:23
__isl_give isl_printer * isl_printer_print_pw_aff(__isl_take isl_printer *p, __isl_keep isl_pw_aff *pwaff)
__isl_give isl_ast_node * isl_ast_node_set_annotation(__isl_take isl_ast_node *node, __isl_take isl_id *annotation)
__isl_give isl_printer * isl_ast_node_print(__isl_keep isl_ast_node *node, __isl_take isl_printer *p, __isl_take isl_ast_print_options *options)
Definition isl_ast.c:3215
isl_stat isl_ast_node_foreach_descendant_top_down(__isl_keep isl_ast_node *node, isl_bool(*fn)(__isl_keep isl_ast_node *node, void *user), void *user)
Definition isl_ast.c:1888
__isl_give isl_ast_print_options * isl_ast_print_options_alloc(isl_ctx *ctx)
Definition isl_ast.c:35
__isl_give isl_ast_expr * isl_ast_expr_or(__isl_take isl_ast_expr *expr1, __isl_take isl_ast_expr *expr2)
Definition isl_ast.c:763
__isl_give isl_ast_print_options * isl_ast_print_options_set_print_user(__isl_take isl_ast_print_options *options, __isl_give isl_printer *(*print_user)(__isl_take isl_printer *p, __isl_take isl_ast_print_options *options, __isl_keep isl_ast_node *node, void *user), void *user)
Definition isl_ast.c:114
__isl_give isl_printer * isl_ast_node_for_print(__isl_keep isl_ast_node *node, __isl_take isl_printer *p, __isl_take isl_ast_print_options *options)
Definition isl_ast.c:3176
__isl_give isl_ast_print_options * isl_ast_print_options_set_print_for(__isl_take isl_ast_print_options *options, __isl_give isl_printer *(*print_for)(__isl_take isl_printer *p, __isl_take isl_ast_print_options *options, __isl_keep isl_ast_node *node, void *user), void *user)
Definition isl_ast.c:135
__isl_export __isl_give isl_id * isl_ast_node_mark_get_id(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1640
__isl_give isl_id * isl_ast_node_get_annotation(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1704
__isl_null isl_ast_print_options * isl_ast_print_options_free(__isl_take isl_ast_print_options *options)
Definition isl_ast.c:94
__isl_give isl_ast_expr * isl_ast_expr_and(__isl_take isl_ast_expr *expr1, __isl_take isl_ast_expr *expr2)
Definition isl_ast.c:746
__isl_give isl_printer * isl_printer_print_ast_expr(__isl_take isl_printer *p, __isl_keep isl_ast_expr *expr)
Definition isl_ast.c:2600
__isl_give isl_ast_build * isl_ast_build_set_before_each_mark(__isl_take isl_ast_build *build, isl_stat(*fn)(__isl_keep isl_id *mark, __isl_keep isl_ast_build *build, void *user), void *user)
isl_stat isl_options_set_ast_build_detect_min_max(isl_ctx *ctx, int val)
__isl_give isl_ast_build * isl_ast_build_set_before_each_for(__isl_take isl_ast_build *build, __isl_give isl_id *(*fn)(__isl_keep isl_ast_build *build, void *user), void *user)
__isl_export __isl_give isl_ast_build * isl_ast_build_from_context(__isl_take isl_set *set)
isl_stat isl_options_set_ast_build_atomic_upper_bound(isl_ctx *ctx, int val)
__isl_give isl_ast_build * isl_ast_build_set_after_each_mark(__isl_take isl_ast_build *build, __isl_give isl_ast_node *(*fn)(__isl_take isl_ast_node *node, __isl_keep isl_ast_build *build, void *user), void *user)
__isl_null isl_ast_build * isl_ast_build_free(__isl_take isl_ast_build *build)
__isl_overload __isl_give isl_ast_node * isl_ast_build_node_from_schedule(__isl_keep isl_ast_build *build, __isl_take isl_schedule *schedule)
__isl_export __isl_give isl_ast_build * isl_ast_build_set_at_each_domain(__isl_take isl_ast_build *build, __isl_give isl_ast_node *(*fn)(__isl_take isl_ast_node *node, __isl_keep isl_ast_build *build, void *user), void *user)
isl_ctx * isl_ast_build_get_ctx(__isl_keep isl_ast_build *build)
__isl_give isl_ast_build * isl_ast_build_set_after_each_for(__isl_take isl_ast_build *build, __isl_give isl_ast_node *(*fn)(__isl_take isl_ast_node *node, __isl_keep isl_ast_build *build, void *user), void *user)
@ isl_ast_node_mark
Definition ast_type.h:87
static isl::ast_expr from_val(isl::val v)
isl::checked::ast_expr access_from(isl::checked::multi_pw_aff mpa) const
isl::checked::union_map get_schedule() const
isl::checked::ast_expr expr_from(isl::checked::pw_aff pa) const
isl::checked::ctx ctx() const
__isl_give isl_ast_expr * release()
__isl_keep isl_ast_expr * get() const
isl::checked::ast_expr expr() const
__isl_keep isl_ast_node * get() const
bool is_error() const
Definition cpp-checked.h:75
bool is_false() const
Definition cpp-checked.h:76
bool is_null() const
__isl_keep isl_pw_aff * get() const
isl::checked::pw_multi_aff intersect_params(isl::checked::set set) const
isl::checked::set domain() const
boolean is_empty() const
static isl::val zero(isl::ctx ctx)
static isl::val int_from_ui(isl::ctx ctx, unsigned long u)
The accumulated dependence information for a SCoP.
bool hasValidDependences() const
Report if valid dependences are available.
const std::shared_ptr< isl_ctx > & getSharedIslCtx() const
isl::union_map getDependences(int Kinds) const
Get the dependences of type Kinds.
isl::boolean isKnownParallel(isl::union_map Schedule, isl::union_map Deps, isl::pw_aff *MinDistancePtr=nullptr) const
Check if a partial schedule is parallel wrt to Deps.
__isl_give isl_map * getReductionDependences(MemoryAccess *MA) const
Return the reduction dependences caused by MA.
static bool isOutermostParallel(const isl::ast_node &Node)
Is this loop an outermost parallel loop?
Definition IslAst.cpp:616
static MemoryAccessSet * getBrokenReductions(const isl::ast_node &Node)
Get the nodes broken reductions or a nullptr if not available.
Definition IslAst.cpp:657
static bool isParallel(const isl::ast_node &Node)
Is this loop a parallel loop?
Definition IslAst.cpp:606
static isl::pw_aff getMinimalDependenceDistance(const isl::ast_node &Node)
Get minimal dependence distance or nullptr if not available.
Definition IslAst.cpp:651
static bool isInnermostParallel(const isl::ast_node &Node)
Is this loop an innermost parallel loop?
Definition IslAst.cpp:611
isl::ast_node getAst()
Return a copy of the AST root node.
Definition IslAst.cpp:590
SmallPtrSet< MemoryAccess *, 4 > MemoryAccessSet
Definition IslAst.h:71
static bool isExecutedInParallel(const isl::ast_node &Node)
Will the loop be run as thread parallel?
Definition IslAst.cpp:626
isl::ast_expr getRunCondition()
Get the run condition.
Definition IslAst.cpp:591
static bool isInnermost(const isl::ast_node &Node)
Is this loop an innermost loop?
Definition IslAst.cpp:601
static IslAstUserPayload * getNodePayload(const isl::ast_node &Node)
Definition IslAst.cpp:593
static isl::union_map getSchedule(const isl::ast_node &Node)
Get the nodes schedule or a nullptr if not available.
Definition IslAst.cpp:645
void print(raw_ostream &O)
Definition IslAst.cpp:738
static isl::ast_build getBuild(const isl::ast_node &Node)
Get the nodes build context or a nullptr if not available.
Definition IslAst.cpp:662
static bool isReductionParallel(const isl::ast_node &Node)
Is this loop a reduction parallel loop?
Definition IslAst.cpp:621
const std::shared_ptr< isl_ctx > getSharedIslCtx() const
Definition IslAst.h:45
static isl::ast_expr buildRunCondition(Scop &S, const isl::ast_build &Build)
Build run-time condition for scop.
Definition IslAst.cpp:409
Scop & S
Definition IslAst.h:59
isl::ast_node Root
Definition IslAst.h:62
isl::ast_expr getRunCondition()
Get the run-time conditions for the Scop.
Definition IslAst.cpp:588
IslAst(const IslAst &)=delete
std::shared_ptr< isl_ctx > Ctx
Definition IslAst.h:60
static IslAst create(Scop &Scop, const Dependences &D)
Definition IslAst.cpp:581
isl::ast_expr RunCondition
Definition IslAst.h:61
isl::ast_node getAst()
Definition IslAst.cpp:587
void init(const Dependences &D)
Definition IslAst.cpp:513
Scoped limit of ISL operations.
Definition GICHelper.h:424
bool hasQuotaExceeded() const
Return whether the current quota has exceeded.
Definition GICHelper.h:483
Represent memory accesses in statements.
Definition ScopInfo.h:427
std::string getReductionOperatorStr() const
Return a string representation of the access's reduction type.
Definition ScopInfo.cpp:910
A class to store information about arrays in the SCoP.
Definition ScopInfo.h:215
static const ScopArrayInfo * getFromId(isl::id Id)
Access the ScopArrayInfo associated with an isl Id.
Definition ScopInfo.cpp:381
const ScopArrayInfo * getBasePtrOriginSAI() const
For indirect accesses return the origin SAI of the BP, else null.
Definition ScopInfo.h:268
Statement of the Scop.
Definition ScopInfo.h:1136
const char * getBaseName() const
Static Control Part.
Definition ScopInfo.h:1626
const MinMaxVectorPairVectorTy & getAliasGroups() const
Return all alias groups for this SCoP.
Definition ScopInfo.h:2278
std::pair< MinMaxVectorTy, MinMaxVectorTy > MinMaxVectorPairTy
Pair of minimal/maximal access vectors representing read write and read only accesses.
Definition ScopInfo.h:1636
const std::shared_ptr< isl_ctx > & getSharedIslCtx() const
Directly return the shared_ptr of the context.
Definition ScopInfo.h:2479
std::pair< isl::pw_multi_aff, isl::pw_multi_aff > MinMaxAccessTy
Type to represent a pair of minimal/maximal access to an array.
Definition ScopInfo.h:1629
bool isOptimized() const
Check if the SCoP has been optimized by the scheduler.
Definition ScopInfo.h:2143
#define __isl_take
Definition ctx.h:23
isl_stat
Definition ctx.h:85
@ isl_stat_error
Definition ctx.h:86
@ isl_stat_ok
Definition ctx.h:87
#define __isl_give
Definition ctx.h:20
#define __isl_keep
Definition ctx.h:26
isl_bool
Definition ctx.h:90
@ isl_bool_true
Definition ctx.h:93
__isl_export __isl_keep const char * isl_id_get_name(__isl_keep isl_id *id)
Definition isl_id.c:41
__isl_null isl_id * isl_id_free(__isl_take isl_id *id)
Definition isl_id.c:207
void * isl_id_get_user(__isl_keep isl_id *id)
Definition isl_id.c:36
__isl_give isl_id * isl_id_alloc(isl_ctx *ctx, __isl_keep const char *name, void *user)
__isl_give isl_id * isl_id_set_free_user(__isl_take isl_id *id, void(*free_user)(void *user))
Definition isl_id.c:183
enum isl_ast_node_type isl_ast_node_get_type(__isl_keep isl_ast_node *node)
Definition isl_ast.c:907
#define S(TYPE, NAME)
const char * str
Definition isl_test.c:1880
#define assert(exp)
boolean manage(isl_bool val)
Definition cpp-checked.h:98
aff manage_copy(__isl_keep isl_aff *ptr)
@ VECTORIZER_NONE
VectorizerChoice PollyVectorizerChoice
bool PollyProcessUnprofitable
std::unique_ptr< IslAstInfo > runIslAstGen(Scop &S, DependenceAnalysis::Result &DA)
Definition IslAst.cpp:790
__isl_null isl_printer * isl_printer_free(__isl_take isl_printer *printer)
#define ISL_FORMAT_C
Definition printer.h:31
__isl_give isl_printer * isl_printer_flush(__isl_take isl_printer *p)
__isl_give char * isl_printer_get_str(__isl_keep isl_printer *printer)
__isl_give isl_printer * isl_printer_print_str(__isl_take isl_printer *p, const char *s)
__isl_give isl_printer * isl_printer_start_line(__isl_take isl_printer *p)
__isl_give isl_printer * isl_printer_indent(__isl_take isl_printer *p, int indent)
__isl_give isl_printer * isl_printer_to_str(isl_ctx *ctx)
__isl_give isl_printer * isl_printer_end_line(__isl_take isl_printer *p)
__isl_give isl_printer * isl_printer_set_output_format(__isl_take isl_printer *p, int output_format)
__isl_export __isl_give isl_set * isl_set_universe(__isl_take isl_space *space)
Definition isl_map.c:6985
Temporary information used when building the ast.
Definition IslAst.cpp:112
AstBuildUserInfo()=default
Construct and initialize the helper struct for AST creation.
bool InParallelFor
Flag to indicate that we are inside a parallel for node.
Definition IslAst.cpp:120
isl_id * LastForNodeId
The last iterator id created for the current SCoP.
Definition IslAst.cpp:126
const Dependences * Deps
The dependence information used for the parallelism check.
Definition IslAst.cpp:117
bool InSIMD
Flag to indicate that we are inside an SIMD node.
Definition IslAst.cpp:123
const Dependences & getDependences(Dependences::AnalysisLevel Level)
Return the dependence information for the current SCoP.
Payload information used to annotate an AST node.
Definition IslAst.h:74
bool IsInnermost
Flag to mark innermost loops.
Definition IslAst.h:83
bool IsOutermostParallel
Flag to mark outermost parallel loops.
Definition IslAst.h:89
bool IsParallel
Does the dependence analysis determine that there are no loop-carried dependencies?
Definition IslAst.h:80
MemoryAccessSet BrokenReductions
Set of accesses which break reduction dependences.
Definition IslAst.h:101
isl::pw_aff MinimalDependenceDistance
The minimal dependence distance for non parallel loops.
Definition IslAst.h:95
bool IsReductionParallel
Flag to mark parallel loops which break reductions.
Definition IslAst.h:92
bool IsInnermostParallel
Flag to mark innermost parallel loops.
Definition IslAst.h:86
isl::ast_build Build
The build environment at the time this node was constructed.
Definition IslAst.h:98