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 "polly/Support/SCEVValidator.h"
22 #include "llvm/ADT/PostOrderIterator.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/BasicAliasAnalysis.h"
25 #include "llvm/Analysis/GlobalsModRef.h"
26 #include "llvm/Analysis/PostDominators.h"
27 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/TargetSelect.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
36 
37 #include "isl/union_map.h"
38 
39 extern "C" {
40 #include "ppcg/cuda.h"
41 #include "ppcg/gpu.h"
42 #include "ppcg/gpu_print.h"
43 #include "ppcg/ppcg.h"
44 #include "ppcg/schedule.h"
45 }
46 
47 #include "llvm/Support/Debug.h"
48 
49 using namespace polly;
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "polly-codegen-ppcg"
53 
54 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
55                                   cl::desc("Dump the computed GPU Schedule"),
56                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
57                                   cl::cat(PollyCategory));
58 
59 static cl::opt<bool>
60     DumpCode("polly-acc-dump-code",
61              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
62              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
63 
64 static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
65                                   cl::desc("Dump the kernel LLVM-IR"),
66                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
67                                   cl::cat(PollyCategory));
68 
69 static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
70                                    cl::desc("Dump the kernel assembly code"),
71                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
72                                    cl::cat(PollyCategory));
73 
74 static cl::opt<bool> FastMath("polly-acc-fastmath",
75                               cl::desc("Allow unsafe math optimizations"),
76                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
77                               cl::cat(PollyCategory));
78 
79 static cl::opt<std::string>
80     CudaVersion("polly-acc-cuda-version",
81                 cl::desc("The CUDA version to compile for"), cl::Hidden,
82                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
83 
84 /// Create the ast expressions for a ScopStmt.
85 ///
86 /// This function is a callback for to generate the ast expressions for each
87 /// of the scheduled ScopStmts.
88 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
89     void *StmtT, isl_ast_build *Build,
90     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
91                                        isl_id *Id, void *User),
92     void *UserIndex,
93     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
94     void *UserExpr) {
95 
96   ScopStmt *Stmt = (ScopStmt *)StmtT;
97 
98   isl_ctx *Ctx;
99 
100   if (!Stmt || !Build)
101     return NULL;
102 
103   Ctx = isl_ast_build_get_ctx(Build);
104   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
105 
106   for (MemoryAccess *Acc : *Stmt) {
107     isl_map *AddrFunc = Acc->getAddressFunction();
108     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
109     isl_id *RefId = Acc->getId();
110     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
111     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
112     MPA = isl_multi_pw_aff_coalesce(MPA);
113     MPA = FunctionIndex(MPA, RefId, UserIndex);
114     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
115     Access = FunctionExpr(Access, RefId, UserExpr);
116     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
117   }
118 
119   return RefToExpr;
120 }
121 
122 /// Generate code for a GPU specific isl AST.
123 ///
124 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
125 /// generates code for general-prupose AST nodes, with special functionality
126 /// for generating GPU specific user nodes.
127 ///
128 /// @see GPUNodeBuilder::createUser
129 class GPUNodeBuilder : public IslNodeBuilder {
130 public:
131   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
132                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
133                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
134       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
135     getExprBuilder().setIDToSAI(&IDToSAI);
136   }
137 
138   /// Create after-run-time-check initialization code.
139   void initializeAfterRTH();
140 
141   /// Finalize the generated scop.
142   virtual void finalize();
143 
144 private:
145   /// A vector of array base pointers for which a new ScopArrayInfo was created.
146   ///
147   /// This vector is used to delete the ScopArrayInfo when it is not needed any
148   /// more.
149   std::vector<Value *> LocalArrays;
150 
151   /// A map from ScopArrays to their corresponding device allocations.
152   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
153 
154   /// The current GPU context.
155   Value *GPUContext;
156 
157   /// A module containing GPU code.
158   ///
159   /// This pointer is only set in case we are currently generating GPU code.
160   std::unique_ptr<Module> GPUModule;
161 
162   /// The GPU program we generate code for.
163   gpu_prog *Prog;
164 
165   /// Class to free isl_ids.
166   class IslIdDeleter {
167   public:
168     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
169   };
170 
171   /// A set containing all isl_ids allocated in a GPU kernel.
172   ///
173   /// By releasing this set all isl_ids will be freed.
174   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
175 
176   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
177 
178   /// Create code for user-defined AST nodes.
179   ///
180   /// These AST nodes can be of type:
181   ///
182   ///   - ScopStmt:      A computational statement (TODO)
183   ///   - Kernel:        A GPU kernel call (TODO)
184   ///   - Data-Transfer: A GPU <-> CPU data-transfer
185   ///   - In-kernel synchronization
186   ///   - In-kernel memory copy statement
187   ///
188   /// @param UserStmt The ast node to generate code for.
189   virtual void createUser(__isl_take isl_ast_node *UserStmt);
190 
191   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
192 
193   /// Create code for a data transfer statement
194   ///
195   /// @param TransferStmt The data transfer statement.
196   /// @param Direction The direction in which to transfer data.
197   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
198                           enum DataDirection Direction);
199 
200   /// Find llvm::Values referenced in GPU kernel.
201   ///
202   /// @param Kernel The kernel to scan for llvm::Values
203   ///
204   /// @returns A set of values referenced by the kernel.
205   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
206 
207   /// Create GPU kernel.
208   ///
209   /// Code generate the kernel described by @p KernelStmt.
210   ///
211   /// @param KernelStmt The ast node to generate kernel code for.
212   void createKernel(__isl_take isl_ast_node *KernelStmt);
213 
214   /// Generate code that computes the size of an array.
215   ///
216   /// @param Array The array for which to compute a size.
217   Value *getArraySize(gpu_array_info *Array);
218 
219   /// Create kernel function.
220   ///
221   /// Create a kernel function located in a newly created module that can serve
222   /// as target for device code generation. Set the Builder to point to the
223   /// start block of this newly created function.
224   ///
225   /// @param Kernel The kernel to generate code for.
226   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
227   void createKernelFunction(ppcg_kernel *Kernel,
228                             SetVector<Value *> &SubtreeValues);
229 
230   /// Create the declaration of a kernel function.
231   ///
232   /// The kernel function takes as arguments:
233   ///
234   ///   - One i8 pointer for each external array reference used in the kernel.
235   ///   - Host iterators
236   ///   - Parameters
237   ///   - Other LLVM Value references (TODO)
238   ///
239   /// @param Kernel The kernel to generate the function declaration for.
240   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
241   ///
242   /// @returns The newly declared function.
243   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
244                                      SetVector<Value *> &SubtreeValues);
245 
246   /// Insert intrinsic functions to obtain thread and block ids.
247   ///
248   /// @param The kernel to generate the intrinsic functions for.
249   void insertKernelIntrinsics(ppcg_kernel *Kernel);
250 
251   /// Create code for a ScopStmt called in @p Expr.
252   ///
253   /// @param Expr The expression containing the call.
254   /// @param KernelStmt The kernel statement referenced in the call.
255   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
256 
257   /// Create an in-kernel synchronization call.
258   void createKernelSync();
259 
260   /// Create a PTX assembly string for the current GPU kernel.
261   ///
262   /// @returns A string containing the corresponding PTX assembly code.
263   std::string createKernelASM();
264 
265   /// Remove references from the dominator tree to the kernel function @p F.
266   ///
267   /// @param F The function to remove references to.
268   void clearDominators(Function *F);
269 
270   /// Remove references from scalar evolution to the kernel function @p F.
271   ///
272   /// @param F The function to remove references to.
273   void clearScalarEvolution(Function *F);
274 
275   /// Remove references from loop info to the kernel function @p F.
276   ///
277   /// @param F The function to remove references to.
278   void clearLoops(Function *F);
279 
280   /// Finalize the generation of the kernel function.
281   ///
282   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
283   /// dump its IR to stderr.
284   void finalizeKernelFunction();
285 
286   /// Create code that allocates memory to store arrays on device.
287   void allocateDeviceArrays();
288 
289   /// Free all allocated device arrays.
290   void freeDeviceArrays();
291 
292   /// Create a call to initialize the GPU context.
293   ///
294   /// @returns A pointer to the newly initialized context.
295   Value *createCallInitContext();
296 
297   /// Create a call to free the GPU context.
298   ///
299   /// @param Context A pointer to an initialized GPU context.
300   void createCallFreeContext(Value *Context);
301 
302   /// Create a call to allocate memory on the device.
303   ///
304   /// @param Size The size of memory to allocate
305   ///
306   /// @returns A pointer that identifies this allocation.
307   Value *createCallAllocateMemoryForDevice(Value *Size);
308 
309   /// Create a call to free a device array.
310   ///
311   /// @param Array The device array to free.
312   void createCallFreeDeviceMemory(Value *Array);
313 
314   /// Create a call to copy data from host to device.
315   ///
316   /// @param HostPtr A pointer to the host data that should be copied.
317   /// @param DevicePtr A device pointer specifying the location to copy to.
318   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
319                                       Value *Size);
320 
321   /// Create a call to copy data from device to host.
322   ///
323   /// @param DevicePtr A pointer to the device data that should be copied.
324   /// @param HostPtr A host pointer specifying the location to copy to.
325   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
326                                       Value *Size);
327 };
328 
329 void GPUNodeBuilder::initializeAfterRTH() {
330   GPUContext = createCallInitContext();
331   allocateDeviceArrays();
332 }
333 
334 void GPUNodeBuilder::finalize() {
335   freeDeviceArrays();
336   createCallFreeContext(GPUContext);
337   IslNodeBuilder::finalize();
338 }
339 
340 void GPUNodeBuilder::allocateDeviceArrays() {
341   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
342 
343   for (int i = 0; i < Prog->n_array; ++i) {
344     gpu_array_info *Array = &Prog->array[i];
345     auto *ScopArray = (ScopArrayInfo *)Array->user;
346     std::string DevArrayName("p_dev_array_");
347     DevArrayName.append(Array->name);
348 
349     Value *ArraySize = getArraySize(Array);
350     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
351     DevArray->setName(DevArrayName);
352     DeviceAllocations[ScopArray] = DevArray;
353   }
354 
355   isl_ast_build_free(Build);
356 }
357 
358 void GPUNodeBuilder::freeDeviceArrays() {
359   for (auto &Array : DeviceAllocations)
360     createCallFreeDeviceMemory(Array.second);
361 }
362 
363 void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
364   const char *Name = "polly_freeDeviceMemory";
365   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
366   Function *F = M->getFunction(Name);
367 
368   // If F is not available, declare it.
369   if (!F) {
370     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
371     std::vector<Type *> Args;
372     Args.push_back(Builder.getInt8PtrTy());
373     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
374     F = Function::Create(Ty, Linkage, Name, M);
375   }
376 
377   Builder.CreateCall(F, {Array});
378 }
379 
380 Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
381   const char *Name = "polly_allocateMemoryForDevice";
382   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
383   Function *F = M->getFunction(Name);
384 
385   // If F is not available, declare it.
386   if (!F) {
387     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
388     std::vector<Type *> Args;
389     Args.push_back(Builder.getInt64Ty());
390     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
391     F = Function::Create(Ty, Linkage, Name, M);
392   }
393 
394   return Builder.CreateCall(F, {Size});
395 }
396 
397 void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
398                                                     Value *DeviceData,
399                                                     Value *Size) {
400   const char *Name = "polly_copyFromHostToDevice";
401   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
402   Function *F = M->getFunction(Name);
403 
404   // If F is not available, declare it.
405   if (!F) {
406     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
407     std::vector<Type *> Args;
408     Args.push_back(Builder.getInt8PtrTy());
409     Args.push_back(Builder.getInt8PtrTy());
410     Args.push_back(Builder.getInt64Ty());
411     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
412     F = Function::Create(Ty, Linkage, Name, M);
413   }
414 
415   Builder.CreateCall(F, {HostData, DeviceData, Size});
416 }
417 
418 void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
419                                                     Value *HostData,
420                                                     Value *Size) {
421   const char *Name = "polly_copyFromDeviceToHost";
422   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
423   Function *F = M->getFunction(Name);
424 
425   // If F is not available, declare it.
426   if (!F) {
427     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
428     std::vector<Type *> Args;
429     Args.push_back(Builder.getInt8PtrTy());
430     Args.push_back(Builder.getInt8PtrTy());
431     Args.push_back(Builder.getInt64Ty());
432     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
433     F = Function::Create(Ty, Linkage, Name, M);
434   }
435 
436   Builder.CreateCall(F, {DeviceData, HostData, Size});
437 }
438 
439 Value *GPUNodeBuilder::createCallInitContext() {
440   const char *Name = "polly_initContext";
441   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
442   Function *F = M->getFunction(Name);
443 
444   // If F is not available, declare it.
445   if (!F) {
446     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
447     std::vector<Type *> Args;
448     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
449     F = Function::Create(Ty, Linkage, Name, M);
450   }
451 
452   return Builder.CreateCall(F, {});
453 }
454 
455 void GPUNodeBuilder::createCallFreeContext(Value *Context) {
456   const char *Name = "polly_freeContext";
457   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
458   Function *F = M->getFunction(Name);
459 
460   // If F is not available, declare it.
461   if (!F) {
462     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
463     std::vector<Type *> Args;
464     Args.push_back(Builder.getInt8PtrTy());
465     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
466     F = Function::Create(Ty, Linkage, Name, M);
467   }
468 
469   Builder.CreateCall(F, {Context});
470 }
471 
472 /// Check if one string is a prefix of another.
473 ///
474 /// @param String The string in which to look for the prefix.
475 /// @param Prefix The prefix to look for.
476 static bool isPrefix(std::string String, std::string Prefix) {
477   return String.find(Prefix) == 0;
478 }
479 
480 Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
481   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
482   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
483 
484   if (!gpu_array_is_scalar(Array)) {
485     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
486     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
487 
488     for (unsigned int i = 1; i < Array->n_index; i++) {
489       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
490       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
491       Res = isl_ast_expr_mul(Res, Expr);
492     }
493 
494     Value *NumElements = ExprBuilder.create(Res);
495     ArraySize = Builder.CreateMul(ArraySize, NumElements);
496   }
497   isl_ast_build_free(Build);
498   return ArraySize;
499 }
500 
501 void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
502                                         enum DataDirection Direction) {
503   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
504   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
505   isl_id *Id = isl_ast_expr_get_id(Arg);
506   auto Array = (gpu_array_info *)isl_id_get_user(Id);
507   auto ScopArray = (ScopArrayInfo *)(Array->user);
508 
509   Value *Size = getArraySize(Array);
510   Value *HostPtr = ScopArray->getBasePtr();
511 
512   Value *DevPtr = DeviceAllocations[ScopArray];
513 
514   if (gpu_array_is_scalar(Array)) {
515     HostPtr = Builder.CreateAlloca(ScopArray->getElementType());
516     Builder.CreateStore(ScopArray->getBasePtr(), HostPtr);
517   }
518 
519   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
520 
521   if (Direction == HOST_TO_DEVICE)
522     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
523   else
524     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
525 
526   isl_id_free(Id);
527   isl_ast_expr_free(Arg);
528   isl_ast_expr_free(Expr);
529   isl_ast_node_free(TransferStmt);
530 }
531 
532 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
533   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
534   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
535   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
536   isl_id_free(Id);
537   isl_ast_expr_free(StmtExpr);
538 
539   const char *Str = isl_id_get_name(Id);
540   if (!strcmp(Str, "kernel")) {
541     createKernel(UserStmt);
542     isl_ast_expr_free(Expr);
543     return;
544   }
545 
546   if (isPrefix(Str, "to_device")) {
547     createDataTransfer(UserStmt, HOST_TO_DEVICE);
548     isl_ast_expr_free(Expr);
549     return;
550   }
551 
552   if (isPrefix(Str, "from_device")) {
553     createDataTransfer(UserStmt, DEVICE_TO_HOST);
554     isl_ast_expr_free(Expr);
555     return;
556   }
557 
558   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
559   struct ppcg_kernel_stmt *KernelStmt =
560       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
561   isl_id_free(Anno);
562 
563   switch (KernelStmt->type) {
564   case ppcg_kernel_domain:
565     createScopStmt(Expr, KernelStmt);
566     isl_ast_node_free(UserStmt);
567     return;
568   case ppcg_kernel_copy:
569     // TODO: Create kernel copy stmt
570     isl_ast_expr_free(Expr);
571     isl_ast_node_free(UserStmt);
572     return;
573   case ppcg_kernel_sync:
574     createKernelSync();
575     isl_ast_expr_free(Expr);
576     isl_ast_node_free(UserStmt);
577     return;
578   }
579 
580   isl_ast_expr_free(Expr);
581   isl_ast_node_free(UserStmt);
582   return;
583 }
584 
585 void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
586                                     ppcg_kernel_stmt *KernelStmt) {
587   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
588   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
589 
590   LoopToScevMapT LTS;
591   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
592 
593   createSubstitutions(Expr, Stmt, LTS);
594 
595   if (Stmt->isBlockStmt())
596     BlockGen.copyStmt(*Stmt, LTS, Indexes);
597   else
598     assert(0 && "Region statement not supported\n");
599 }
600 
601 void GPUNodeBuilder::createKernelSync() {
602   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
603   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
604   Builder.CreateCall(Sync, {});
605 }
606 
607 /// Collect llvm::Values referenced from @p Node
608 ///
609 /// This function only applies to isl_ast_nodes that are user_nodes referring
610 /// to a ScopStmt. All other node types are ignore.
611 ///
612 /// @param Node The node to collect references for.
613 /// @param User A user pointer used as storage for the data that is collected.
614 ///
615 /// @returns isl_bool_true if data could be collected successfully.
616 isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
617   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
618     return isl_bool_true;
619 
620   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
621   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
622   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
623   const char *Str = isl_id_get_name(Id);
624   isl_id_free(Id);
625   isl_ast_expr_free(StmtExpr);
626   isl_ast_expr_free(Expr);
627 
628   if (!isPrefix(Str, "Stmt"))
629     return isl_bool_true;
630 
631   Id = isl_ast_node_get_annotation(Node);
632   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
633   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
634   isl_id_free(Id);
635 
636   addReferencesFromStmt(Stmt, User);
637 
638   return isl_bool_true;
639 }
640 
641 SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
642   SetVector<Value *> SubtreeValues;
643   SetVector<const SCEV *> SCEVs;
644   SetVector<const Loop *> Loops;
645   SubtreeReferences References = {
646       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
647 
648   for (const auto &I : IDToValue)
649     SubtreeValues.insert(I.second);
650 
651   isl_ast_node_foreach_descendant_top_down(
652       Kernel->tree, collectReferencesInGPUStmt, &References);
653 
654   for (const SCEV *Expr : SCEVs)
655     findValues(Expr, SE, SubtreeValues);
656 
657   for (auto &SAI : S.arrays())
658     SubtreeValues.remove(SAI.second->getBasePtr());
659 
660   isl_space *Space = S.getParamSpace();
661   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
662     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
663     assert(IDToValue.count(Id));
664     Value *Val = IDToValue[Id];
665     SubtreeValues.remove(Val);
666     isl_id_free(Id);
667   }
668   isl_space_free(Space);
669 
670   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
671     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
672     assert(IDToValue.count(Id));
673     Value *Val = IDToValue[Id];
674     SubtreeValues.remove(Val);
675     isl_id_free(Id);
676   }
677 
678   return SubtreeValues;
679 }
680 
681 void GPUNodeBuilder::clearDominators(Function *F) {
682   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
683   std::vector<BasicBlock *> Nodes;
684   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
685     Nodes.push_back(I->getBlock());
686 
687   for (BasicBlock *BB : Nodes)
688     DT.eraseNode(BB);
689 }
690 
691 void GPUNodeBuilder::clearScalarEvolution(Function *F) {
692   for (BasicBlock &BB : *F) {
693     Loop *L = LI.getLoopFor(&BB);
694     if (L)
695       SE.forgetLoop(L);
696   }
697 }
698 
699 void GPUNodeBuilder::clearLoops(Function *F) {
700   for (BasicBlock &BB : *F) {
701     Loop *L = LI.getLoopFor(&BB);
702     if (L)
703       SE.forgetLoop(L);
704     LI.removeBlock(&BB);
705   }
706 }
707 
708 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
709   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
710   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
711   isl_id_free(Id);
712   isl_ast_node_free(KernelStmt);
713 
714   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
715 
716   assert(Kernel->tree && "Device AST of kernel node is empty");
717 
718   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
719   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
720   ValueMapT HostValueMap = ValueMap;
721 
722   SetVector<const Loop *> Loops;
723 
724   // Create for all loops we depend on values that contain the current loop
725   // iteration. These values are necessary to generate code for SCEVs that
726   // depend on such loops. As a result we need to pass them to the subfunction.
727   for (const Loop *L : Loops) {
728     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
729                                             SE.getUnknown(Builder.getInt64(1)),
730                                             L, SCEV::FlagAnyWrap);
731     Value *V = generateSCEV(OuterLIV);
732     OutsideLoopIterations[L] = SE.getUnknown(V);
733     SubtreeValues.insert(V);
734   }
735 
736   createKernelFunction(Kernel, SubtreeValues);
737 
738   create(isl_ast_node_copy(Kernel->tree));
739 
740   Function *F = Builder.GetInsertBlock()->getParent();
741   clearDominators(F);
742   clearScalarEvolution(F);
743   clearLoops(F);
744 
745   Builder.SetInsertPoint(&HostInsertPoint);
746   IDToValue = HostIDs;
747 
748   ValueMap = HostValueMap;
749   ScalarMap.clear();
750   PHIOpMap.clear();
751   EscapeMap.clear();
752   IDToSAI.clear();
753   Annotator.resetAlternativeAliasBases();
754   for (auto &BasePtr : LocalArrays)
755     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
756   LocalArrays.clear();
757 
758   finalizeKernelFunction();
759 }
760 
761 /// Compute the DataLayout string for the NVPTX backend.
762 ///
763 /// @param is64Bit Are we looking for a 64 bit architecture?
764 static std::string computeNVPTXDataLayout(bool is64Bit) {
765   std::string Ret = "e";
766 
767   if (!is64Bit)
768     Ret += "-p:32:32";
769 
770   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
771 
772   return Ret;
773 }
774 
775 Function *
776 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
777                                          SetVector<Value *> &SubtreeValues) {
778   std::vector<Type *> Args;
779   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
780 
781   for (long i = 0; i < Prog->n_array; i++) {
782     if (!ppcg_kernel_requires_array_argument(Kernel, i))
783       continue;
784 
785     Args.push_back(Builder.getInt8PtrTy());
786   }
787 
788   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
789 
790   for (long i = 0; i < NumHostIters; i++)
791     Args.push_back(Builder.getInt64Ty());
792 
793   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
794 
795   for (long i = 0; i < NumVars; i++)
796     Args.push_back(Builder.getInt64Ty());
797 
798   for (auto *V : SubtreeValues)
799     Args.push_back(V->getType());
800 
801   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
802   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
803                               GPUModule.get());
804   FN->setCallingConv(CallingConv::PTX_Kernel);
805 
806   auto Arg = FN->arg_begin();
807   for (long i = 0; i < Kernel->n_array; i++) {
808     if (!ppcg_kernel_requires_array_argument(Kernel, i))
809       continue;
810 
811     Arg->setName(Kernel->array[i].array->name);
812 
813     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
814     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
815     Type *EleTy = SAI->getElementType();
816     Value *Val = &*Arg;
817     SmallVector<const SCEV *, 4> Sizes;
818     isl_ast_build *Build =
819         isl_ast_build_from_context(isl_set_copy(Prog->context));
820     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
821       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
822           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
823       auto V = ExprBuilder.create(DimSize);
824       Sizes.push_back(SE.getSCEV(V));
825     }
826     const ScopArrayInfo *SAIRep =
827         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
828     LocalArrays.push_back(Val);
829 
830     isl_ast_build_free(Build);
831     isl_id_free(Id);
832     IDToSAI[Id] = SAIRep;
833     Arg++;
834   }
835 
836   for (long i = 0; i < NumHostIters; i++) {
837     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
838     Arg->setName(isl_id_get_name(Id));
839     IDToValue[Id] = &*Arg;
840     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
841     Arg++;
842   }
843 
844   for (long i = 0; i < NumVars; i++) {
845     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
846     Arg->setName(isl_id_get_name(Id));
847     IDToValue[Id] = &*Arg;
848     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
849     Arg++;
850   }
851 
852   for (auto *V : SubtreeValues) {
853     Arg->setName(V->getName());
854     ValueMap[V] = &*Arg;
855     Arg++;
856   }
857 
858   return FN;
859 }
860 
861 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
862   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
863                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
864 
865   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
866                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
867                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
868 
869   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
870     std::string Name = isl_id_get_name(Id);
871     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
872     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
873     Value *Val = Builder.CreateCall(IntrinsicFn, {});
874     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
875     IDToValue[Id] = Val;
876     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
877   };
878 
879   for (int i = 0; i < Kernel->n_grid; ++i) {
880     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
881     addId(Id, IntrinsicsBID[i]);
882   }
883 
884   for (int i = 0; i < Kernel->n_block; ++i) {
885     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
886     addId(Id, IntrinsicsTID[i]);
887   }
888 }
889 
890 void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
891                                           SetVector<Value *> &SubtreeValues) {
892 
893   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
894   GPUModule.reset(new Module(Identifier, Builder.getContext()));
895   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
896   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
897 
898   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
899 
900   BasicBlock *PrevBlock = Builder.GetInsertBlock();
901   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
902 
903   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
904   DT.addNewBlock(EntryBlock, PrevBlock);
905 
906   Builder.SetInsertPoint(EntryBlock);
907   Builder.CreateRetVoid();
908   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
909 
910   insertKernelIntrinsics(Kernel);
911 }
912 
913 std::string GPUNodeBuilder::createKernelASM() {
914   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
915   std::string ErrMsg;
916   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
917 
918   if (!GPUTarget) {
919     errs() << ErrMsg << "\n";
920     return "";
921   }
922 
923   TargetOptions Options;
924   Options.UnsafeFPMath = FastMath;
925   std::unique_ptr<TargetMachine> TargetM(
926       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
927                                      Options, Optional<Reloc::Model>()));
928 
929   SmallString<0> ASMString;
930   raw_svector_ostream ASMStream(ASMString);
931   llvm::legacy::PassManager PM;
932 
933   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
934 
935   if (TargetM->addPassesToEmitFile(
936           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
937     errs() << "The target does not support generation of this file type!\n";
938     return "";
939   }
940 
941   PM.run(*GPUModule);
942 
943   return ASMStream.str();
944 }
945 
946 void GPUNodeBuilder::finalizeKernelFunction() {
947   // Verify module.
948   llvm::legacy::PassManager Passes;
949   Passes.add(createVerifierPass());
950   Passes.run(*GPUModule);
951 
952   if (DumpKernelIR)
953     outs() << *GPUModule << "\n";
954 
955   // Optimize module.
956   llvm::legacy::PassManager OptPasses;
957   PassManagerBuilder PassBuilder;
958   PassBuilder.OptLevel = 3;
959   PassBuilder.SizeLevel = 0;
960   PassBuilder.populateModulePassManager(OptPasses);
961   OptPasses.run(*GPUModule);
962 
963   std::string Assembly = createKernelASM();
964 
965   if (DumpKernelASM)
966     outs() << Assembly << "\n";
967 
968   GPUModule.release();
969   KernelIDs.clear();
970 }
971 
972 namespace {
973 class PPCGCodeGeneration : public ScopPass {
974 public:
975   static char ID;
976 
977   /// The scop that is currently processed.
978   Scop *S;
979 
980   LoopInfo *LI;
981   DominatorTree *DT;
982   ScalarEvolution *SE;
983   const DataLayout *DL;
984   RegionInfo *RI;
985 
986   PPCGCodeGeneration() : ScopPass(ID) {}
987 
988   /// Construct compilation options for PPCG.
989   ///
990   /// @returns The compilation options.
991   ppcg_options *createPPCGOptions() {
992     auto DebugOptions =
993         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
994     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
995 
996     DebugOptions->dump_schedule_constraints = false;
997     DebugOptions->dump_schedule = false;
998     DebugOptions->dump_final_schedule = false;
999     DebugOptions->dump_sizes = false;
1000 
1001     Options->debug = DebugOptions;
1002 
1003     Options->reschedule = true;
1004     Options->scale_tile_loops = false;
1005     Options->wrap = false;
1006 
1007     Options->non_negative_parameters = false;
1008     Options->ctx = nullptr;
1009     Options->sizes = nullptr;
1010 
1011     Options->tile_size = 32;
1012 
1013     Options->use_private_memory = false;
1014     Options->use_shared_memory = false;
1015     Options->max_shared_memory = 0;
1016 
1017     Options->target = PPCG_TARGET_CUDA;
1018     Options->openmp = false;
1019     Options->linearize_device_arrays = true;
1020     Options->live_range_reordering = false;
1021 
1022     Options->opencl_compiler_options = nullptr;
1023     Options->opencl_use_gpu = false;
1024     Options->opencl_n_include_file = 0;
1025     Options->opencl_include_files = nullptr;
1026     Options->opencl_print_kernel_types = false;
1027     Options->opencl_embed_kernel_code = false;
1028 
1029     Options->save_schedule_file = nullptr;
1030     Options->load_schedule_file = nullptr;
1031 
1032     return Options;
1033   }
1034 
1035   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1036   ///
1037   /// Instead of a normal access of the form:
1038   ///
1039   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1040   ///
1041   /// a tagged access has the form
1042   ///
1043   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1044   ///
1045   /// where 'id' is an additional space that references the memory access that
1046   /// triggered the access.
1047   ///
1048   /// @param AccessTy The type of the memory accesses to collect.
1049   ///
1050   /// @return The relation describing all tagged memory accesses.
1051   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1052     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1053 
1054     for (auto &Stmt : *S)
1055       for (auto &Acc : Stmt)
1056         if (Acc->getType() == AccessTy) {
1057           isl_map *Relation = Acc->getAccessRelation();
1058           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1059 
1060           isl_space *Space = isl_map_get_space(Relation);
1061           Space = isl_space_range(Space);
1062           Space = isl_space_from_range(Space);
1063           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1064           isl_map *Universe = isl_map_universe(Space);
1065           Relation = isl_map_domain_product(Relation, Universe);
1066           Accesses = isl_union_map_add_map(Accesses, Relation);
1067         }
1068 
1069     return Accesses;
1070   }
1071 
1072   /// Get the set of all read accesses, tagged with the access id.
1073   ///
1074   /// @see getTaggedAccesses
1075   isl_union_map *getTaggedReads() {
1076     return getTaggedAccesses(MemoryAccess::READ);
1077   }
1078 
1079   /// Get the set of all may (and must) accesses, tagged with the access id.
1080   ///
1081   /// @see getTaggedAccesses
1082   isl_union_map *getTaggedMayWrites() {
1083     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1084                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1085   }
1086 
1087   /// Get the set of all must accesses, tagged with the access id.
1088   ///
1089   /// @see getTaggedAccesses
1090   isl_union_map *getTaggedMustWrites() {
1091     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1092   }
1093 
1094   /// Collect parameter and array names as isl_ids.
1095   ///
1096   /// To reason about the different parameters and arrays used, ppcg requires
1097   /// a list of all isl_ids in use. As PPCG traditionally performs
1098   /// source-to-source compilation each of these isl_ids is mapped to the
1099   /// expression that represents it. As we do not have a corresponding
1100   /// expression in Polly, we just map each id to a 'zero' expression to match
1101   /// the data format that ppcg expects.
1102   ///
1103   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1104   __isl_give isl_id_to_ast_expr *getNames() {
1105     auto *Names = isl_id_to_ast_expr_alloc(
1106         S->getIslCtx(),
1107         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1108     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1109     auto *Space = S->getParamSpace();
1110 
1111     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1112       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1113       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1114     }
1115 
1116     for (auto &Array : S->arrays()) {
1117       auto Id = Array.second->getBasePtrId();
1118       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1119     }
1120 
1121     isl_space_free(Space);
1122     isl_ast_expr_free(Zero);
1123 
1124     return Names;
1125   }
1126 
1127   /// Create a new PPCG scop from the current scop.
1128   ///
1129   /// The PPCG scop is initialized with data from the current polly::Scop. From
1130   /// this initial data, the data-dependences in the PPCG scop are initialized.
1131   /// We do not use Polly's dependence analysis for now, to ensure we match
1132   /// the PPCG default behaviour more closely.
1133   ///
1134   /// @returns A new ppcg scop.
1135   ppcg_scop *createPPCGScop() {
1136     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1137 
1138     PPCGScop->options = createPPCGOptions();
1139 
1140     PPCGScop->start = 0;
1141     PPCGScop->end = 0;
1142 
1143     PPCGScop->context = S->getContext();
1144     PPCGScop->domain = S->getDomains();
1145     PPCGScop->call = nullptr;
1146     PPCGScop->tagged_reads = getTaggedReads();
1147     PPCGScop->reads = S->getReads();
1148     PPCGScop->live_in = nullptr;
1149     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1150     PPCGScop->may_writes = S->getWrites();
1151     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1152     PPCGScop->must_writes = S->getMustWrites();
1153     PPCGScop->live_out = nullptr;
1154     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1155     PPCGScop->tagger = nullptr;
1156 
1157     PPCGScop->independence = nullptr;
1158     PPCGScop->dep_flow = nullptr;
1159     PPCGScop->tagged_dep_flow = nullptr;
1160     PPCGScop->dep_false = nullptr;
1161     PPCGScop->dep_forced = nullptr;
1162     PPCGScop->dep_order = nullptr;
1163     PPCGScop->tagged_dep_order = nullptr;
1164 
1165     PPCGScop->schedule = S->getScheduleTree();
1166     PPCGScop->names = getNames();
1167 
1168     PPCGScop->pet = nullptr;
1169 
1170     compute_tagger(PPCGScop);
1171     compute_dependences(PPCGScop);
1172 
1173     return PPCGScop;
1174   }
1175 
1176   /// Collect the array acesses in a statement.
1177   ///
1178   /// @param Stmt The statement for which to collect the accesses.
1179   ///
1180   /// @returns A list of array accesses.
1181   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
1182     gpu_stmt_access *Accesses = nullptr;
1183 
1184     for (MemoryAccess *Acc : Stmt) {
1185       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
1186       Access->read = Acc->isRead();
1187       Access->write = Acc->isWrite();
1188       Access->access = Acc->getAccessRelation();
1189       isl_space *Space = isl_map_get_space(Access->access);
1190       Space = isl_space_range(Space);
1191       Space = isl_space_from_range(Space);
1192       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1193       isl_map *Universe = isl_map_universe(Space);
1194       Access->tagged_access =
1195           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1196       Access->exact_write = Acc->isWrite();
1197       Access->ref_id = Acc->getId();
1198       Access->next = Accesses;
1199       Accesses = Access;
1200     }
1201 
1202     return Accesses;
1203   }
1204 
1205   /// Collect the list of GPU statements.
1206   ///
1207   /// Each statement has an id, a pointer to the underlying data structure,
1208   /// as well as a list with all memory accesses.
1209   ///
1210   /// TODO: Initialize the list of memory accesses.
1211   ///
1212   /// @returns A linked-list of statements.
1213   gpu_stmt *getStatements() {
1214     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
1215                                        std::distance(S->begin(), S->end()));
1216 
1217     int i = 0;
1218     for (auto &Stmt : *S) {
1219       gpu_stmt *GPUStmt = &Stmts[i];
1220 
1221       GPUStmt->id = Stmt.getDomainId();
1222 
1223       // We use the pet stmt pointer to keep track of the Polly statements.
1224       GPUStmt->stmt = (pet_stmt *)&Stmt;
1225       GPUStmt->accesses = getStmtAccesses(Stmt);
1226       i++;
1227     }
1228 
1229     return Stmts;
1230   }
1231 
1232   /// Derive the extent of an array.
1233   ///
1234   /// The extent of an array is defined by the set of memory locations for
1235   /// which a memory access in the iteration domain exists.
1236   ///
1237   /// @param Array The array to derive the extent for.
1238   ///
1239   /// @returns An isl_set describing the extent of the array.
1240   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1241     isl_union_map *Accesses = S->getAccesses();
1242     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1243     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1244     isl_set *AccessSet =
1245         isl_union_set_extract_set(AccessUSet, Array->getSpace());
1246     isl_union_set_free(AccessUSet);
1247 
1248     return AccessSet;
1249   }
1250 
1251   /// Derive the bounds of an array.
1252   ///
1253   /// For the first dimension we derive the bound of the array from the extent
1254   /// of this dimension. For inner dimensions we obtain their size directly from
1255   /// ScopArrayInfo.
1256   ///
1257   /// @param PPCGArray The array to compute bounds for.
1258   /// @param Array The polly array from which to take the information.
1259   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
1260     if (PPCGArray.n_index > 0) {
1261       isl_set *Dom = isl_set_copy(PPCGArray.extent);
1262       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
1263       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
1264       isl_set_free(Dom);
1265       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
1266       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
1267       isl_aff *One = isl_aff_zero_on_domain(LS);
1268       One = isl_aff_add_constant_si(One, 1);
1269       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
1270       Bound = isl_pw_aff_gist(Bound, S->getContext());
1271       PPCGArray.bound[0] = Bound;
1272     }
1273 
1274     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
1275       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
1276       auto LS = isl_pw_aff_get_domain_space(Bound);
1277       auto Aff = isl_multi_aff_zero(LS);
1278       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
1279       PPCGArray.bound[i] = Bound;
1280     }
1281   }
1282 
1283   /// Create the arrays for @p PPCGProg.
1284   ///
1285   /// @param PPCGProg The program to compute the arrays for.
1286   void createArrays(gpu_prog *PPCGProg) {
1287     int i = 0;
1288     for (auto &Element : S->arrays()) {
1289       ScopArrayInfo *Array = Element.second.get();
1290 
1291       std::string TypeName;
1292       raw_string_ostream OS(TypeName);
1293 
1294       OS << *Array->getElementType();
1295       TypeName = OS.str();
1296 
1297       gpu_array_info &PPCGArray = PPCGProg->array[i];
1298 
1299       PPCGArray.space = Array->getSpace();
1300       PPCGArray.type = strdup(TypeName.c_str());
1301       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
1302       PPCGArray.name = strdup(Array->getName().c_str());
1303       PPCGArray.extent = nullptr;
1304       PPCGArray.n_index = Array->getNumberOfDimensions();
1305       PPCGArray.bound =
1306           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
1307       PPCGArray.extent = getExtent(Array);
1308       PPCGArray.n_ref = 0;
1309       PPCGArray.refs = nullptr;
1310       PPCGArray.accessed = true;
1311       PPCGArray.read_only_scalar = false;
1312       PPCGArray.has_compound_element = false;
1313       PPCGArray.local = false;
1314       PPCGArray.declare_local = false;
1315       PPCGArray.global = false;
1316       PPCGArray.linearize = false;
1317       PPCGArray.dep_order = nullptr;
1318       PPCGArray.user = Array;
1319 
1320       setArrayBounds(PPCGArray, Array);
1321       i++;
1322 
1323       collect_references(PPCGProg, &PPCGArray);
1324     }
1325   }
1326 
1327   /// Create an identity map between the arrays in the scop.
1328   ///
1329   /// @returns An identity map between the arrays in the scop.
1330   isl_union_map *getArrayIdentity() {
1331     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
1332 
1333     for (auto &Item : S->arrays()) {
1334       ScopArrayInfo *Array = Item.second.get();
1335       isl_space *Space = Array->getSpace();
1336       Space = isl_space_map_from_set(Space);
1337       isl_map *Identity = isl_map_identity(Space);
1338       Maps = isl_union_map_add_map(Maps, Identity);
1339     }
1340 
1341     return Maps;
1342   }
1343 
1344   /// Create a default-initialized PPCG GPU program.
1345   ///
1346   /// @returns A new gpu grogram description.
1347   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1348 
1349     if (!PPCGScop)
1350       return nullptr;
1351 
1352     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1353 
1354     PPCGProg->ctx = S->getIslCtx();
1355     PPCGProg->scop = PPCGScop;
1356     PPCGProg->context = isl_set_copy(PPCGScop->context);
1357     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
1358     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
1359     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
1360     PPCGProg->tagged_must_kill =
1361         isl_union_map_copy(PPCGScop->tagged_must_kills);
1362     PPCGProg->to_inner = getArrayIdentity();
1363     PPCGProg->to_outer = getArrayIdentity();
1364     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1365     PPCGProg->any_to_outer = nullptr;
1366     PPCGProg->array_order = nullptr;
1367     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
1368     PPCGProg->stmts = getStatements();
1369     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
1370     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
1371                                        PPCGProg->n_array);
1372 
1373     createArrays(PPCGProg);
1374 
1375     return PPCGProg;
1376   }
1377 
1378   struct PrintGPUUserData {
1379     struct cuda_info *CudaInfo;
1380     struct gpu_prog *PPCGProg;
1381     std::vector<ppcg_kernel *> Kernels;
1382   };
1383 
1384   /// Print a user statement node in the host code.
1385   ///
1386   /// We use ppcg's printing facilities to print the actual statement and
1387   /// additionally build up a list of all kernels that are encountered in the
1388   /// host ast.
1389   ///
1390   /// @param P The printer to print to
1391   /// @param Options The printing options to use
1392   /// @param Node The node to print
1393   /// @param User A user pointer to carry additional data. This pointer is
1394   ///             expected to be of type PrintGPUUserData.
1395   ///
1396   /// @returns A printer to which the output has been printed.
1397   static __isl_give isl_printer *
1398   printHostUser(__isl_take isl_printer *P,
1399                 __isl_take isl_ast_print_options *Options,
1400                 __isl_take isl_ast_node *Node, void *User) {
1401     auto Data = (struct PrintGPUUserData *)User;
1402     auto Id = isl_ast_node_get_annotation(Node);
1403 
1404     if (Id) {
1405       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
1406 
1407       // If this is a user statement, format it ourselves as ppcg would
1408       // otherwise try to call pet functionality that is not available in
1409       // Polly.
1410       if (IsUser) {
1411         P = isl_printer_start_line(P);
1412         P = isl_printer_print_ast_node(P, Node);
1413         P = isl_printer_end_line(P);
1414         isl_id_free(Id);
1415         isl_ast_print_options_free(Options);
1416         return P;
1417       }
1418 
1419       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
1420       isl_id_free(Id);
1421       Data->Kernels.push_back(Kernel);
1422     }
1423 
1424     return print_host_user(P, Options, Node, User);
1425   }
1426 
1427   /// Print C code corresponding to the control flow in @p Kernel.
1428   ///
1429   /// @param Kernel The kernel to print
1430   void printKernel(ppcg_kernel *Kernel) {
1431     auto *P = isl_printer_to_str(S->getIslCtx());
1432     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
1433     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
1434     P = isl_ast_node_print(Kernel->tree, P, Options);
1435     char *String = isl_printer_get_str(P);
1436     printf("%s\n", String);
1437     free(String);
1438     isl_printer_free(P);
1439   }
1440 
1441   /// Print C code corresponding to the GPU code described by @p Tree.
1442   ///
1443   /// @param Tree An AST describing GPU code
1444   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
1445   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
1446     auto *P = isl_printer_to_str(S->getIslCtx());
1447     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
1448 
1449     PrintGPUUserData Data;
1450     Data.PPCGProg = PPCGProg;
1451 
1452     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
1453     Options =
1454         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
1455     P = isl_ast_node_print(Tree, P, Options);
1456     char *String = isl_printer_get_str(P);
1457     printf("# host\n");
1458     printf("%s\n", String);
1459     free(String);
1460     isl_printer_free(P);
1461 
1462     for (auto Kernel : Data.Kernels) {
1463       printf("# kernel%d\n", Kernel->id);
1464       printKernel(Kernel);
1465     }
1466   }
1467 
1468   // Generate a GPU program using PPCG.
1469   //
1470   // GPU mapping consists of multiple steps:
1471   //
1472   //  1) Compute new schedule for the program.
1473   //  2) Map schedule to GPU (TODO)
1474   //  3) Generate code for new schedule (TODO)
1475   //
1476   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1477   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1478   // strategy directly from this pass.
1479   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1480 
1481     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1482 
1483     PPCGGen->ctx = S->getIslCtx();
1484     PPCGGen->options = PPCGScop->options;
1485     PPCGGen->print = nullptr;
1486     PPCGGen->print_user = nullptr;
1487     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1488     PPCGGen->prog = PPCGProg;
1489     PPCGGen->tree = nullptr;
1490     PPCGGen->types.n = 0;
1491     PPCGGen->types.name = nullptr;
1492     PPCGGen->sizes = nullptr;
1493     PPCGGen->used_sizes = nullptr;
1494     PPCGGen->kernel_id = 0;
1495 
1496     // Set scheduling strategy to same strategy PPCG is using.
1497     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1498     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
1499     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1500 
1501     isl_schedule *Schedule = get_schedule(PPCGGen);
1502 
1503     int has_permutable = has_any_permutable_node(Schedule);
1504 
1505     if (!has_permutable || has_permutable < 0) {
1506       Schedule = isl_schedule_free(Schedule);
1507     } else {
1508       Schedule = map_to_device(PPCGGen, Schedule);
1509       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
1510     }
1511 
1512     if (DumpSchedule) {
1513       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1514       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1515       P = isl_printer_print_str(P, "Schedule\n");
1516       P = isl_printer_print_str(P, "========\n");
1517       if (Schedule)
1518         P = isl_printer_print_schedule(P, Schedule);
1519       else
1520         P = isl_printer_print_str(P, "No schedule found\n");
1521 
1522       printf("%s\n", isl_printer_get_str(P));
1523       isl_printer_free(P);
1524     }
1525 
1526     if (DumpCode) {
1527       printf("Code\n");
1528       printf("====\n");
1529       if (PPCGGen->tree)
1530         printGPUTree(PPCGGen->tree, PPCGProg);
1531       else
1532         printf("No code generated\n");
1533     }
1534 
1535     isl_schedule_free(Schedule);
1536 
1537     return PPCGGen;
1538   }
1539 
1540   /// Free gpu_gen structure.
1541   ///
1542   /// @param PPCGGen The ppcg_gen object to free.
1543   void freePPCGGen(gpu_gen *PPCGGen) {
1544     isl_ast_node_free(PPCGGen->tree);
1545     isl_union_map_free(PPCGGen->sizes);
1546     isl_union_map_free(PPCGGen->used_sizes);
1547     free(PPCGGen);
1548   }
1549 
1550   /// Free the options in the ppcg scop structure.
1551   ///
1552   /// ppcg is not freeing these options for us. To avoid leaks we do this
1553   /// ourselves.
1554   ///
1555   /// @param PPCGScop The scop referencing the options to free.
1556   void freeOptions(ppcg_scop *PPCGScop) {
1557     free(PPCGScop->options->debug);
1558     PPCGScop->options->debug = nullptr;
1559     free(PPCGScop->options);
1560     PPCGScop->options = nullptr;
1561   }
1562 
1563   /// Generate code for a given GPU AST described by @p Root.
1564   ///
1565   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
1566   /// @param Prog The GPU Program to generate code for.
1567   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
1568     ScopAnnotator Annotator;
1569     Annotator.buildAliasScopes(*S);
1570 
1571     Region *R = &S->getRegion();
1572 
1573     simplifyRegion(R, DT, LI, RI);
1574 
1575     BasicBlock *EnteringBB = R->getEnteringBlock();
1576 
1577     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
1578 
1579     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
1580                                Prog);
1581 
1582     // Only build the run-time condition and parameters _after_ having
1583     // introduced the conditional branch. This is important as the conditional
1584     // branch will guard the original scop from new induction variables that
1585     // the SCEVExpander may introduce while code generating the parameters and
1586     // which may introduce scalar dependences that prevent us from correctly
1587     // code generating this scop.
1588     BasicBlock *StartBlock =
1589         executeScopConditionally(*S, this, Builder.getTrue());
1590 
1591     // TODO: Handle LICM
1592     // TODO: Verify run-time checks
1593     auto SplitBlock = StartBlock->getSinglePredecessor();
1594     Builder.SetInsertPoint(SplitBlock->getTerminator());
1595     NodeBuilder.addParameters(S->getContext());
1596     Builder.SetInsertPoint(&*StartBlock->begin());
1597 
1598     NodeBuilder.initializeAfterRTH();
1599     NodeBuilder.create(Root);
1600     NodeBuilder.finalize();
1601   }
1602 
1603   bool runOnScop(Scop &CurrentScop) override {
1604     S = &CurrentScop;
1605     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1606     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1607     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1608     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
1609     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1610 
1611     // We currently do not support scops with invariant loads.
1612     if (S->hasInvariantAccesses())
1613       return false;
1614 
1615     auto PPCGScop = createPPCGScop();
1616     auto PPCGProg = createPPCGProg(PPCGScop);
1617     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
1618 
1619     if (PPCGGen->tree)
1620       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
1621 
1622     freeOptions(PPCGScop);
1623     freePPCGGen(PPCGGen);
1624     gpu_prog_free(PPCGProg);
1625     ppcg_scop_free(PPCGScop);
1626 
1627     return true;
1628   }
1629 
1630   void printScop(raw_ostream &, Scop &) const override {}
1631 
1632   void getAnalysisUsage(AnalysisUsage &AU) const override {
1633     AU.addRequired<DominatorTreeWrapperPass>();
1634     AU.addRequired<RegionInfoPass>();
1635     AU.addRequired<ScalarEvolutionWrapperPass>();
1636     AU.addRequired<ScopDetection>();
1637     AU.addRequired<ScopInfoRegionPass>();
1638     AU.addRequired<LoopInfoWrapperPass>();
1639 
1640     AU.addPreserved<AAResultsWrapperPass>();
1641     AU.addPreserved<BasicAAWrapperPass>();
1642     AU.addPreserved<LoopInfoWrapperPass>();
1643     AU.addPreserved<DominatorTreeWrapperPass>();
1644     AU.addPreserved<GlobalsAAWrapperPass>();
1645     AU.addPreserved<PostDominatorTreeWrapperPass>();
1646     AU.addPreserved<ScopDetection>();
1647     AU.addPreserved<ScalarEvolutionWrapperPass>();
1648     AU.addPreserved<SCEVAAWrapperPass>();
1649 
1650     // FIXME: We do not yet add regions for the newly generated code to the
1651     //        region tree.
1652     AU.addPreserved<RegionInfoPass>();
1653     AU.addPreserved<ScopInfoRegionPass>();
1654   }
1655 };
1656 }
1657 
1658 char PPCGCodeGeneration::ID = 1;
1659 
1660 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
1661 
1662 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
1663                       "Polly - Apply PPCG translation to SCOP", false, false)
1664 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
1665 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
1666 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
1667 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
1668 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
1669 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1670 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
1671                     "Polly - Apply PPCG translation to SCOP", false, false)
1672