1 //===- IslAst.cpp - isl code generator interface --------------------------===//
2 //
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 //
10 // The isl code generator interface takes a Scop and generates an isl_ast. This
11 // ist_ast can either be returned directly or it can be pretty printed to
12 // stdout.
13 //
14 // A typical isl_ast output looks like this:
15 //
16 // for (c2 = max(0, ceild(n + m, 2); c2 <= min(511, floord(5 * n, 3)); c2++) {
17 //   bb2(c2);
18 // }
19 //
20 // An in-depth discussion of our AST generation approach can be found in:
21 //
22 // Polyhedral AST generation is more than scanning polyhedra
23 // Tobias Grosser, Sven Verdoolaege, Albert Cohen
24 // ACM Transactions on Programming Languages and Systems (TOPLAS),
25 // 37(4), July 2015
26 // http://www.grosser.es/#pub-polyhedral-AST-generation
27 //
28 //===----------------------------------------------------------------------===//
29 
30 #include "polly/CodeGen/IslAst.h"
31 #include "polly/CodeGen/CodeGeneration.h"
32 #include "polly/DependenceInfo.h"
33 #include "polly/LinkAllPasses.h"
34 #include "polly/Options.h"
35 #include "polly/ScopInfo.h"
36 #include "polly/Support/GICHelper.h"
37 #include "llvm/Analysis/RegionInfo.h"
38 #include "llvm/Support/Debug.h"
39 #include "isl/aff.h"
40 #include "isl/ast_build.h"
41 #include "isl/list.h"
42 #include "isl/map.h"
43 #include "isl/set.h"
44 #include "isl/union_map.h"
45 
46 #include <utility>
47 
48 #define DEBUG_TYPE "polly-ast"
49 
50 using namespace llvm;
51 using namespace polly;
52 
53 using IslAstUserPayload = IslAstInfo::IslAstUserPayload;
54 
55 static cl::opt<bool>
56     PollyParallel("polly-parallel",
57                   cl::desc("Generate thread parallel code (isl codegen only)"),
58                   cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
59 
60 static cl::opt<bool> PrintAccesses("polly-ast-print-accesses",
61                                    cl::desc("Print memory access functions"),
62                                    cl::init(false), cl::ZeroOrMore,
63                                    cl::cat(PollyCategory));
64 
65 static cl::opt<bool> PollyParallelForce(
66     "polly-parallel-force",
67     cl::desc(
68         "Force generation of thread parallel code ignoring any cost model"),
69     cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
70 
71 static cl::opt<bool> UseContext("polly-ast-use-context",
72                                 cl::desc("Use context"), cl::Hidden,
73                                 cl::init(true), cl::ZeroOrMore,
74                                 cl::cat(PollyCategory));
75 
76 static cl::opt<bool> DetectParallel("polly-ast-detect-parallel",
77                                     cl::desc("Detect parallelism"), cl::Hidden,
78                                     cl::init(false), cl::ZeroOrMore,
79                                     cl::cat(PollyCategory));
80 
81 namespace polly {
82 /// Temporary information used when building the ast.
83 struct AstBuildUserInfo {
84   /// Construct and initialize the helper struct for AST creation.
85   AstBuildUserInfo()
86       : Deps(nullptr), InParallelFor(false), LastForNodeId(nullptr) {}
87 
88   /// The dependence information used for the parallelism check.
89   const Dependences *Deps;
90 
91   /// Flag to indicate that we are inside a parallel for node.
92   bool InParallelFor;
93 
94   /// The last iterator id created for the current SCoP.
95   isl_id *LastForNodeId;
96 };
97 } // namespace polly
98 
99 /// Free an IslAstUserPayload object pointed to by @p Ptr.
100 static void freeIslAstUserPayload(void *Ptr) {
101   delete ((IslAstInfo::IslAstUserPayload *)Ptr);
102 }
103 
104 IslAstInfo::IslAstUserPayload::~IslAstUserPayload() {
105   isl_ast_build_free(Build);
106   isl_pw_aff_free(MinimalDependenceDistance);
107 }
108 
109 /// Print a string @p str in a single line using @p Printer.
110 static isl_printer *printLine(__isl_take isl_printer *Printer,
111                               const std::string &str,
112                               __isl_keep isl_pw_aff *PWA = nullptr) {
113   Printer = isl_printer_start_line(Printer);
114   Printer = isl_printer_print_str(Printer, str.c_str());
115   if (PWA)
116     Printer = isl_printer_print_pw_aff(Printer, PWA);
117   return isl_printer_end_line(Printer);
118 }
119 
120 /// Return all broken reductions as a string of clauses (OpenMP style).
121 static const std::string getBrokenReductionsStr(__isl_keep isl_ast_node *Node) {
122   IslAstInfo::MemoryAccessSet *BrokenReductions;
123   std::string str;
124 
125   BrokenReductions = IslAstInfo::getBrokenReductions(Node);
126   if (!BrokenReductions || BrokenReductions->empty())
127     return "";
128 
129   // Map each type of reduction to a comma separated list of the base addresses.
130   std::map<MemoryAccess::ReductionType, std::string> Clauses;
131   for (MemoryAccess *MA : *BrokenReductions)
132     if (MA->isWrite())
133       Clauses[MA->getReductionType()] +=
134           ", " + MA->getScopArrayInfo()->getName();
135 
136   // Now print the reductions sorted by type. Each type will cause a clause
137   // like:  reduction (+ : sum0, sum1, sum2)
138   for (const auto &ReductionClause : Clauses) {
139     str += " reduction (";
140     str += MemoryAccess::getReductionOperatorStr(ReductionClause.first);
141     // Remove the first two symbols (", ") to make the output look pretty.
142     str += " : " + ReductionClause.second.substr(2) + ")";
143   }
144 
145   return str;
146 }
147 
148 /// Callback executed for each for node in the ast in order to print it.
149 static isl_printer *cbPrintFor(__isl_take isl_printer *Printer,
150                                __isl_take isl_ast_print_options *Options,
151                                __isl_keep isl_ast_node *Node, void *) {
152 
153   isl_pw_aff *DD = IslAstInfo::getMinimalDependenceDistance(Node);
154   const std::string BrokenReductionsStr = getBrokenReductionsStr(Node);
155   const std::string KnownParallelStr = "#pragma known-parallel";
156   const std::string DepDisPragmaStr = "#pragma minimal dependence distance: ";
157   const std::string SimdPragmaStr = "#pragma simd";
158   const std::string OmpPragmaStr = "#pragma omp parallel for";
159 
160   if (DD)
161     Printer = printLine(Printer, DepDisPragmaStr, DD);
162 
163   if (IslAstInfo::isInnermostParallel(Node))
164     Printer = printLine(Printer, SimdPragmaStr + BrokenReductionsStr);
165 
166   if (IslAstInfo::isExecutedInParallel(Node))
167     Printer = printLine(Printer, OmpPragmaStr);
168   else if (IslAstInfo::isOutermostParallel(Node))
169     Printer = printLine(Printer, KnownParallelStr + BrokenReductionsStr);
170 
171   isl_pw_aff_free(DD);
172   return isl_ast_node_for_print(Node, Printer, Options);
173 }
174 
175 /// Check if the current scheduling dimension is parallel.
176 ///
177 /// In case the dimension is parallel we also check if any reduction
178 /// dependences is broken when we exploit this parallelism. If so,
179 /// @p IsReductionParallel will be set to true. The reduction dependences we use
180 /// to check are actually the union of the transitive closure of the initial
181 /// reduction dependences together with their reversal. Even though these
182 /// dependences connect all iterations with each other (thus they are cyclic)
183 /// we can perform the parallelism check as we are only interested in a zero
184 /// (or non-zero) dependence distance on the dimension in question.
185 static bool astScheduleDimIsParallel(__isl_keep isl_ast_build *Build,
186                                      const Dependences *D,
187                                      IslAstUserPayload *NodeInfo) {
188   if (!D->hasValidDependences())
189     return false;
190 
191   isl_union_map *Schedule = isl_ast_build_get_schedule(Build);
192   isl_union_map *Deps = D->getDependences(
193       Dependences::TYPE_RAW | Dependences::TYPE_WAW | Dependences::TYPE_WAR);
194 
195   if (!D->isParallel(Schedule, Deps, &NodeInfo->MinimalDependenceDistance) &&
196       !isl_union_map_free(Schedule))
197     return false;
198 
199   isl_union_map *RedDeps = D->getDependences(Dependences::TYPE_TC_RED);
200   if (!D->isParallel(Schedule, RedDeps))
201     NodeInfo->IsReductionParallel = true;
202 
203   if (!NodeInfo->IsReductionParallel && !isl_union_map_free(Schedule))
204     return true;
205 
206   // Annotate reduction parallel nodes with the memory accesses which caused the
207   // reduction dependences parallel execution of the node conflicts with.
208   for (const auto &MaRedPair : D->getReductionDependences()) {
209     if (!MaRedPair.second)
210       continue;
211     RedDeps = isl_union_map_from_map(isl_map_copy(MaRedPair.second));
212     if (!D->isParallel(Schedule, RedDeps))
213       NodeInfo->BrokenReductions.insert(MaRedPair.first);
214   }
215 
216   isl_union_map_free(Schedule);
217   return true;
218 }
219 
220 // This method is executed before the construction of a for node. It creates
221 // an isl_id that is used to annotate the subsequently generated ast for nodes.
222 //
223 // In this function we also run the following analyses:
224 //
225 // - Detection of openmp parallel loops
226 //
227 static __isl_give isl_id *astBuildBeforeFor(__isl_keep isl_ast_build *Build,
228                                             void *User) {
229   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
230   IslAstUserPayload *Payload = new IslAstUserPayload();
231   isl_id *Id = isl_id_alloc(isl_ast_build_get_ctx(Build), "", Payload);
232   Id = isl_id_set_free_user(Id, freeIslAstUserPayload);
233   BuildInfo->LastForNodeId = Id;
234 
235   // Test for parallelism only if we are not already inside a parallel loop
236   if (!BuildInfo->InParallelFor)
237     BuildInfo->InParallelFor = Payload->IsOutermostParallel =
238         astScheduleDimIsParallel(Build, BuildInfo->Deps, Payload);
239 
240   return Id;
241 }
242 
243 // This method is executed after the construction of a for node.
244 //
245 // It performs the following actions:
246 //
247 // - Reset the 'InParallelFor' flag, as soon as we leave a for node,
248 //   that is marked as openmp parallel.
249 //
250 static __isl_give isl_ast_node *
251 astBuildAfterFor(__isl_take isl_ast_node *Node, __isl_keep isl_ast_build *Build,
252                  void *User) {
253   isl_id *Id = isl_ast_node_get_annotation(Node);
254   assert(Id && "Post order visit assumes annotated for nodes");
255   IslAstUserPayload *Payload = (IslAstUserPayload *)isl_id_get_user(Id);
256   assert(Payload && "Post order visit assumes annotated for nodes");
257 
258   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
259   assert(!Payload->Build && "Build environment already set");
260   Payload->Build = isl_ast_build_copy(Build);
261   Payload->IsInnermost = (Id == BuildInfo->LastForNodeId);
262 
263   // Innermost loops that are surrounded by parallel loops have not yet been
264   // tested for parallelism. Test them here to ensure we check all innermost
265   // loops for parallelism.
266   if (Payload->IsInnermost && BuildInfo->InParallelFor) {
267     if (Payload->IsOutermostParallel) {
268       Payload->IsInnermostParallel = true;
269     } else {
270       if (PollyVectorizerChoice == VECTORIZER_NONE)
271         Payload->IsInnermostParallel =
272             astScheduleDimIsParallel(Build, BuildInfo->Deps, Payload);
273     }
274   }
275   if (Payload->IsOutermostParallel)
276     BuildInfo->InParallelFor = false;
277 
278   isl_id_free(Id);
279   return Node;
280 }
281 
282 static isl_stat astBuildBeforeMark(__isl_keep isl_id *MarkId,
283                                    __isl_keep isl_ast_build *Build,
284                                    void *User) {
285   if (!MarkId)
286     return isl_stat_error;
287 
288   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
289   if (!strcmp(isl_id_get_name(MarkId), "SIMD"))
290     BuildInfo->InParallelFor = true;
291 
292   return isl_stat_ok;
293 }
294 
295 static __isl_give isl_ast_node *
296 astBuildAfterMark(__isl_take isl_ast_node *Node,
297                   __isl_keep isl_ast_build *Build, void *User) {
298   assert(isl_ast_node_get_type(Node) == isl_ast_node_mark);
299   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
300   auto *Id = isl_ast_node_mark_get_id(Node);
301   if (!strcmp(isl_id_get_name(Id), "SIMD"))
302     BuildInfo->InParallelFor = false;
303   isl_id_free(Id);
304   return Node;
305 }
306 
307 static __isl_give isl_ast_node *AtEachDomain(__isl_take isl_ast_node *Node,
308                                              __isl_keep isl_ast_build *Build,
309                                              void *User) {
310   assert(!isl_ast_node_get_annotation(Node) && "Node already annotated");
311 
312   IslAstUserPayload *Payload = new IslAstUserPayload();
313   isl_id *Id = isl_id_alloc(isl_ast_build_get_ctx(Build), "", Payload);
314   Id = isl_id_set_free_user(Id, freeIslAstUserPayload);
315 
316   Payload->Build = isl_ast_build_copy(Build);
317 
318   return isl_ast_node_set_annotation(Node, Id);
319 }
320 
321 // Build alias check condition given a pair of minimal/maximal access.
322 static __isl_give isl_ast_expr *
323 buildCondition(__isl_keep isl_ast_build *Build, const Scop::MinMaxAccessTy *It0,
324                const Scop::MinMaxAccessTy *It1) {
325   isl_ast_expr *NonAliasGroup, *MinExpr, *MaxExpr;
326   MinExpr = isl_ast_expr_address_of(isl_ast_build_access_from_pw_multi_aff(
327       Build, isl_pw_multi_aff_copy(It0->first)));
328   MaxExpr = isl_ast_expr_address_of(isl_ast_build_access_from_pw_multi_aff(
329       Build, isl_pw_multi_aff_copy(It1->second)));
330   NonAliasGroup = isl_ast_expr_le(MaxExpr, MinExpr);
331   MinExpr = isl_ast_expr_address_of(isl_ast_build_access_from_pw_multi_aff(
332       Build, isl_pw_multi_aff_copy(It1->first)));
333   MaxExpr = isl_ast_expr_address_of(isl_ast_build_access_from_pw_multi_aff(
334       Build, isl_pw_multi_aff_copy(It0->second)));
335   NonAliasGroup =
336       isl_ast_expr_or(NonAliasGroup, isl_ast_expr_le(MaxExpr, MinExpr));
337 
338   return NonAliasGroup;
339 }
340 
341 __isl_give isl_ast_expr *
342 IslAst::buildRunCondition(Scop &S, __isl_keep isl_ast_build *Build) {
343   isl_ast_expr *RunCondition;
344 
345   // The conditions that need to be checked at run-time for this scop are
346   // available as an isl_set in the runtime check context from which we can
347   // directly derive a run-time condition.
348   auto *PosCond =
349       isl_ast_build_expr_from_set(Build, S.getAssumedContext().release());
350   if (S.hasTrivialInvalidContext()) {
351     RunCondition = PosCond;
352   } else {
353     auto *ZeroV = isl_val_zero(isl_ast_build_get_ctx(Build));
354     auto *NegCond =
355         isl_ast_build_expr_from_set(Build, S.getInvalidContext().release());
356     auto *NotNegCond = isl_ast_expr_eq(isl_ast_expr_from_val(ZeroV), NegCond);
357     RunCondition = isl_ast_expr_and(PosCond, NotNegCond);
358   }
359 
360   // Create the alias checks from the minimal/maximal accesses in each alias
361   // group which consists of read only and non read only (read write) accesses.
362   // This operation is by construction quadratic in the read-write pointers and
363   // linear in the read only pointers in each alias group.
364   for (const Scop::MinMaxVectorPairTy &MinMaxAccessPair : S.getAliasGroups()) {
365     auto &MinMaxReadWrite = MinMaxAccessPair.first;
366     auto &MinMaxReadOnly = MinMaxAccessPair.second;
367     auto RWAccEnd = MinMaxReadWrite.end();
368 
369     for (auto RWAccIt0 = MinMaxReadWrite.begin(); RWAccIt0 != RWAccEnd;
370          ++RWAccIt0) {
371       for (auto RWAccIt1 = RWAccIt0 + 1; RWAccIt1 != RWAccEnd; ++RWAccIt1)
372         RunCondition = isl_ast_expr_and(
373             RunCondition, buildCondition(Build, RWAccIt0, RWAccIt1));
374       for (const Scop::MinMaxAccessTy &ROAccIt : MinMaxReadOnly)
375         RunCondition = isl_ast_expr_and(
376             RunCondition, buildCondition(Build, RWAccIt0, &ROAccIt));
377     }
378   }
379 
380   return RunCondition;
381 }
382 
383 /// Simple cost analysis for a given SCoP.
384 ///
385 /// TODO: Improve this analysis and extract it to make it usable in other
386 ///       places too.
387 ///       In order to improve the cost model we could either keep track of
388 ///       performed optimizations (e.g., tiling) or compute properties on the
389 ///       original as well as optimized SCoP (e.g., #stride-one-accesses).
390 static bool benefitsFromPolly(Scop &Scop, bool PerformParallelTest) {
391 
392   if (PollyProcessUnprofitable)
393     return true;
394 
395   // Check if nothing interesting happened.
396   if (!PerformParallelTest && !Scop.isOptimized() &&
397       Scop.getAliasGroups().empty())
398     return false;
399 
400   // The default assumption is that Polly improves the code.
401   return true;
402 }
403 
404 IslAst::IslAst(Scop &Scop)
405     : S(Scop), Root(nullptr), RunCondition(nullptr),
406       Ctx(Scop.getSharedIslCtx()) {}
407 
408 void IslAst::init(const Dependences &D) {
409   bool PerformParallelTest = PollyParallel || DetectParallel ||
410                              PollyVectorizerChoice != VECTORIZER_NONE;
411 
412   // We can not perform the dependence analysis and, consequently,
413   // the parallel code generation in case the schedule tree contains
414   // extension nodes.
415   auto *ScheduleTree = S.getScheduleTree().release();
416   PerformParallelTest =
417       PerformParallelTest && !S.containsExtensionNode(ScheduleTree);
418   isl_schedule_free(ScheduleTree);
419 
420   // Skip AST and code generation if there was no benefit achieved.
421   if (!benefitsFromPolly(S, PerformParallelTest))
422     return;
423 
424   isl_ctx *Ctx = S.getIslCtx();
425   isl_options_set_ast_build_atomic_upper_bound(Ctx, true);
426   isl_options_set_ast_build_detect_min_max(Ctx, true);
427   isl_ast_build *Build;
428   AstBuildUserInfo BuildInfo;
429 
430   if (UseContext)
431     Build = isl_ast_build_from_context(S.getContext().release());
432   else
433     Build = isl_ast_build_from_context(
434         isl_set_universe(S.getParamSpace().release()));
435 
436   Build = isl_ast_build_set_at_each_domain(Build, AtEachDomain, nullptr);
437 
438   if (PerformParallelTest) {
439     BuildInfo.Deps = &D;
440     BuildInfo.InParallelFor = 0;
441 
442     Build = isl_ast_build_set_before_each_for(Build, &astBuildBeforeFor,
443                                               &BuildInfo);
444     Build =
445         isl_ast_build_set_after_each_for(Build, &astBuildAfterFor, &BuildInfo);
446 
447     Build = isl_ast_build_set_before_each_mark(Build, &astBuildBeforeMark,
448                                                &BuildInfo);
449 
450     Build = isl_ast_build_set_after_each_mark(Build, &astBuildAfterMark,
451                                               &BuildInfo);
452   }
453 
454   RunCondition = buildRunCondition(S, Build);
455 
456   Root = isl_ast_build_node_from_schedule(Build, S.getScheduleTree().release());
457 
458   isl_ast_build_free(Build);
459 }
460 
461 IslAst IslAst::create(Scop &Scop, const Dependences &D) {
462   IslAst Ast{Scop};
463   Ast.init(D);
464   return Ast;
465 }
466 
467 IslAst::IslAst(IslAst &&O)
468     : S(O.S), Root(O.Root), RunCondition(O.RunCondition), Ctx(O.Ctx) {
469   O.Root = nullptr;
470   O.RunCondition = nullptr;
471 }
472 
473 IslAst::~IslAst() {
474   isl_ast_node_free(Root);
475   isl_ast_expr_free(RunCondition);
476 }
477 
478 __isl_give isl_ast_node *IslAst::getAst() { return isl_ast_node_copy(Root); }
479 __isl_give isl_ast_expr *IslAst::getRunCondition() {
480   return isl_ast_expr_copy(RunCondition);
481 }
482 
483 __isl_give isl_ast_node *IslAstInfo::getAst() { return Ast.getAst(); }
484 __isl_give isl_ast_expr *IslAstInfo::getRunCondition() {
485   return Ast.getRunCondition();
486 }
487 
488 IslAstUserPayload *IslAstInfo::getNodePayload(__isl_keep isl_ast_node *Node) {
489   isl_id *Id = isl_ast_node_get_annotation(Node);
490   if (!Id)
491     return nullptr;
492   IslAstUserPayload *Payload = (IslAstUserPayload *)isl_id_get_user(Id);
493   isl_id_free(Id);
494   return Payload;
495 }
496 
497 bool IslAstInfo::isInnermost(__isl_keep isl_ast_node *Node) {
498   IslAstUserPayload *Payload = getNodePayload(Node);
499   return Payload && Payload->IsInnermost;
500 }
501 
502 bool IslAstInfo::isParallel(__isl_keep isl_ast_node *Node) {
503   return IslAstInfo::isInnermostParallel(Node) ||
504          IslAstInfo::isOutermostParallel(Node);
505 }
506 
507 bool IslAstInfo::isInnermostParallel(__isl_keep isl_ast_node *Node) {
508   IslAstUserPayload *Payload = getNodePayload(Node);
509   return Payload && Payload->IsInnermostParallel;
510 }
511 
512 bool IslAstInfo::isOutermostParallel(__isl_keep isl_ast_node *Node) {
513   IslAstUserPayload *Payload = getNodePayload(Node);
514   return Payload && Payload->IsOutermostParallel;
515 }
516 
517 bool IslAstInfo::isReductionParallel(__isl_keep isl_ast_node *Node) {
518   IslAstUserPayload *Payload = getNodePayload(Node);
519   return Payload && Payload->IsReductionParallel;
520 }
521 
522 bool IslAstInfo::isExecutedInParallel(__isl_keep isl_ast_node *Node) {
523 
524   if (!PollyParallel)
525     return false;
526 
527   // Do not parallelize innermost loops.
528   //
529   // Parallelizing innermost loops is often not profitable, especially if
530   // they have a low number of iterations.
531   //
532   // TODO: Decide this based on the number of loop iterations that will be
533   //       executed. This can possibly require run-time checks, which again
534   //       raises the question of both run-time check overhead and code size
535   //       costs.
536   if (!PollyParallelForce && isInnermost(Node))
537     return false;
538 
539   return isOutermostParallel(Node) && !isReductionParallel(Node);
540 }
541 
542 __isl_give isl_union_map *
543 IslAstInfo::getSchedule(__isl_keep isl_ast_node *Node) {
544   IslAstUserPayload *Payload = getNodePayload(Node);
545   return Payload ? isl_ast_build_get_schedule(Payload->Build) : nullptr;
546 }
547 
548 __isl_give isl_pw_aff *
549 IslAstInfo::getMinimalDependenceDistance(__isl_keep isl_ast_node *Node) {
550   IslAstUserPayload *Payload = getNodePayload(Node);
551   return Payload ? isl_pw_aff_copy(Payload->MinimalDependenceDistance)
552                  : nullptr;
553 }
554 
555 IslAstInfo::MemoryAccessSet *
556 IslAstInfo::getBrokenReductions(__isl_keep isl_ast_node *Node) {
557   IslAstUserPayload *Payload = getNodePayload(Node);
558   return Payload ? &Payload->BrokenReductions : nullptr;
559 }
560 
561 isl_ast_build *IslAstInfo::getBuild(__isl_keep isl_ast_node *Node) {
562   IslAstUserPayload *Payload = getNodePayload(Node);
563   return Payload ? Payload->Build : nullptr;
564 }
565 
566 IslAstInfo IslAstAnalysis::run(Scop &S, ScopAnalysisManager &SAM,
567                                ScopStandardAnalysisResults &SAR) {
568   return {S, SAM.getResult<DependenceAnalysis>(S, SAR).getDependences(
569                  Dependences::AL_Statement)};
570 }
571 
572 static __isl_give isl_printer *cbPrintUser(__isl_take isl_printer *P,
573                                            __isl_take isl_ast_print_options *O,
574                                            __isl_keep isl_ast_node *Node,
575                                            void *User) {
576   isl::ast_node AstNode = isl::manage(isl_ast_node_copy(Node));
577   isl::ast_expr NodeExpr = AstNode.user_get_expr();
578   isl::ast_expr CallExpr = NodeExpr.get_op_arg(0);
579   isl::id CallExprId = CallExpr.get_id();
580   ScopStmt *AccessStmt = (ScopStmt *)CallExprId.get_user();
581 
582   P = isl_printer_start_line(P);
583   P = isl_printer_print_str(P, AccessStmt->getBaseName());
584   P = isl_printer_print_str(P, "(");
585   P = isl_printer_end_line(P);
586   P = isl_printer_indent(P, 2);
587 
588   for (MemoryAccess *MemAcc : *AccessStmt) {
589     P = isl_printer_start_line(P);
590 
591     if (MemAcc->isRead())
592       P = isl_printer_print_str(P, "/* read  */ &");
593     else
594       P = isl_printer_print_str(P, "/* write */  ");
595 
596     isl::ast_build Build =
597         isl::manage(isl_ast_build_copy(IslAstInfo::getBuild(Node)));
598     if (MemAcc->isAffine()) {
599       isl_pw_multi_aff *PwmaPtr =
600           MemAcc->applyScheduleToAccessRelation(Build.get_schedule()).release();
601       isl::pw_multi_aff Pwma = isl::manage(PwmaPtr);
602       isl::ast_expr AccessExpr = Build.access_from(Pwma);
603       P = isl_printer_print_ast_expr(P, AccessExpr.get());
604     } else {
605       P = isl_printer_print_str(
606           P, MemAcc->getLatestScopArrayInfo()->getName().c_str());
607       P = isl_printer_print_str(P, "[*]");
608     }
609     P = isl_printer_end_line(P);
610   }
611 
612   P = isl_printer_indent(P, -2);
613   P = isl_printer_start_line(P);
614   P = isl_printer_print_str(P, ");");
615   P = isl_printer_end_line(P);
616 
617   isl_ast_print_options_free(O);
618   return P;
619 }
620 
621 void IslAstInfo::print(raw_ostream &OS) {
622   isl_ast_print_options *Options;
623   isl_ast_node *RootNode = Ast.getAst();
624   Function &F = S.getFunction();
625 
626   OS << ":: isl ast :: " << F.getName() << " :: " << S.getNameStr() << "\n";
627 
628   if (!RootNode) {
629     OS << ":: isl ast generation and code generation was skipped!\n\n";
630     OS << ":: This is either because no useful optimizations could be applied "
631           "(use -polly-process-unprofitable to enforce code generation) or "
632           "because earlier passes such as dependence analysis timed out (use "
633           "-polly-dependences-computeout=0 to set dependence analysis timeout "
634           "to infinity)\n\n";
635     return;
636   }
637 
638   isl_ast_expr *RunCondition = Ast.getRunCondition();
639   char *RtCStr, *AstStr;
640 
641   Options = isl_ast_print_options_alloc(S.getIslCtx());
642 
643   if (PrintAccesses)
644     Options =
645         isl_ast_print_options_set_print_user(Options, cbPrintUser, nullptr);
646   Options = isl_ast_print_options_set_print_for(Options, cbPrintFor, nullptr);
647 
648   isl_printer *P = isl_printer_to_str(S.getIslCtx());
649   P = isl_printer_set_output_format(P, ISL_FORMAT_C);
650   P = isl_printer_print_ast_expr(P, RunCondition);
651   RtCStr = isl_printer_get_str(P);
652   P = isl_printer_flush(P);
653   P = isl_printer_indent(P, 4);
654   P = isl_ast_node_print(RootNode, P, Options);
655   AstStr = isl_printer_get_str(P);
656 
657   auto *Schedule = S.getScheduleTree().release();
658 
659   DEBUG({
660     dbgs() << S.getContextStr() << "\n";
661     dbgs() << stringFromIslObj(Schedule);
662   });
663   OS << "\nif (" << RtCStr << ")\n\n";
664   OS << AstStr << "\n";
665   OS << "else\n";
666   OS << "    {  /* original code */ }\n\n";
667 
668   free(RtCStr);
669   free(AstStr);
670 
671   isl_ast_expr_free(RunCondition);
672   isl_schedule_free(Schedule);
673   isl_ast_node_free(RootNode);
674   isl_printer_free(P);
675 }
676 
677 AnalysisKey IslAstAnalysis::Key;
678 PreservedAnalyses IslAstPrinterPass::run(Scop &S, ScopAnalysisManager &SAM,
679                                          ScopStandardAnalysisResults &SAR,
680                                          SPMUpdater &U) {
681 
682   auto &Ast = SAM.getResult<IslAstAnalysis>(S, SAR);
683   Ast.print(Stream);
684   return PreservedAnalyses::all();
685 }
686 
687 void IslAstInfoWrapperPass::releaseMemory() { Ast.reset(); }
688 
689 bool IslAstInfoWrapperPass::runOnScop(Scop &Scop) {
690 
691   // Skip SCoPs in case they're already handled by PPCGCodeGeneration.
692   if (Scop.isToBeSkipped())
693     return false;
694 
695   const Dependences &D =
696       getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
697 
698   Ast.reset(new IslAstInfo(Scop, D));
699 
700   DEBUG(printScop(dbgs(), Scop));
701   return false;
702 }
703 void IslAstInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
704   // Get the Common analysis usage of ScopPasses.
705   ScopPass::getAnalysisUsage(AU);
706   AU.addRequired<ScopInfoRegionPass>();
707   AU.addRequired<DependenceInfo>();
708 }
709 
710 void IslAstInfoWrapperPass::printScop(raw_ostream &OS, Scop &S) const {
711   if (Ast)
712     Ast->print(OS);
713 }
714 
715 char IslAstInfoWrapperPass::ID = 0;
716 
717 Pass *polly::createIslAstInfoWrapperPassPass() {
718   return new IslAstInfoWrapperPass();
719 }
720 
721 INITIALIZE_PASS_BEGIN(IslAstInfoWrapperPass, "polly-ast",
722                       "Polly - Generate an AST of the SCoP (isl)", false,
723                       false);
724 INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass);
725 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
726 INITIALIZE_PASS_END(IslAstInfoWrapperPass, "polly-ast",
727                     "Polly - Generate an AST from the SCoP (isl)", false, false)
728