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