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 Transations 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 #define DEBUG_TYPE "polly-ast"
47 
48 using namespace llvm;
49 using namespace polly;
50 
51 using IslAstUserPayload = IslAstInfo::IslAstUserPayload;
52 
53 static cl::opt<bool>
54     PollyParallel("polly-parallel",
55                   cl::desc("Generate thread parallel code (isl codegen only)"),
56                   cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
57 
58 static cl::opt<bool> PollyParallelForce(
59     "polly-parallel-force",
60     cl::desc(
61         "Force generation of thread parallel code ignoring any cost model"),
62     cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
63 
64 static cl::opt<bool> UseContext("polly-ast-use-context",
65                                 cl::desc("Use context"), cl::Hidden,
66                                 cl::init(false), cl::ZeroOrMore,
67                                 cl::cat(PollyCategory));
68 
69 static cl::opt<bool> DetectParallel("polly-ast-detect-parallel",
70                                     cl::desc("Detect parallelism"), cl::Hidden,
71                                     cl::init(false), cl::ZeroOrMore,
72                                     cl::cat(PollyCategory));
73 
74 /// @brief Free an IslAstUserPayload object pointed to by @p Ptr
75 static void freeIslAstUserPayload(void *Ptr) {
76   delete ((IslAstInfo::IslAstUserPayload *)Ptr);
77 }
78 
79 IslAstInfo::IslAstUserPayload::~IslAstUserPayload() {
80   isl_ast_build_free(Build);
81   isl_pw_aff_free(MinimalDependenceDistance);
82 }
83 
84 /// @brief Temporary information used when building the ast.
85 struct AstBuildUserInfo {
86   /// @brief Construct and initialize the helper struct for AST creation.
87   AstBuildUserInfo()
88       : Deps(nullptr), InParallelFor(false), LastForNodeId(nullptr) {}
89 
90   /// @brief The dependence information used for the parallelism check.
91   const Dependences *Deps;
92 
93   /// @brief Flag to indicate that we are inside a parallel for node.
94   bool InParallelFor;
95 
96   /// @brief The last iterator id created for the current SCoP.
97   isl_id *LastForNodeId;
98 };
99 
100 /// @brief Print a string @p str in a single line using @p Printer.
101 static isl_printer *printLine(__isl_take isl_printer *Printer,
102                               const std::string &str,
103                               __isl_keep isl_pw_aff *PWA = nullptr) {
104   Printer = isl_printer_start_line(Printer);
105   Printer = isl_printer_print_str(Printer, str.c_str());
106   if (PWA)
107     Printer = isl_printer_print_pw_aff(Printer, PWA);
108   return isl_printer_end_line(Printer);
109 }
110 
111 /// @brief Return all broken reductions as a string of clauses (OpenMP style).
112 static const std::string getBrokenReductionsStr(__isl_keep isl_ast_node *Node) {
113   IslAstInfo::MemoryAccessSet *BrokenReductions;
114   std::string str;
115 
116   BrokenReductions = IslAstInfo::getBrokenReductions(Node);
117   if (!BrokenReductions || BrokenReductions->empty())
118     return "";
119 
120   // Map each type of reduction to a comma separated list of the base addresses.
121   std::map<MemoryAccess::ReductionType, std::string> Clauses;
122   for (MemoryAccess *MA : *BrokenReductions)
123     if (MA->isWrite())
124       Clauses[MA->getReductionType()] +=
125           ", " + MA->getBaseAddr()->getName().str();
126 
127   // Now print the reductions sorted by type. Each type will cause a clause
128   // like:  reduction (+ : sum0, sum1, sum2)
129   for (const auto &ReductionClause : Clauses) {
130     str += " reduction (";
131     str += MemoryAccess::getReductionOperatorStr(ReductionClause.first);
132     // Remove the first two symbols (", ") to make the output look pretty.
133     str += " : " + ReductionClause.second.substr(2) + ")";
134   }
135 
136   return str;
137 }
138 
139 /// @brief Callback executed for each for node in the ast in order to print it.
140 static isl_printer *cbPrintFor(__isl_take isl_printer *Printer,
141                                __isl_take isl_ast_print_options *Options,
142                                __isl_keep isl_ast_node *Node, void *) {
143 
144   isl_pw_aff *DD = IslAstInfo::getMinimalDependenceDistance(Node);
145   const std::string BrokenReductionsStr = getBrokenReductionsStr(Node);
146   const std::string KnownParallelStr = "#pragma known-parallel";
147   const std::string DepDisPragmaStr = "#pragma minimal dependence distance: ";
148   const std::string SimdPragmaStr = "#pragma simd";
149   const std::string OmpPragmaStr = "#pragma omp parallel for";
150 
151   if (DD)
152     Printer = printLine(Printer, DepDisPragmaStr, DD);
153 
154   if (IslAstInfo::isInnermostParallel(Node))
155     Printer = printLine(Printer, SimdPragmaStr + BrokenReductionsStr);
156 
157   if (IslAstInfo::isExecutedInParallel(Node))
158     Printer = printLine(Printer, OmpPragmaStr);
159   else if (IslAstInfo::isOutermostParallel(Node))
160     Printer = printLine(Printer, KnownParallelStr + BrokenReductionsStr);
161 
162   isl_pw_aff_free(DD);
163   return isl_ast_node_for_print(Node, Printer, Options);
164 }
165 
166 /// @brief Check if the current scheduling dimension is parallel
167 ///
168 /// In case the dimension is parallel we also check if any reduction
169 /// dependences is broken when we exploit this parallelism. If so,
170 /// @p IsReductionParallel will be set to true. The reduction dependences we use
171 /// to check are actually the union of the transitive closure of the initial
172 /// reduction dependences together with their reveresal. Even though these
173 /// dependences connect all iterations with each other (thus they are cyclic)
174 /// we can perform the parallelism check as we are only interested in a zero
175 /// (or non-zero) dependence distance on the dimension in question.
176 static bool astScheduleDimIsParallel(__isl_keep isl_ast_build *Build,
177                                      const Dependences *D,
178                                      IslAstUserPayload *NodeInfo) {
179   if (!D->hasValidDependences())
180     return false;
181 
182   isl_union_map *Schedule = isl_ast_build_get_schedule(Build);
183   isl_union_map *Deps = D->getDependences(
184       Dependences::TYPE_RAW | Dependences::TYPE_WAW | Dependences::TYPE_WAR);
185 
186   if (!D->isParallel(Schedule, Deps, &NodeInfo->MinimalDependenceDistance) &&
187       !isl_union_map_free(Schedule))
188     return false;
189 
190   isl_union_map *RedDeps = D->getDependences(Dependences::TYPE_TC_RED);
191   if (!D->isParallel(Schedule, RedDeps))
192     NodeInfo->IsReductionParallel = true;
193 
194   if (!NodeInfo->IsReductionParallel && !isl_union_map_free(Schedule))
195     return true;
196 
197   // Annotate reduction parallel nodes with the memory accesses which caused the
198   // reduction dependences parallel execution of the node conflicts with.
199   for (const auto &MaRedPair : D->getReductionDependences()) {
200     if (!MaRedPair.second)
201       continue;
202     RedDeps = isl_union_map_from_map(isl_map_copy(MaRedPair.second));
203     if (!D->isParallel(Schedule, RedDeps))
204       NodeInfo->BrokenReductions.insert(MaRedPair.first);
205   }
206 
207   isl_union_map_free(Schedule);
208   return true;
209 }
210 
211 // This method is executed before the construction of a for node. It creates
212 // an isl_id that is used to annotate the subsequently generated ast for nodes.
213 //
214 // In this function we also run the following analyses:
215 //
216 // - Detection of openmp parallel loops
217 //
218 static __isl_give isl_id *astBuildBeforeFor(__isl_keep isl_ast_build *Build,
219                                             void *User) {
220   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
221   IslAstUserPayload *Payload = new IslAstUserPayload();
222   isl_id *Id = isl_id_alloc(isl_ast_build_get_ctx(Build), "", Payload);
223   Id = isl_id_set_free_user(Id, freeIslAstUserPayload);
224   BuildInfo->LastForNodeId = Id;
225 
226   // Test for parallelism only if we are not already inside a parallel loop
227   if (!BuildInfo->InParallelFor)
228     BuildInfo->InParallelFor = Payload->IsOutermostParallel =
229         astScheduleDimIsParallel(Build, BuildInfo->Deps, Payload);
230 
231   return Id;
232 }
233 
234 // This method is executed after the construction of a for node.
235 //
236 // It performs the following actions:
237 //
238 // - Reset the 'InParallelFor' flag, as soon as we leave a for node,
239 //   that is marked as openmp parallel.
240 //
241 static __isl_give isl_ast_node *
242 astBuildAfterFor(__isl_take isl_ast_node *Node, __isl_keep isl_ast_build *Build,
243                  void *User) {
244   isl_id *Id = isl_ast_node_get_annotation(Node);
245   assert(Id && "Post order visit assumes annotated for nodes");
246   IslAstUserPayload *Payload = (IslAstUserPayload *)isl_id_get_user(Id);
247   assert(Payload && "Post order visit assumes annotated for nodes");
248 
249   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
250   assert(!Payload->Build && "Build environment already set");
251   Payload->Build = isl_ast_build_copy(Build);
252   Payload->IsInnermost = (Id == BuildInfo->LastForNodeId);
253 
254   // Innermost loops that are surrounded by parallel loops have not yet been
255   // tested for parallelism. Test them here to ensure we check all innermost
256   // loops for parallelism.
257   if (Payload->IsInnermost && BuildInfo->InParallelFor) {
258     if (Payload->IsOutermostParallel) {
259       Payload->IsInnermostParallel = true;
260     } else {
261       if (PollyVectorizerChoice == VECTORIZER_NONE)
262         Payload->IsInnermostParallel =
263             astScheduleDimIsParallel(Build, BuildInfo->Deps, Payload);
264     }
265   }
266   if (Payload->IsOutermostParallel)
267     BuildInfo->InParallelFor = false;
268 
269   isl_id_free(Id);
270   return Node;
271 }
272 
273 static isl_stat astBuildBeforeMark(__isl_keep isl_id *MarkId,
274                                    __isl_keep isl_ast_build *Build,
275                                    void *User) {
276   if (!MarkId)
277     return isl_stat_error;
278 
279   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
280   if (!strcmp(isl_id_get_name(MarkId), "SIMD"))
281     BuildInfo->InParallelFor = true;
282 
283   return isl_stat_ok;
284 }
285 
286 static __isl_give isl_ast_node *
287 astBuildAfterMark(__isl_take isl_ast_node *Node,
288                   __isl_keep isl_ast_build *Build, void *User) {
289   assert(isl_ast_node_get_type(Node) == isl_ast_node_mark);
290   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
291   auto *Id = isl_ast_node_mark_get_id(Node);
292   if (!strcmp(isl_id_get_name(Id), "SIMD"))
293     BuildInfo->InParallelFor = false;
294   isl_id_free(Id);
295   return Node;
296 }
297 
298 static __isl_give isl_ast_node *AtEachDomain(__isl_take isl_ast_node *Node,
299                                              __isl_keep isl_ast_build *Build,
300                                              void *User) {
301   assert(!isl_ast_node_get_annotation(Node) && "Node already annotated");
302 
303   IslAstUserPayload *Payload = new IslAstUserPayload();
304   isl_id *Id = isl_id_alloc(isl_ast_build_get_ctx(Build), "", Payload);
305   Id = isl_id_set_free_user(Id, freeIslAstUserPayload);
306 
307   Payload->Build = isl_ast_build_copy(Build);
308 
309   return isl_ast_node_set_annotation(Node, Id);
310 }
311 
312 // Build alias check condition given a pair of minimal/maximal access.
313 static __isl_give isl_ast_expr *
314 buildCondition(__isl_keep isl_ast_build *Build, const Scop::MinMaxAccessTy *It0,
315                const Scop::MinMaxAccessTy *It1) {
316   isl_ast_expr *NonAliasGroup, *MinExpr, *MaxExpr;
317   MinExpr = isl_ast_expr_address_of(isl_ast_build_access_from_pw_multi_aff(
318       Build, isl_pw_multi_aff_copy(It0->first)));
319   MaxExpr = isl_ast_expr_address_of(isl_ast_build_access_from_pw_multi_aff(
320       Build, isl_pw_multi_aff_copy(It1->second)));
321   NonAliasGroup = isl_ast_expr_le(MaxExpr, MinExpr);
322   MinExpr = isl_ast_expr_address_of(isl_ast_build_access_from_pw_multi_aff(
323       Build, isl_pw_multi_aff_copy(It1->first)));
324   MaxExpr = isl_ast_expr_address_of(isl_ast_build_access_from_pw_multi_aff(
325       Build, isl_pw_multi_aff_copy(It0->second)));
326   NonAliasGroup =
327       isl_ast_expr_or(NonAliasGroup, isl_ast_expr_le(MaxExpr, MinExpr));
328 
329   return NonAliasGroup;
330 }
331 
332 __isl_give isl_ast_expr *
333 IslAst::buildRunCondition(Scop *S, __isl_keep isl_ast_build *Build) {
334   isl_ast_expr *RunCondition;
335 
336   // The conditions that need to be checked at run-time for this scop are
337   // available as an isl_set in the runtime check context from which we can
338   // directly derive a run-time condition.
339   RunCondition =
340       isl_ast_build_expr_from_set(Build, S->getRuntimeCheckContext());
341 
342   // Create the alias checks from the minimal/maximal accesses in each alias
343   // group which consists of read only and non read only (read write) accesses.
344   // This operation is by construction quadratic in the read-write pointers and
345   // linear int the read only pointers in each alias group.
346   for (const Scop::MinMaxVectorPairTy &MinMaxAccessPair : S->getAliasGroups()) {
347     auto &MinMaxReadWrite = MinMaxAccessPair.first;
348     auto &MinMaxReadOnly = MinMaxAccessPair.second;
349     auto RWAccEnd = MinMaxReadWrite.end();
350 
351     for (auto RWAccIt0 = MinMaxReadWrite.begin(); RWAccIt0 != RWAccEnd;
352          ++RWAccIt0) {
353       for (auto RWAccIt1 = RWAccIt0 + 1; RWAccIt1 != RWAccEnd; ++RWAccIt1)
354         RunCondition = isl_ast_expr_and(
355             RunCondition, buildCondition(Build, RWAccIt0, RWAccIt1));
356       for (const Scop::MinMaxAccessTy &ROAccIt : MinMaxReadOnly)
357         RunCondition = isl_ast_expr_and(
358             RunCondition, buildCondition(Build, RWAccIt0, &ROAccIt));
359     }
360   }
361 
362   return RunCondition;
363 }
364 
365 /// @brief Simple cost analysis for a given SCoP
366 ///
367 /// TODO: Improve this analysis and extract it to make it usable in other
368 ///       places too.
369 ///       In order to improve the cost model we could either keep track of
370 ///       performed optimizations (e.g., tiling) or compute properties on the
371 ///       original as well as optimized SCoP (e.g., #stride-one-accesses).
372 static bool benefitsFromPolly(Scop *Scop, bool PerformParallelTest) {
373 
374   if (PollyProcessUnprofitable)
375     return true;
376 
377   // Check if nothing interesting happened.
378   if (!PerformParallelTest && !Scop->isOptimized() &&
379       Scop->getAliasGroups().empty())
380     return false;
381 
382   // The default assumption is that Polly improves the code.
383   return true;
384 }
385 
386 IslAst::IslAst(Scop *Scop)
387     : S(Scop), Root(nullptr), RunCondition(nullptr),
388       Ctx(Scop->getSharedIslCtx()) {}
389 
390 void IslAst::init(const Dependences &D) {
391   bool PerformParallelTest = PollyParallel || DetectParallel ||
392                              PollyVectorizerChoice != VECTORIZER_NONE;
393 
394   // Skip AST and code generation if there was no benefit achieved.
395   if (!benefitsFromPolly(S, PerformParallelTest))
396     return;
397 
398   isl_ctx *Ctx = S->getIslCtx();
399   isl_options_set_ast_build_atomic_upper_bound(Ctx, true);
400   isl_ast_build *Build;
401   AstBuildUserInfo BuildInfo;
402 
403   if (UseContext)
404     Build = isl_ast_build_from_context(S->getContext());
405   else
406     Build = isl_ast_build_from_context(isl_set_universe(S->getParamSpace()));
407 
408   Build = isl_ast_build_set_at_each_domain(Build, AtEachDomain, nullptr);
409 
410   if (PerformParallelTest) {
411     BuildInfo.Deps = &D;
412     BuildInfo.InParallelFor = 0;
413 
414     Build = isl_ast_build_set_before_each_for(Build, &astBuildBeforeFor,
415                                               &BuildInfo);
416     Build =
417         isl_ast_build_set_after_each_for(Build, &astBuildAfterFor, &BuildInfo);
418 
419     Build = isl_ast_build_set_before_each_mark(Build, &astBuildBeforeMark,
420                                                &BuildInfo);
421 
422     Build = isl_ast_build_set_after_each_mark(Build, &astBuildAfterMark,
423                                               &BuildInfo);
424   }
425 
426   RunCondition = buildRunCondition(S, Build);
427 
428   Root = isl_ast_build_node_from_schedule(Build, S->getScheduleTree());
429 
430   isl_ast_build_free(Build);
431 }
432 
433 IslAst *IslAst::create(Scop *Scop, const Dependences &D) {
434   auto Ast = new IslAst(Scop);
435   Ast->init(D);
436   return Ast;
437 }
438 
439 IslAst::~IslAst() {
440   isl_ast_node_free(Root);
441   isl_ast_expr_free(RunCondition);
442 }
443 
444 __isl_give isl_ast_node *IslAst::getAst() { return isl_ast_node_copy(Root); }
445 __isl_give isl_ast_expr *IslAst::getRunCondition() {
446   return isl_ast_expr_copy(RunCondition);
447 }
448 
449 void IslAstInfo::releaseMemory() {
450   if (Ast) {
451     delete Ast;
452     Ast = nullptr;
453   }
454 }
455 
456 bool IslAstInfo::runOnScop(Scop &Scop) {
457   if (Ast)
458     delete Ast;
459 
460   S = &Scop;
461 
462   const Dependences &D = getAnalysis<DependenceInfo>().getDependences();
463 
464   Ast = IslAst::create(&Scop, D);
465 
466   DEBUG(printScop(dbgs(), Scop));
467   return false;
468 }
469 
470 __isl_give isl_ast_node *IslAstInfo::getAst() const { return Ast->getAst(); }
471 __isl_give isl_ast_expr *IslAstInfo::getRunCondition() const {
472   return Ast->getRunCondition();
473 }
474 
475 IslAstUserPayload *IslAstInfo::getNodePayload(__isl_keep isl_ast_node *Node) {
476   isl_id *Id = isl_ast_node_get_annotation(Node);
477   if (!Id)
478     return nullptr;
479   IslAstUserPayload *Payload = (IslAstUserPayload *)isl_id_get_user(Id);
480   isl_id_free(Id);
481   return Payload;
482 }
483 
484 bool IslAstInfo::isInnermost(__isl_keep isl_ast_node *Node) {
485   IslAstUserPayload *Payload = getNodePayload(Node);
486   return Payload && Payload->IsInnermost;
487 }
488 
489 bool IslAstInfo::isParallel(__isl_keep isl_ast_node *Node) {
490   return IslAstInfo::isInnermostParallel(Node) ||
491          IslAstInfo::isOutermostParallel(Node);
492 }
493 
494 bool IslAstInfo::isInnermostParallel(__isl_keep isl_ast_node *Node) {
495   IslAstUserPayload *Payload = getNodePayload(Node);
496   return Payload && Payload->IsInnermostParallel;
497 }
498 
499 bool IslAstInfo::isOutermostParallel(__isl_keep isl_ast_node *Node) {
500   IslAstUserPayload *Payload = getNodePayload(Node);
501   return Payload && Payload->IsOutermostParallel;
502 }
503 
504 bool IslAstInfo::isReductionParallel(__isl_keep isl_ast_node *Node) {
505   IslAstUserPayload *Payload = getNodePayload(Node);
506   return Payload && Payload->IsReductionParallel;
507 }
508 
509 bool IslAstInfo::isExecutedInParallel(__isl_keep isl_ast_node *Node) {
510 
511   if (!PollyParallel)
512     return false;
513 
514   // Do not parallelize innermost loops.
515   //
516   // Parallelizing innermost loops is often not profitable, especially if
517   // they have a low number of iterations.
518   //
519   // TODO: Decide this based on the number of loop iterations that will be
520   //       executed. This can possibly require run-time checks, which again
521   //       raises the question of both run-time check overhead and code size
522   //       costs.
523   if (!PollyParallelForce && isInnermost(Node))
524     return false;
525 
526   return isOutermostParallel(Node) && !isReductionParallel(Node);
527 }
528 
529 isl_union_map *IslAstInfo::getSchedule(__isl_keep isl_ast_node *Node) {
530   IslAstUserPayload *Payload = getNodePayload(Node);
531   return Payload ? isl_ast_build_get_schedule(Payload->Build) : nullptr;
532 }
533 
534 isl_pw_aff *
535 IslAstInfo::getMinimalDependenceDistance(__isl_keep isl_ast_node *Node) {
536   IslAstUserPayload *Payload = getNodePayload(Node);
537   return Payload ? isl_pw_aff_copy(Payload->MinimalDependenceDistance)
538                  : nullptr;
539 }
540 
541 IslAstInfo::MemoryAccessSet *
542 IslAstInfo::getBrokenReductions(__isl_keep isl_ast_node *Node) {
543   IslAstUserPayload *Payload = getNodePayload(Node);
544   return Payload ? &Payload->BrokenReductions : nullptr;
545 }
546 
547 isl_ast_build *IslAstInfo::getBuild(__isl_keep isl_ast_node *Node) {
548   IslAstUserPayload *Payload = getNodePayload(Node);
549   return Payload ? Payload->Build : nullptr;
550 }
551 
552 void IslAstInfo::printScop(raw_ostream &OS, Scop &S) const {
553   isl_ast_print_options *Options;
554   isl_ast_node *RootNode = getAst();
555   Function *F = S.getRegion().getEntry()->getParent();
556 
557   OS << ":: isl ast :: " << F->getName() << " :: " << S.getRegion().getNameStr()
558      << "\n";
559 
560   if (!RootNode) {
561     OS << ":: isl ast generation and code generation was skipped!\n\n";
562     OS << ":: This is either because no useful optimizations could be applied "
563           "(use -polly-process-unprofitable to enforce code generation) or "
564           "because earlier passes such as dependence analysis timed out (use "
565           "-polly-dependences-computeout=0 to set dependence analysis timeout "
566           "to infinity)\n\n";
567     return;
568   }
569 
570   isl_ast_expr *RunCondition = getRunCondition();
571   char *RtCStr, *AstStr;
572 
573   Options = isl_ast_print_options_alloc(S.getIslCtx());
574   Options = isl_ast_print_options_set_print_for(Options, cbPrintFor, nullptr);
575 
576   isl_printer *P = isl_printer_to_str(S.getIslCtx());
577   P = isl_printer_print_ast_expr(P, RunCondition);
578   RtCStr = isl_printer_get_str(P);
579   P = isl_printer_flush(P);
580   P = isl_printer_indent(P, 4);
581   P = isl_printer_set_output_format(P, ISL_FORMAT_C);
582   P = isl_ast_node_print(RootNode, P, Options);
583   AstStr = isl_printer_get_str(P);
584 
585   isl_union_map *Schedule =
586       isl_union_map_intersect_domain(S.getSchedule(), S.getDomains());
587 
588   DEBUG({
589     dbgs() << S.getContextStr() << "\n";
590     dbgs() << stringFromIslObj(Schedule);
591   });
592   OS << "\nif (" << RtCStr << ")\n\n";
593   OS << AstStr << "\n";
594   OS << "else\n";
595   OS << "    {  /* original code */ }\n\n";
596 
597   free(RtCStr);
598   free(AstStr);
599 
600   isl_ast_expr_free(RunCondition);
601   isl_union_map_free(Schedule);
602   isl_ast_node_free(RootNode);
603   isl_printer_free(P);
604 }
605 
606 void IslAstInfo::getAnalysisUsage(AnalysisUsage &AU) const {
607   // Get the Common analysis usage of ScopPasses.
608   ScopPass::getAnalysisUsage(AU);
609   AU.addRequired<ScopInfo>();
610   AU.addRequired<DependenceInfo>();
611 }
612 
613 char IslAstInfo::ID = 0;
614 
615 Pass *polly::createIslAstInfoPass() { return new IslAstInfo(); }
616 
617 INITIALIZE_PASS_BEGIN(IslAstInfo, "polly-ast",
618                       "Polly - Generate an AST of the SCoP (isl)", false,
619                       false);
620 INITIALIZE_PASS_DEPENDENCY(ScopInfo);
621 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
622 INITIALIZE_PASS_END(IslAstInfo, "polly-ast",
623                     "Polly - Generate an AST from the SCoP (isl)", false, false)
624