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