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