1 //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
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 // Take a scop created by ScopInfo and map it to GPU code using the ppcg
11 // GPU mapping strategy.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "polly/CodeGen/IslNodeBuilder.h"
16 #include "polly/CodeGen/Utils.h"
17 #include "polly/DependenceInfo.h"
18 #include "polly/LinkAllPasses.h"
19 #include "polly/Options.h"
20 #include "polly/ScopInfo.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/BasicAliasAnalysis.h"
23 #include "llvm/Analysis/GlobalsModRef.h"
24 #include "llvm/Analysis/PostDominators.h"
25 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
26 
27 #include "isl/union_map.h"
28 
29 extern "C" {
30 #include "ppcg/cuda.h"
31 #include "ppcg/gpu.h"
32 #include "ppcg/gpu_print.h"
33 #include "ppcg/ppcg.h"
34 #include "ppcg/schedule.h"
35 }
36 
37 #include "llvm/Support/Debug.h"
38 
39 using namespace polly;
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "polly-codegen-ppcg"
43 
44 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
45                                   cl::desc("Dump the computed GPU Schedule"),
46                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
47                                   cl::cat(PollyCategory));
48 
49 static cl::opt<bool>
50     DumpCode("polly-acc-dump-code",
51              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
52              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
53 
54 /// Create the ast expressions for a ScopStmt.
55 ///
56 /// This function is a callback for to generate the ast expressions for each
57 /// of the scheduled ScopStmts.
58 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
59     void *Stmt, isl_ast_build *Build,
60     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
61                                        isl_id *Id, void *User),
62     void *UserIndex,
63     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
64     void *User_expr) {
65 
66   // TODO: Implement the AST expression generation. For now we just return a
67   // nullptr to ensure that we do not free uninitialized pointers.
68 
69   return nullptr;
70 }
71 
72 /// Generate code for a GPU specific isl AST.
73 ///
74 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
75 /// generates code for general-prupose AST nodes, with special functionality
76 /// for generating GPU specific user nodes.
77 ///
78 /// @see GPUNodeBuilder::createUser
79 class GPUNodeBuilder : public IslNodeBuilder {
80 public:
81   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
82                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
83                  DominatorTree &DT, Scop &S)
84       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S) {}
85 
86 private:
87   /// Create code for user-defined AST nodes.
88   ///
89   /// These AST nodes can be of type:
90   ///
91   ///   - ScopStmt:      A computational statement (TODO)
92   ///   - Kernel:        A GPU kernel call (TODO)
93   ///   - Data-Transfer: A GPU <-> CPU data-transfer (TODO)
94   ///
95   virtual void createUser(__isl_take isl_ast_node *User) {
96     isl_ast_node_free(User);
97     return;
98   }
99 };
100 
101 namespace {
102 class PPCGCodeGeneration : public ScopPass {
103 public:
104   static char ID;
105 
106   /// The scop that is currently processed.
107   Scop *S;
108 
109   LoopInfo *LI;
110   DominatorTree *DT;
111   ScalarEvolution *SE;
112   const DataLayout *DL;
113   RegionInfo *RI;
114 
115   PPCGCodeGeneration() : ScopPass(ID) {}
116 
117   /// Construct compilation options for PPCG.
118   ///
119   /// @returns The compilation options.
120   ppcg_options *createPPCGOptions() {
121     auto DebugOptions =
122         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
123     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
124 
125     DebugOptions->dump_schedule_constraints = false;
126     DebugOptions->dump_schedule = false;
127     DebugOptions->dump_final_schedule = false;
128     DebugOptions->dump_sizes = false;
129 
130     Options->debug = DebugOptions;
131 
132     Options->reschedule = true;
133     Options->scale_tile_loops = false;
134     Options->wrap = false;
135 
136     Options->non_negative_parameters = false;
137     Options->ctx = nullptr;
138     Options->sizes = nullptr;
139 
140     Options->tile_size = 32;
141 
142     Options->use_private_memory = false;
143     Options->use_shared_memory = false;
144     Options->max_shared_memory = 0;
145 
146     Options->target = PPCG_TARGET_CUDA;
147     Options->openmp = false;
148     Options->linearize_device_arrays = true;
149     Options->live_range_reordering = false;
150 
151     Options->opencl_compiler_options = nullptr;
152     Options->opencl_use_gpu = false;
153     Options->opencl_n_include_file = 0;
154     Options->opencl_include_files = nullptr;
155     Options->opencl_print_kernel_types = false;
156     Options->opencl_embed_kernel_code = false;
157 
158     Options->save_schedule_file = nullptr;
159     Options->load_schedule_file = nullptr;
160 
161     return Options;
162   }
163 
164   /// Get a tagged access relation containing all accesses of type @p AccessTy.
165   ///
166   /// Instead of a normal access of the form:
167   ///
168   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
169   ///
170   /// a tagged access has the form
171   ///
172   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
173   ///
174   /// where 'id' is an additional space that references the memory access that
175   /// triggered the access.
176   ///
177   /// @param AccessTy The type of the memory accesses to collect.
178   ///
179   /// @return The relation describing all tagged memory accesses.
180   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
181     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
182 
183     for (auto &Stmt : *S)
184       for (auto &Acc : Stmt)
185         if (Acc->getType() == AccessTy) {
186           isl_map *Relation = Acc->getAccessRelation();
187           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
188 
189           isl_space *Space = isl_map_get_space(Relation);
190           Space = isl_space_range(Space);
191           Space = isl_space_from_range(Space);
192           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
193           isl_map *Universe = isl_map_universe(Space);
194           Relation = isl_map_domain_product(Relation, Universe);
195           Accesses = isl_union_map_add_map(Accesses, Relation);
196         }
197 
198     return Accesses;
199   }
200 
201   /// Get the set of all read accesses, tagged with the access id.
202   ///
203   /// @see getTaggedAccesses
204   isl_union_map *getTaggedReads() {
205     return getTaggedAccesses(MemoryAccess::READ);
206   }
207 
208   /// Get the set of all may (and must) accesses, tagged with the access id.
209   ///
210   /// @see getTaggedAccesses
211   isl_union_map *getTaggedMayWrites() {
212     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
213                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
214   }
215 
216   /// Get the set of all must accesses, tagged with the access id.
217   ///
218   /// @see getTaggedAccesses
219   isl_union_map *getTaggedMustWrites() {
220     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
221   }
222 
223   /// Collect parameter and array names as isl_ids.
224   ///
225   /// To reason about the different parameters and arrays used, ppcg requires
226   /// a list of all isl_ids in use. As PPCG traditionally performs
227   /// source-to-source compilation each of these isl_ids is mapped to the
228   /// expression that represents it. As we do not have a corresponding
229   /// expression in Polly, we just map each id to a 'zero' expression to match
230   /// the data format that ppcg expects.
231   ///
232   /// @returns Retun a map from collected ids to 'zero' ast expressions.
233   __isl_give isl_id_to_ast_expr *getNames() {
234     auto *Names = isl_id_to_ast_expr_alloc(
235         S->getIslCtx(),
236         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
237     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
238     auto *Space = S->getParamSpace();
239 
240     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
241       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
242       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
243     }
244 
245     for (auto &Array : S->arrays()) {
246       auto Id = Array.second->getBasePtrId();
247       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
248     }
249 
250     isl_space_free(Space);
251     isl_ast_expr_free(Zero);
252 
253     return Names;
254   }
255 
256   /// Create a new PPCG scop from the current scop.
257   ///
258   /// The PPCG scop is initialized with data from the current polly::Scop. From
259   /// this initial data, the data-dependences in the PPCG scop are initialized.
260   /// We do not use Polly's dependence analysis for now, to ensure we match
261   /// the PPCG default behaviour more closely.
262   ///
263   /// @returns A new ppcg scop.
264   ppcg_scop *createPPCGScop() {
265     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
266 
267     PPCGScop->options = createPPCGOptions();
268 
269     PPCGScop->start = 0;
270     PPCGScop->end = 0;
271 
272     PPCGScop->context = S->getContext();
273     PPCGScop->domain = S->getDomains();
274     PPCGScop->call = nullptr;
275     PPCGScop->tagged_reads = getTaggedReads();
276     PPCGScop->reads = S->getReads();
277     PPCGScop->live_in = nullptr;
278     PPCGScop->tagged_may_writes = getTaggedMayWrites();
279     PPCGScop->may_writes = S->getWrites();
280     PPCGScop->tagged_must_writes = getTaggedMustWrites();
281     PPCGScop->must_writes = S->getMustWrites();
282     PPCGScop->live_out = nullptr;
283     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
284     PPCGScop->tagger = nullptr;
285 
286     PPCGScop->independence = nullptr;
287     PPCGScop->dep_flow = nullptr;
288     PPCGScop->tagged_dep_flow = nullptr;
289     PPCGScop->dep_false = nullptr;
290     PPCGScop->dep_forced = nullptr;
291     PPCGScop->dep_order = nullptr;
292     PPCGScop->tagged_dep_order = nullptr;
293 
294     PPCGScop->schedule = S->getScheduleTree();
295     PPCGScop->names = getNames();
296 
297     PPCGScop->pet = nullptr;
298 
299     compute_tagger(PPCGScop);
300     compute_dependences(PPCGScop);
301 
302     return PPCGScop;
303   }
304 
305   /// Collect the array acesses in a statement.
306   ///
307   /// @param Stmt The statement for which to collect the accesses.
308   ///
309   /// @returns A list of array accesses.
310   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
311     gpu_stmt_access *Accesses = nullptr;
312 
313     for (MemoryAccess *Acc : Stmt) {
314       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
315       Access->read = Acc->isRead();
316       Access->write = Acc->isWrite();
317       Access->access = Acc->getAccessRelation();
318       isl_space *Space = isl_map_get_space(Access->access);
319       Space = isl_space_range(Space);
320       Space = isl_space_from_range(Space);
321       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
322       isl_map *Universe = isl_map_universe(Space);
323       Access->tagged_access =
324           isl_map_domain_product(Acc->getAccessRelation(), Universe);
325       Access->exact_write = Acc->isWrite();
326       Access->ref_id = Acc->getId();
327       Access->next = Accesses;
328       Accesses = Access;
329     }
330 
331     return Accesses;
332   }
333 
334   /// Collect the list of GPU statements.
335   ///
336   /// Each statement has an id, a pointer to the underlying data structure,
337   /// as well as a list with all memory accesses.
338   ///
339   /// TODO: Initialize the list of memory accesses.
340   ///
341   /// @returns A linked-list of statements.
342   gpu_stmt *getStatements() {
343     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
344                                        std::distance(S->begin(), S->end()));
345 
346     int i = 0;
347     for (auto &Stmt : *S) {
348       gpu_stmt *GPUStmt = &Stmts[i];
349 
350       GPUStmt->id = Stmt.getDomainId();
351 
352       // We use the pet stmt pointer to keep track of the Polly statements.
353       GPUStmt->stmt = (pet_stmt *)&Stmt;
354       GPUStmt->accesses = getStmtAccesses(Stmt);
355       i++;
356     }
357 
358     return Stmts;
359   }
360 
361   /// Derive the extent of an array.
362   ///
363   /// The extent of an array is defined by the set of memory locations for
364   /// which a memory access in the iteration domain exists.
365   ///
366   /// @param Array The array to derive the extent for.
367   ///
368   /// @returns An isl_set describing the extent of the array.
369   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
370     isl_union_map *Accesses = S->getAccesses();
371     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
372     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
373     isl_set *AccessSet =
374         isl_union_set_extract_set(AccessUSet, Array->getSpace());
375     isl_union_set_free(AccessUSet);
376 
377     return AccessSet;
378   }
379 
380   /// Derive the bounds of an array.
381   ///
382   /// For the first dimension we derive the bound of the array from the extent
383   /// of this dimension. For inner dimensions we obtain their size directly from
384   /// ScopArrayInfo.
385   ///
386   /// @param PPCGArray The array to compute bounds for.
387   /// @param Array The polly array from which to take the information.
388   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
389     if (PPCGArray.n_index > 0) {
390       isl_set *Dom = isl_set_copy(PPCGArray.extent);
391       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
392       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
393       isl_set_free(Dom);
394       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
395       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
396       isl_aff *One = isl_aff_zero_on_domain(LS);
397       One = isl_aff_add_constant_si(One, 1);
398       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
399       Bound = isl_pw_aff_gist(Bound, S->getContext());
400       PPCGArray.bound[0] = Bound;
401     }
402 
403     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
404       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
405       auto LS = isl_pw_aff_get_domain_space(Bound);
406       auto Aff = isl_multi_aff_zero(LS);
407       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
408       PPCGArray.bound[i] = Bound;
409     }
410   }
411 
412   /// Create the arrays for @p PPCGProg.
413   ///
414   /// @param PPCGProg The program to compute the arrays for.
415   void createArrays(gpu_prog *PPCGProg) {
416     int i = 0;
417     for (auto &Element : S->arrays()) {
418       ScopArrayInfo *Array = Element.second.get();
419 
420       std::string TypeName;
421       raw_string_ostream OS(TypeName);
422 
423       OS << *Array->getElementType();
424       TypeName = OS.str();
425 
426       gpu_array_info &PPCGArray = PPCGProg->array[i];
427 
428       PPCGArray.space = Array->getSpace();
429       PPCGArray.type = strdup(TypeName.c_str());
430       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
431       PPCGArray.name = strdup(Array->getName().c_str());
432       PPCGArray.extent = nullptr;
433       PPCGArray.n_index = Array->getNumberOfDimensions();
434       PPCGArray.bound =
435           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
436       PPCGArray.extent = getExtent(Array);
437       PPCGArray.n_ref = 0;
438       PPCGArray.refs = nullptr;
439       PPCGArray.accessed = true;
440       PPCGArray.read_only_scalar = false;
441       PPCGArray.has_compound_element = false;
442       PPCGArray.local = false;
443       PPCGArray.declare_local = false;
444       PPCGArray.global = false;
445       PPCGArray.linearize = false;
446       PPCGArray.dep_order = nullptr;
447 
448       setArrayBounds(PPCGArray, Array);
449       i++;
450     }
451   }
452 
453   /// Create an identity map between the arrays in the scop.
454   ///
455   /// @returns An identity map between the arrays in the scop.
456   isl_union_map *getArrayIdentity() {
457     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
458 
459     for (auto &Item : S->arrays()) {
460       ScopArrayInfo *Array = Item.second.get();
461       isl_space *Space = Array->getSpace();
462       Space = isl_space_map_from_set(Space);
463       isl_map *Identity = isl_map_identity(Space);
464       Maps = isl_union_map_add_map(Maps, Identity);
465     }
466 
467     return Maps;
468   }
469 
470   /// Create a default-initialized PPCG GPU program.
471   ///
472   /// @returns A new gpu grogram description.
473   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
474 
475     if (!PPCGScop)
476       return nullptr;
477 
478     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
479 
480     PPCGProg->ctx = S->getIslCtx();
481     PPCGProg->scop = PPCGScop;
482     PPCGProg->context = isl_set_copy(PPCGScop->context);
483     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
484     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
485     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
486     PPCGProg->tagged_must_kill =
487         isl_union_map_copy(PPCGScop->tagged_must_kills);
488     PPCGProg->to_inner = getArrayIdentity();
489     PPCGProg->to_outer = getArrayIdentity();
490     PPCGProg->may_persist = compute_may_persist(PPCGProg);
491     PPCGProg->any_to_outer = nullptr;
492     PPCGProg->array_order = nullptr;
493     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
494     PPCGProg->stmts = getStatements();
495     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
496     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
497                                        PPCGProg->n_array);
498 
499     createArrays(PPCGProg);
500 
501     return PPCGProg;
502   }
503 
504   struct PrintGPUUserData {
505     struct cuda_info *CudaInfo;
506     struct gpu_prog *PPCGProg;
507     std::vector<ppcg_kernel *> Kernels;
508   };
509 
510   /// Print a user statement node in the host code.
511   ///
512   /// We use ppcg's printing facilities to print the actual statement and
513   /// additionally build up a list of all kernels that are encountered in the
514   /// host ast.
515   ///
516   /// @param P The printer to print to
517   /// @param Options The printing options to use
518   /// @param Node The node to print
519   /// @param User A user pointer to carry additional data. This pointer is
520   ///             expected to be of type PrintGPUUserData.
521   ///
522   /// @returns A printer to which the output has been printed.
523   static __isl_give isl_printer *
524   printHostUser(__isl_take isl_printer *P,
525                 __isl_take isl_ast_print_options *Options,
526                 __isl_take isl_ast_node *Node, void *User) {
527     auto Data = (struct PrintGPUUserData *)User;
528     auto Id = isl_ast_node_get_annotation(Node);
529 
530     if (Id) {
531       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
532 
533       // If this is a user statement, format it ourselves as ppcg would
534       // otherwise try to call pet functionality that is not available in
535       // Polly.
536       if (IsUser) {
537         P = isl_printer_start_line(P);
538         P = isl_printer_print_ast_node(P, Node);
539         P = isl_printer_end_line(P);
540         isl_id_free(Id);
541         isl_ast_print_options_free(Options);
542         return P;
543       }
544 
545       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
546       isl_id_free(Id);
547       Data->Kernels.push_back(Kernel);
548     }
549 
550     return print_host_user(P, Options, Node, User);
551   }
552 
553   /// Print C code corresponding to the control flow in @p Kernel.
554   ///
555   /// @param Kernel The kernel to print
556   void printKernel(ppcg_kernel *Kernel) {
557     auto *P = isl_printer_to_str(S->getIslCtx());
558     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
559     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
560     P = isl_ast_node_print(Kernel->tree, P, Options);
561     char *String = isl_printer_get_str(P);
562     printf("%s\n", String);
563     free(String);
564     isl_printer_free(P);
565   }
566 
567   /// Print C code corresponding to the GPU code described by @p Tree.
568   ///
569   /// @param Tree An AST describing GPU code
570   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
571   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
572     auto *P = isl_printer_to_str(S->getIslCtx());
573     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
574 
575     PrintGPUUserData Data;
576     Data.PPCGProg = PPCGProg;
577 
578     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
579     Options =
580         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
581     P = isl_ast_node_print(Tree, P, Options);
582     char *String = isl_printer_get_str(P);
583     printf("# host\n");
584     printf("%s\n", String);
585     free(String);
586     isl_printer_free(P);
587 
588     for (auto Kernel : Data.Kernels) {
589       printf("# kernel%d\n", Kernel->id);
590       printKernel(Kernel);
591     }
592   }
593 
594   // Generate a GPU program using PPCG.
595   //
596   // GPU mapping consists of multiple steps:
597   //
598   //  1) Compute new schedule for the program.
599   //  2) Map schedule to GPU (TODO)
600   //  3) Generate code for new schedule (TODO)
601   //
602   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
603   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
604   // strategy directly from this pass.
605   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
606 
607     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
608 
609     PPCGGen->ctx = S->getIslCtx();
610     PPCGGen->options = PPCGScop->options;
611     PPCGGen->print = nullptr;
612     PPCGGen->print_user = nullptr;
613     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
614     PPCGGen->prog = PPCGProg;
615     PPCGGen->tree = nullptr;
616     PPCGGen->types.n = 0;
617     PPCGGen->types.name = nullptr;
618     PPCGGen->sizes = nullptr;
619     PPCGGen->used_sizes = nullptr;
620     PPCGGen->kernel_id = 0;
621 
622     // Set scheduling strategy to same strategy PPCG is using.
623     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
624     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
625     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
626 
627     isl_schedule *Schedule = get_schedule(PPCGGen);
628 
629     int has_permutable = has_any_permutable_node(Schedule);
630 
631     if (!has_permutable || has_permutable < 0) {
632       Schedule = isl_schedule_free(Schedule);
633     } else {
634       Schedule = map_to_device(PPCGGen, Schedule);
635       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
636     }
637 
638     if (DumpSchedule) {
639       isl_printer *P = isl_printer_to_str(S->getIslCtx());
640       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
641       P = isl_printer_print_str(P, "Schedule\n");
642       P = isl_printer_print_str(P, "========\n");
643       if (Schedule)
644         P = isl_printer_print_schedule(P, Schedule);
645       else
646         P = isl_printer_print_str(P, "No schedule found\n");
647 
648       printf("%s\n", isl_printer_get_str(P));
649       isl_printer_free(P);
650     }
651 
652     if (DumpCode) {
653       printf("Code\n");
654       printf("====\n");
655       if (PPCGGen->tree)
656         printGPUTree(PPCGGen->tree, PPCGProg);
657       else
658         printf("No code generated\n");
659     }
660 
661     isl_schedule_free(Schedule);
662 
663     return PPCGGen;
664   }
665 
666   /// Free gpu_gen structure.
667   ///
668   /// @param PPCGGen The ppcg_gen object to free.
669   void freePPCGGen(gpu_gen *PPCGGen) {
670     isl_ast_node_free(PPCGGen->tree);
671     isl_union_map_free(PPCGGen->sizes);
672     isl_union_map_free(PPCGGen->used_sizes);
673     free(PPCGGen);
674   }
675 
676   /// Free the options in the ppcg scop structure.
677   ///
678   /// ppcg is not freeing these options for us. To avoid leaks we do this
679   /// ourselves.
680   ///
681   /// @param PPCGScop The scop referencing the options to free.
682   void freeOptions(ppcg_scop *PPCGScop) {
683     free(PPCGScop->options->debug);
684     PPCGScop->options->debug = nullptr;
685     free(PPCGScop->options);
686     PPCGScop->options = nullptr;
687   }
688 
689   /// Generate code for a given GPU AST described by @p Root.
690   ///
691   /// @param An isl_ast_node pointing to the root of the GPU AST.
692   void generateCode(__isl_take isl_ast_node *Root) {
693     ScopAnnotator Annotator;
694     Annotator.buildAliasScopes(*S);
695 
696     Region *R = &S->getRegion();
697 
698     simplifyRegion(R, DT, LI, RI);
699 
700     BasicBlock *EnteringBB = R->getEnteringBlock();
701 
702     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
703 
704     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT,
705                                *S);
706 
707     // Only build the run-time condition and parameters _after_ having
708     // introduced the conditional branch. This is important as the conditional
709     // branch will guard the original scop from new induction variables that
710     // the SCEVExpander may introduce while code generating the parameters and
711     // which may introduce scalar dependences that prevent us from correctly
712     // code generating this scop.
713     BasicBlock *StartBlock =
714         executeScopConditionally(*S, this, Builder.getTrue());
715 
716     // TODO: Handle LICM
717     // TODO: Verify run-time checks
718     auto SplitBlock = StartBlock->getSinglePredecessor();
719     Builder.SetInsertPoint(SplitBlock->getTerminator());
720     NodeBuilder.addParameters(S->getContext());
721     Builder.SetInsertPoint(&*StartBlock->begin());
722     NodeBuilder.create(Root);
723     NodeBuilder.finalizeSCoP(*S);
724   }
725 
726   bool runOnScop(Scop &CurrentScop) override {
727     S = &CurrentScop;
728     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
729     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
730     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
731     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
732     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
733 
734     auto PPCGScop = createPPCGScop();
735     auto PPCGProg = createPPCGProg(PPCGScop);
736     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
737 
738     if (PPCGGen->tree)
739       generateCode(isl_ast_node_copy(PPCGGen->tree));
740 
741     freeOptions(PPCGScop);
742     freePPCGGen(PPCGGen);
743     gpu_prog_free(PPCGProg);
744     ppcg_scop_free(PPCGScop);
745 
746     return true;
747   }
748 
749   void printScop(raw_ostream &, Scop &) const override {}
750 
751   void getAnalysisUsage(AnalysisUsage &AU) const override {
752     AU.addRequired<DominatorTreeWrapperPass>();
753     AU.addRequired<RegionInfoPass>();
754     AU.addRequired<ScalarEvolutionWrapperPass>();
755     AU.addRequired<ScopDetection>();
756     AU.addRequired<ScopInfoRegionPass>();
757     AU.addRequired<LoopInfoWrapperPass>();
758 
759     AU.addPreserved<AAResultsWrapperPass>();
760     AU.addPreserved<BasicAAWrapperPass>();
761     AU.addPreserved<LoopInfoWrapperPass>();
762     AU.addPreserved<DominatorTreeWrapperPass>();
763     AU.addPreserved<GlobalsAAWrapperPass>();
764     AU.addPreserved<PostDominatorTreeWrapperPass>();
765     AU.addPreserved<ScopDetection>();
766     AU.addPreserved<ScalarEvolutionWrapperPass>();
767     AU.addPreserved<SCEVAAWrapperPass>();
768 
769     // FIXME: We do not yet add regions for the newly generated code to the
770     //        region tree.
771     AU.addPreserved<RegionInfoPass>();
772     AU.addPreserved<ScopInfoRegionPass>();
773   }
774 };
775 }
776 
777 char PPCGCodeGeneration::ID = 1;
778 
779 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
780 
781 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
782                       "Polly - Apply PPCG translation to SCOP", false, false)
783 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
784 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
785 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
786 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
787 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
788 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
789 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
790                     "Polly - Apply PPCG translation to SCOP", false, false)
791