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/IslAst.h"
16 #include "polly/CodeGen/IslNodeBuilder.h"
17 #include "polly/CodeGen/Utils.h"
18 #include "polly/DependenceInfo.h"
19 #include "polly/LinkAllPasses.h"
20 #include "polly/Options.h"
21 #include "polly/ScopDetection.h"
22 #include "polly/ScopInfo.h"
23 #include "polly/Support/SCEVValidator.h"
24 #include "llvm/ADT/PostOrderIterator.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/BasicAliasAnalysis.h"
27 #include "llvm/Analysis/GlobalsModRef.h"
28 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Analysis/TargetTransformInfo.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/TargetSelect.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 
39 #include "isl/union_map.h"
40 
41 extern "C" {
42 #include "ppcg/cuda.h"
43 #include "ppcg/gpu.h"
44 #include "ppcg/gpu_print.h"
45 #include "ppcg/ppcg.h"
46 #include "ppcg/schedule.h"
47 }
48 
49 #include "llvm/Support/Debug.h"
50 
51 using namespace polly;
52 using namespace llvm;
53 
54 #define DEBUG_TYPE "polly-codegen-ppcg"
55 
56 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
57                                   cl::desc("Dump the computed GPU Schedule"),
58                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
59                                   cl::cat(PollyCategory));
60 
61 static cl::opt<bool>
62     DumpCode("polly-acc-dump-code",
63              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
64              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
65 
66 static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
67                                   cl::desc("Dump the kernel LLVM-IR"),
68                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
69                                   cl::cat(PollyCategory));
70 
71 static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
72                                    cl::desc("Dump the kernel assembly code"),
73                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
74                                    cl::cat(PollyCategory));
75 
76 static cl::opt<bool> FastMath("polly-acc-fastmath",
77                               cl::desc("Allow unsafe math optimizations"),
78                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
79                               cl::cat(PollyCategory));
80 static cl::opt<bool> SharedMemory("polly-acc-use-shared",
81                                   cl::desc("Use shared memory"), cl::Hidden,
82                                   cl::init(false), cl::ZeroOrMore,
83                                   cl::cat(PollyCategory));
84 static cl::opt<bool> PrivateMemory("polly-acc-use-private",
85                                    cl::desc("Use private memory"), cl::Hidden,
86                                    cl::init(false), cl::ZeroOrMore,
87                                    cl::cat(PollyCategory));
88 
89 static cl::opt<std::string>
90     CudaVersion("polly-acc-cuda-version",
91                 cl::desc("The CUDA version to compile for"), cl::Hidden,
92                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
93 
94 static cl::opt<int>
95     MinCompute("polly-acc-mincompute",
96                cl::desc("Minimal number of compute statements to run on GPU."),
97                cl::Hidden, cl::init(10 * 512 * 512));
98 
99 /// Create the ast expressions for a ScopStmt.
100 ///
101 /// This function is a callback for to generate the ast expressions for each
102 /// of the scheduled ScopStmts.
103 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
104     void *StmtT, isl_ast_build *Build,
105     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
106                                        isl_id *Id, void *User),
107     void *UserIndex,
108     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
109     void *UserExpr) {
110 
111   ScopStmt *Stmt = (ScopStmt *)StmtT;
112 
113   isl_ctx *Ctx;
114 
115   if (!Stmt || !Build)
116     return NULL;
117 
118   Ctx = isl_ast_build_get_ctx(Build);
119   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
120 
121   for (MemoryAccess *Acc : *Stmt) {
122     isl_map *AddrFunc = Acc->getAddressFunction();
123     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
124     isl_id *RefId = Acc->getId();
125     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
126     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
127     MPA = isl_multi_pw_aff_coalesce(MPA);
128     MPA = FunctionIndex(MPA, RefId, UserIndex);
129     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
130     Access = FunctionExpr(Access, RefId, UserExpr);
131     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
132   }
133 
134   return RefToExpr;
135 }
136 
137 /// Generate code for a GPU specific isl AST.
138 ///
139 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
140 /// generates code for general-prupose AST nodes, with special functionality
141 /// for generating GPU specific user nodes.
142 ///
143 /// @see GPUNodeBuilder::createUser
144 class GPUNodeBuilder : public IslNodeBuilder {
145 public:
146   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
147                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
148                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
149                  gpu_prog *Prog)
150       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S, StartBlock),
151         Prog(Prog) {
152     getExprBuilder().setIDToSAI(&IDToSAI);
153   }
154 
155   /// Create after-run-time-check initialization code.
156   void initializeAfterRTH();
157 
158   /// Finalize the generated scop.
159   virtual void finalize();
160 
161   /// Track if the full build process was successful.
162   ///
163   /// This value is set to false, if throughout the build process an error
164   /// occurred which prevents us from generating valid GPU code.
165   bool BuildSuccessful = true;
166 
167   /// The maximal number of loops surrounding a sequential kernel.
168   unsigned DeepestSequential = 0;
169 
170   /// The maximal number of loops surrounding a parallel kernel.
171   unsigned DeepestParallel = 0;
172 
173 private:
174   /// A vector of array base pointers for which a new ScopArrayInfo was created.
175   ///
176   /// This vector is used to delete the ScopArrayInfo when it is not needed any
177   /// more.
178   std::vector<Value *> LocalArrays;
179 
180   /// A map from ScopArrays to their corresponding device allocations.
181   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
182 
183   /// The current GPU context.
184   Value *GPUContext;
185 
186   /// The set of isl_ids allocated in the kernel
187   std::vector<isl_id *> KernelIds;
188 
189   /// A module containing GPU code.
190   ///
191   /// This pointer is only set in case we are currently generating GPU code.
192   std::unique_ptr<Module> GPUModule;
193 
194   /// The GPU program we generate code for.
195   gpu_prog *Prog;
196 
197   /// Class to free isl_ids.
198   class IslIdDeleter {
199   public:
200     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
201   };
202 
203   /// A set containing all isl_ids allocated in a GPU kernel.
204   ///
205   /// By releasing this set all isl_ids will be freed.
206   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
207 
208   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
209 
210   /// Create code for user-defined AST nodes.
211   ///
212   /// These AST nodes can be of type:
213   ///
214   ///   - ScopStmt:      A computational statement (TODO)
215   ///   - Kernel:        A GPU kernel call (TODO)
216   ///   - Data-Transfer: A GPU <-> CPU data-transfer
217   ///   - In-kernel synchronization
218   ///   - In-kernel memory copy statement
219   ///
220   /// @param UserStmt The ast node to generate code for.
221   virtual void createUser(__isl_take isl_ast_node *UserStmt);
222 
223   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
224 
225   /// Create code for a data transfer statement
226   ///
227   /// @param TransferStmt The data transfer statement.
228   /// @param Direction The direction in which to transfer data.
229   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
230                           enum DataDirection Direction);
231 
232   /// Find llvm::Values referenced in GPU kernel.
233   ///
234   /// @param Kernel The kernel to scan for llvm::Values
235   ///
236   /// @returns A set of values referenced by the kernel.
237   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
238 
239   /// Compute the sizes of the execution grid for a given kernel.
240   ///
241   /// @param Kernel The kernel to compute grid sizes for.
242   ///
243   /// @returns A tuple with grid sizes for X and Y dimension
244   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
245 
246   /// Compute the sizes of the thread blocks for a given kernel.
247   ///
248   /// @param Kernel The kernel to compute thread block sizes for.
249   ///
250   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
251   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
252 
253   /// Create kernel launch parameters.
254   ///
255   /// @param Kernel        The kernel to create parameters for.
256   /// @param F             The kernel function that has been created.
257   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
258   ///
259   /// @returns A stack allocated array with pointers to the parameter
260   ///          values that are passed to the kernel.
261   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
262                                 SetVector<Value *> SubtreeValues);
263 
264   /// Create declarations for kernel variable.
265   ///
266   /// This includes shared memory declarations.
267   ///
268   /// @param Kernel        The kernel definition to create variables for.
269   /// @param FN            The function into which to generate the variables.
270   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
271 
272   /// Add CUDA annotations to module.
273   ///
274   /// Add a set of CUDA annotations that declares the maximal block dimensions
275   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
276   /// PTX compiler to bound the number of allocated registers to ensure the
277   /// resulting kernel is known to run with up to as many block dimensions
278   /// as specified here.
279   ///
280   /// @param M         The module to add the annotations to.
281   /// @param BlockDimX The size of block dimension X.
282   /// @param BlockDimY The size of block dimension Y.
283   /// @param BlockDimZ The size of block dimension Z.
284   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
285                           Value *BlockDimZ);
286 
287   /// Create GPU kernel.
288   ///
289   /// Code generate the kernel described by @p KernelStmt.
290   ///
291   /// @param KernelStmt The ast node to generate kernel code for.
292   void createKernel(__isl_take isl_ast_node *KernelStmt);
293 
294   /// Generate code that computes the size of an array.
295   ///
296   /// @param Array The array for which to compute a size.
297   Value *getArraySize(gpu_array_info *Array);
298 
299   /// Generate code to compute the minimal offset at which an array is accessed.
300   ///
301   /// The offset of an array is the minimal array location accessed in a scop.
302   ///
303   /// Example:
304   ///
305   ///   for (long i = 0; i < 100; i++)
306   ///     A[i + 42] += ...
307   ///
308   ///   getArrayOffset(A) results in 42.
309   ///
310   /// @param Array The array for which to compute the offset.
311   /// @returns An llvm::Value that contains the offset of the array.
312   Value *getArrayOffset(gpu_array_info *Array);
313 
314   /// Prepare the kernel arguments for kernel code generation
315   ///
316   /// @param Kernel The kernel to generate code for.
317   /// @param FN     The function created for the kernel.
318   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
319 
320   /// Create kernel function.
321   ///
322   /// Create a kernel function located in a newly created module that can serve
323   /// as target for device code generation. Set the Builder to point to the
324   /// start block of this newly created function.
325   ///
326   /// @param Kernel The kernel to generate code for.
327   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
328   void createKernelFunction(ppcg_kernel *Kernel,
329                             SetVector<Value *> &SubtreeValues);
330 
331   /// Create the declaration of a kernel function.
332   ///
333   /// The kernel function takes as arguments:
334   ///
335   ///   - One i8 pointer for each external array reference used in the kernel.
336   ///   - Host iterators
337   ///   - Parameters
338   ///   - Other LLVM Value references (TODO)
339   ///
340   /// @param Kernel The kernel to generate the function declaration for.
341   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
342   ///
343   /// @returns The newly declared function.
344   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
345                                      SetVector<Value *> &SubtreeValues);
346 
347   /// Insert intrinsic functions to obtain thread and block ids.
348   ///
349   /// @param The kernel to generate the intrinsic functions for.
350   void insertKernelIntrinsics(ppcg_kernel *Kernel);
351 
352   /// Create a global-to-shared or shared-to-global copy statement.
353   ///
354   /// @param CopyStmt The copy statement to generate code for
355   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
356 
357   /// Create code for a ScopStmt called in @p Expr.
358   ///
359   /// @param Expr The expression containing the call.
360   /// @param KernelStmt The kernel statement referenced in the call.
361   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
362 
363   /// Create an in-kernel synchronization call.
364   void createKernelSync();
365 
366   /// Create a PTX assembly string for the current GPU kernel.
367   ///
368   /// @returns A string containing the corresponding PTX assembly code.
369   std::string createKernelASM();
370 
371   /// Remove references from the dominator tree to the kernel function @p F.
372   ///
373   /// @param F The function to remove references to.
374   void clearDominators(Function *F);
375 
376   /// Remove references from scalar evolution to the kernel function @p F.
377   ///
378   /// @param F The function to remove references to.
379   void clearScalarEvolution(Function *F);
380 
381   /// Remove references from loop info to the kernel function @p F.
382   ///
383   /// @param F The function to remove references to.
384   void clearLoops(Function *F);
385 
386   /// Finalize the generation of the kernel function.
387   ///
388   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
389   /// dump its IR to stderr.
390   ///
391   /// @returns The Assembly string of the kernel.
392   std::string finalizeKernelFunction();
393 
394   /// Finalize the generation of the kernel arguments.
395   ///
396   /// This function ensures that not-read-only scalars used in a kernel are
397   /// stored back to the global memory location they ared backed up with before
398   /// the kernel terminates.
399   ///
400   /// @params Kernel The kernel to finalize kernel arguments for.
401   void finalizeKernelArguments(ppcg_kernel *Kernel);
402 
403   /// Create code that allocates memory to store arrays on device.
404   void allocateDeviceArrays();
405 
406   /// Free all allocated device arrays.
407   void freeDeviceArrays();
408 
409   /// Create a call to initialize the GPU context.
410   ///
411   /// @returns A pointer to the newly initialized context.
412   Value *createCallInitContext();
413 
414   /// Create a call to get the device pointer for a kernel allocation.
415   ///
416   /// @param Allocation The Polly GPU allocation
417   ///
418   /// @returns The device parameter corresponding to this allocation.
419   Value *createCallGetDevicePtr(Value *Allocation);
420 
421   /// Create a call to free the GPU context.
422   ///
423   /// @param Context A pointer to an initialized GPU context.
424   void createCallFreeContext(Value *Context);
425 
426   /// Create a call to allocate memory on the device.
427   ///
428   /// @param Size The size of memory to allocate
429   ///
430   /// @returns A pointer that identifies this allocation.
431   Value *createCallAllocateMemoryForDevice(Value *Size);
432 
433   /// Create a call to free a device array.
434   ///
435   /// @param Array The device array to free.
436   void createCallFreeDeviceMemory(Value *Array);
437 
438   /// Create a call to copy data from host to device.
439   ///
440   /// @param HostPtr A pointer to the host data that should be copied.
441   /// @param DevicePtr A device pointer specifying the location to copy to.
442   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
443                                       Value *Size);
444 
445   /// Create a call to copy data from device to host.
446   ///
447   /// @param DevicePtr A pointer to the device data that should be copied.
448   /// @param HostPtr A host pointer specifying the location to copy to.
449   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
450                                       Value *Size);
451 
452   /// Create a call to get a kernel from an assembly string.
453   ///
454   /// @param Buffer The string describing the kernel.
455   /// @param Entry  The name of the kernel function to call.
456   ///
457   /// @returns A pointer to a kernel object
458   Value *createCallGetKernel(Value *Buffer, Value *Entry);
459 
460   /// Create a call to free a GPU kernel.
461   ///
462   /// @param GPUKernel THe kernel to free.
463   void createCallFreeKernel(Value *GPUKernel);
464 
465   /// Create a call to launch a GPU kernel.
466   ///
467   /// @param GPUKernel  The kernel to launch.
468   /// @param GridDimX   The size of the first grid dimension.
469   /// @param GridDimY   The size of the second grid dimension.
470   /// @param GridBlockX The size of the first block dimension.
471   /// @param GridBlockY The size of the second block dimension.
472   /// @param GridBlockZ The size of the third block dimension.
473   /// @param Paramters  A pointer to an array that contains itself pointers to
474   ///                   the parameter values passed for each kernel argument.
475   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
476                               Value *GridDimY, Value *BlockDimX,
477                               Value *BlockDimY, Value *BlockDimZ,
478                               Value *Parameters);
479 };
480 
481 void GPUNodeBuilder::initializeAfterRTH() {
482   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
483                                  &*Builder.GetInsertPoint(), &DT, &LI);
484   NewBB->setName("polly.acc.initialize");
485   Builder.SetInsertPoint(&NewBB->front());
486 
487   GPUContext = createCallInitContext();
488   allocateDeviceArrays();
489 }
490 
491 void GPUNodeBuilder::finalize() {
492   freeDeviceArrays();
493   createCallFreeContext(GPUContext);
494   IslNodeBuilder::finalize();
495 }
496 
497 void GPUNodeBuilder::allocateDeviceArrays() {
498   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
499 
500   for (int i = 0; i < Prog->n_array; ++i) {
501     gpu_array_info *Array = &Prog->array[i];
502     auto *ScopArray = (ScopArrayInfo *)Array->user;
503     std::string DevArrayName("p_dev_array_");
504     DevArrayName.append(Array->name);
505 
506     Value *ArraySize = getArraySize(Array);
507     Value *Offset = getArrayOffset(Array);
508     if (Offset)
509       ArraySize = Builder.CreateSub(
510           ArraySize,
511           Builder.CreateMul(Offset,
512                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
513     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
514     DevArray->setName(DevArrayName);
515     DeviceAllocations[ScopArray] = DevArray;
516   }
517 
518   isl_ast_build_free(Build);
519 }
520 
521 void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
522                                         Value *BlockDimY, Value *BlockDimZ) {
523   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
524 
525   for (auto &F : *M) {
526     if (F.getCallingConv() != CallingConv::PTX_Kernel)
527       continue;
528 
529     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
530 
531     Metadata *Elements[] = {
532         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
533         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
534         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
535         ValueAsMetadata::get(V[2]),
536     };
537     MDNode *Node = MDNode::get(M->getContext(), Elements);
538     AnnotationNode->addOperand(Node);
539   }
540 }
541 
542 void GPUNodeBuilder::freeDeviceArrays() {
543   for (auto &Array : DeviceAllocations)
544     createCallFreeDeviceMemory(Array.second);
545 }
546 
547 Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
548   const char *Name = "polly_getKernel";
549   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
550   Function *F = M->getFunction(Name);
551 
552   // If F is not available, declare it.
553   if (!F) {
554     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
555     std::vector<Type *> Args;
556     Args.push_back(Builder.getInt8PtrTy());
557     Args.push_back(Builder.getInt8PtrTy());
558     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
559     F = Function::Create(Ty, Linkage, Name, M);
560   }
561 
562   return Builder.CreateCall(F, {Buffer, Entry});
563 }
564 
565 Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
566   const char *Name = "polly_getDevicePtr";
567   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
568   Function *F = M->getFunction(Name);
569 
570   // If F is not available, declare it.
571   if (!F) {
572     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
573     std::vector<Type *> Args;
574     Args.push_back(Builder.getInt8PtrTy());
575     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
576     F = Function::Create(Ty, Linkage, Name, M);
577   }
578 
579   return Builder.CreateCall(F, {Allocation});
580 }
581 
582 void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
583                                             Value *GridDimY, Value *BlockDimX,
584                                             Value *BlockDimY, Value *BlockDimZ,
585                                             Value *Parameters) {
586   const char *Name = "polly_launchKernel";
587   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
588   Function *F = M->getFunction(Name);
589 
590   // If F is not available, declare it.
591   if (!F) {
592     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
593     std::vector<Type *> Args;
594     Args.push_back(Builder.getInt8PtrTy());
595     Args.push_back(Builder.getInt32Ty());
596     Args.push_back(Builder.getInt32Ty());
597     Args.push_back(Builder.getInt32Ty());
598     Args.push_back(Builder.getInt32Ty());
599     Args.push_back(Builder.getInt32Ty());
600     Args.push_back(Builder.getInt8PtrTy());
601     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
602     F = Function::Create(Ty, Linkage, Name, M);
603   }
604 
605   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
606                          BlockDimZ, Parameters});
607 }
608 
609 void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
610   const char *Name = "polly_freeKernel";
611   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
612   Function *F = M->getFunction(Name);
613 
614   // If F is not available, declare it.
615   if (!F) {
616     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
617     std::vector<Type *> Args;
618     Args.push_back(Builder.getInt8PtrTy());
619     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
620     F = Function::Create(Ty, Linkage, Name, M);
621   }
622 
623   Builder.CreateCall(F, {GPUKernel});
624 }
625 
626 void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
627   const char *Name = "polly_freeDeviceMemory";
628   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
629   Function *F = M->getFunction(Name);
630 
631   // If F is not available, declare it.
632   if (!F) {
633     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
634     std::vector<Type *> Args;
635     Args.push_back(Builder.getInt8PtrTy());
636     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
637     F = Function::Create(Ty, Linkage, Name, M);
638   }
639 
640   Builder.CreateCall(F, {Array});
641 }
642 
643 Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
644   const char *Name = "polly_allocateMemoryForDevice";
645   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
646   Function *F = M->getFunction(Name);
647 
648   // If F is not available, declare it.
649   if (!F) {
650     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
651     std::vector<Type *> Args;
652     Args.push_back(Builder.getInt64Ty());
653     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
654     F = Function::Create(Ty, Linkage, Name, M);
655   }
656 
657   return Builder.CreateCall(F, {Size});
658 }
659 
660 void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
661                                                     Value *DeviceData,
662                                                     Value *Size) {
663   const char *Name = "polly_copyFromHostToDevice";
664   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
665   Function *F = M->getFunction(Name);
666 
667   // If F is not available, declare it.
668   if (!F) {
669     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
670     std::vector<Type *> Args;
671     Args.push_back(Builder.getInt8PtrTy());
672     Args.push_back(Builder.getInt8PtrTy());
673     Args.push_back(Builder.getInt64Ty());
674     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
675     F = Function::Create(Ty, Linkage, Name, M);
676   }
677 
678   Builder.CreateCall(F, {HostData, DeviceData, Size});
679 }
680 
681 void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
682                                                     Value *HostData,
683                                                     Value *Size) {
684   const char *Name = "polly_copyFromDeviceToHost";
685   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
686   Function *F = M->getFunction(Name);
687 
688   // If F is not available, declare it.
689   if (!F) {
690     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
691     std::vector<Type *> Args;
692     Args.push_back(Builder.getInt8PtrTy());
693     Args.push_back(Builder.getInt8PtrTy());
694     Args.push_back(Builder.getInt64Ty());
695     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
696     F = Function::Create(Ty, Linkage, Name, M);
697   }
698 
699   Builder.CreateCall(F, {DeviceData, HostData, Size});
700 }
701 
702 Value *GPUNodeBuilder::createCallInitContext() {
703   const char *Name = "polly_initContext";
704   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
705   Function *F = M->getFunction(Name);
706 
707   // If F is not available, declare it.
708   if (!F) {
709     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
710     std::vector<Type *> Args;
711     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
712     F = Function::Create(Ty, Linkage, Name, M);
713   }
714 
715   return Builder.CreateCall(F, {});
716 }
717 
718 void GPUNodeBuilder::createCallFreeContext(Value *Context) {
719   const char *Name = "polly_freeContext";
720   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
721   Function *F = M->getFunction(Name);
722 
723   // If F is not available, declare it.
724   if (!F) {
725     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
726     std::vector<Type *> Args;
727     Args.push_back(Builder.getInt8PtrTy());
728     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
729     F = Function::Create(Ty, Linkage, Name, M);
730   }
731 
732   Builder.CreateCall(F, {Context});
733 }
734 
735 /// Check if one string is a prefix of another.
736 ///
737 /// @param String The string in which to look for the prefix.
738 /// @param Prefix The prefix to look for.
739 static bool isPrefix(std::string String, std::string Prefix) {
740   return String.find(Prefix) == 0;
741 }
742 
743 Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
744   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
745   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
746 
747   if (!gpu_array_is_scalar(Array)) {
748     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
749     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
750 
751     for (unsigned int i = 1; i < Array->n_index; i++) {
752       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
753       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
754       Res = isl_ast_expr_mul(Res, Expr);
755     }
756 
757     Value *NumElements = ExprBuilder.create(Res);
758     if (NumElements->getType() != ArraySize->getType())
759       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
760     ArraySize = Builder.CreateMul(ArraySize, NumElements);
761   }
762   isl_ast_build_free(Build);
763   return ArraySize;
764 }
765 
766 Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
767   if (gpu_array_is_scalar(Array))
768     return nullptr;
769 
770   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
771 
772   isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent));
773 
774   isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min));
775 
776   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++)
777     ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0);
778 
779   if (isl_set_is_subset(Min, ZeroSet)) {
780     isl_set_free(Min);
781     isl_set_free(ZeroSet);
782     isl_ast_build_free(Build);
783     return nullptr;
784   }
785   isl_set_free(ZeroSet);
786 
787   isl_ast_expr *Result =
788       isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0));
789 
790   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) {
791     if (i > 0) {
792       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]);
793       isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
794       Result = isl_ast_expr_mul(Result, BExpr);
795     }
796     isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i);
797     isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin);
798     Result = isl_ast_expr_add(Result, MExpr);
799   }
800 
801   Value *ResultValue = ExprBuilder.create(Result);
802   isl_set_free(Min);
803   isl_ast_build_free(Build);
804 
805   return ResultValue;
806 }
807 
808 void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
809                                         enum DataDirection Direction) {
810   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
811   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
812   isl_id *Id = isl_ast_expr_get_id(Arg);
813   auto Array = (gpu_array_info *)isl_id_get_user(Id);
814   auto ScopArray = (ScopArrayInfo *)(Array->user);
815 
816   Value *Size = getArraySize(Array);
817   Value *Offset = getArrayOffset(Array);
818   Value *DevPtr = DeviceAllocations[ScopArray];
819 
820   Value *HostPtr;
821 
822   if (gpu_array_is_scalar(Array))
823     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
824   else
825     HostPtr = ScopArray->getBasePtr();
826 
827   if (Offset) {
828     HostPtr = Builder.CreatePointerCast(
829         HostPtr, ScopArray->getElementType()->getPointerTo());
830     HostPtr = Builder.CreateGEP(HostPtr, Offset);
831   }
832 
833   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
834 
835   if (Offset) {
836     Size = Builder.CreateSub(
837         Size, Builder.CreateMul(
838                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
839   }
840 
841   if (Direction == HOST_TO_DEVICE)
842     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
843   else
844     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
845 
846   isl_id_free(Id);
847   isl_ast_expr_free(Arg);
848   isl_ast_expr_free(Expr);
849   isl_ast_node_free(TransferStmt);
850 }
851 
852 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
853   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
854   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
855   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
856   isl_id_free(Id);
857   isl_ast_expr_free(StmtExpr);
858 
859   const char *Str = isl_id_get_name(Id);
860   if (!strcmp(Str, "kernel")) {
861     createKernel(UserStmt);
862     isl_ast_expr_free(Expr);
863     return;
864   }
865 
866   if (isPrefix(Str, "to_device")) {
867     createDataTransfer(UserStmt, HOST_TO_DEVICE);
868     isl_ast_expr_free(Expr);
869     return;
870   }
871 
872   if (isPrefix(Str, "from_device")) {
873     createDataTransfer(UserStmt, DEVICE_TO_HOST);
874     isl_ast_expr_free(Expr);
875     return;
876   }
877 
878   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
879   struct ppcg_kernel_stmt *KernelStmt =
880       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
881   isl_id_free(Anno);
882 
883   switch (KernelStmt->type) {
884   case ppcg_kernel_domain:
885     createScopStmt(Expr, KernelStmt);
886     isl_ast_node_free(UserStmt);
887     return;
888   case ppcg_kernel_copy:
889     createKernelCopy(KernelStmt);
890     isl_ast_expr_free(Expr);
891     isl_ast_node_free(UserStmt);
892     return;
893   case ppcg_kernel_sync:
894     createKernelSync();
895     isl_ast_expr_free(Expr);
896     isl_ast_node_free(UserStmt);
897     return;
898   }
899 
900   isl_ast_expr_free(Expr);
901   isl_ast_node_free(UserStmt);
902   return;
903 }
904 void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
905   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
906   LocalIndex = isl_ast_expr_address_of(LocalIndex);
907   Value *LocalAddr = ExprBuilder.create(LocalIndex);
908   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
909   Index = isl_ast_expr_address_of(Index);
910   Value *GlobalAddr = ExprBuilder.create(Index);
911 
912   if (KernelStmt->u.c.read) {
913     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
914     Builder.CreateStore(Load, LocalAddr);
915   } else {
916     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
917     Builder.CreateStore(Load, GlobalAddr);
918   }
919 }
920 
921 void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
922                                     ppcg_kernel_stmt *KernelStmt) {
923   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
924   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
925 
926   LoopToScevMapT LTS;
927   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
928 
929   createSubstitutions(Expr, Stmt, LTS);
930 
931   if (Stmt->isBlockStmt())
932     BlockGen.copyStmt(*Stmt, LTS, Indexes);
933   else
934     RegionGen.copyStmt(*Stmt, LTS, Indexes);
935 }
936 
937 void GPUNodeBuilder::createKernelSync() {
938   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
939   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
940   Builder.CreateCall(Sync, {});
941 }
942 
943 /// Collect llvm::Values referenced from @p Node
944 ///
945 /// This function only applies to isl_ast_nodes that are user_nodes referring
946 /// to a ScopStmt. All other node types are ignore.
947 ///
948 /// @param Node The node to collect references for.
949 /// @param User A user pointer used as storage for the data that is collected.
950 ///
951 /// @returns isl_bool_true if data could be collected successfully.
952 isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
953   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
954     return isl_bool_true;
955 
956   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
957   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
958   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
959   const char *Str = isl_id_get_name(Id);
960   isl_id_free(Id);
961   isl_ast_expr_free(StmtExpr);
962   isl_ast_expr_free(Expr);
963 
964   if (!isPrefix(Str, "Stmt"))
965     return isl_bool_true;
966 
967   Id = isl_ast_node_get_annotation(Node);
968   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
969   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
970   isl_id_free(Id);
971 
972   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
973 
974   return isl_bool_true;
975 }
976 
977 SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
978   SetVector<Value *> SubtreeValues;
979   SetVector<const SCEV *> SCEVs;
980   SetVector<const Loop *> Loops;
981   SubtreeReferences References = {
982       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
983 
984   for (const auto &I : IDToValue)
985     SubtreeValues.insert(I.second);
986 
987   isl_ast_node_foreach_descendant_top_down(
988       Kernel->tree, collectReferencesInGPUStmt, &References);
989 
990   for (const SCEV *Expr : SCEVs)
991     findValues(Expr, SE, SubtreeValues);
992 
993   for (auto &SAI : S.arrays())
994     SubtreeValues.remove(SAI->getBasePtr());
995 
996   isl_space *Space = S.getParamSpace();
997   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
998     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
999     assert(IDToValue.count(Id));
1000     Value *Val = IDToValue[Id];
1001     SubtreeValues.remove(Val);
1002     isl_id_free(Id);
1003   }
1004   isl_space_free(Space);
1005 
1006   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1007     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1008     assert(IDToValue.count(Id));
1009     Value *Val = IDToValue[Id];
1010     SubtreeValues.remove(Val);
1011     isl_id_free(Id);
1012   }
1013 
1014   return SubtreeValues;
1015 }
1016 
1017 void GPUNodeBuilder::clearDominators(Function *F) {
1018   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
1019   std::vector<BasicBlock *> Nodes;
1020   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
1021     Nodes.push_back(I->getBlock());
1022 
1023   for (BasicBlock *BB : Nodes)
1024     DT.eraseNode(BB);
1025 }
1026 
1027 void GPUNodeBuilder::clearScalarEvolution(Function *F) {
1028   for (BasicBlock &BB : *F) {
1029     Loop *L = LI.getLoopFor(&BB);
1030     if (L)
1031       SE.forgetLoop(L);
1032   }
1033 }
1034 
1035 void GPUNodeBuilder::clearLoops(Function *F) {
1036   for (BasicBlock &BB : *F) {
1037     Loop *L = LI.getLoopFor(&BB);
1038     if (L)
1039       SE.forgetLoop(L);
1040     LI.removeBlock(&BB);
1041   }
1042 }
1043 
1044 std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
1045   std::vector<Value *> Sizes;
1046   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
1047 
1048   for (long i = 0; i < Kernel->n_grid; i++) {
1049     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
1050     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
1051     Value *Res = ExprBuilder.create(GridSize);
1052     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
1053     Sizes.push_back(Res);
1054   }
1055   isl_ast_build_free(Context);
1056 
1057   for (long i = Kernel->n_grid; i < 3; i++)
1058     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
1059 
1060   return std::make_tuple(Sizes[0], Sizes[1]);
1061 }
1062 
1063 std::tuple<Value *, Value *, Value *>
1064 GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
1065   std::vector<Value *> Sizes;
1066 
1067   for (long i = 0; i < Kernel->n_block; i++) {
1068     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
1069     Sizes.push_back(Res);
1070   }
1071 
1072   for (long i = Kernel->n_block; i < 3; i++)
1073     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
1074 
1075   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
1076 }
1077 
1078 Value *
1079 GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
1080                                        SetVector<Value *> SubtreeValues) {
1081   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
1082                                  std::distance(F->arg_begin(), F->arg_end()));
1083 
1084   BasicBlock *EntryBlock =
1085       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
1086   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
1087   Instruction *Parameters =
1088       new AllocaInst(ArrayTy, Launch + "_params", EntryBlock->getTerminator());
1089 
1090   int Index = 0;
1091   for (long i = 0; i < Prog->n_array; i++) {
1092     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1093       continue;
1094 
1095     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1096     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1097 
1098     Value *DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
1099     DevArray = createCallGetDevicePtr(DevArray);
1100 
1101     Value *Offset = getArrayOffset(&Prog->array[i]);
1102 
1103     if (Offset) {
1104       DevArray = Builder.CreatePointerCast(
1105           DevArray, SAI->getElementType()->getPointerTo());
1106       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1107       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1108     }
1109     Value *Slot = Builder.CreateGEP(
1110         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1111 
1112     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1113       Value *ValPtr = BlockGen.getOrCreateAlloca(SAI);
1114       Value *ValPtrCast =
1115           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1116       Builder.CreateStore(ValPtrCast, Slot);
1117     } else {
1118       Instruction *Param = new AllocaInst(
1119           Builder.getInt8PtrTy(), Launch + "_param_" + std::to_string(Index),
1120           EntryBlock->getTerminator());
1121       Builder.CreateStore(DevArray, Param);
1122       Value *ParamTyped =
1123           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1124       Builder.CreateStore(ParamTyped, Slot);
1125     }
1126     Index++;
1127   }
1128 
1129   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1130 
1131   for (long i = 0; i < NumHostIters; i++) {
1132     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1133     Value *Val = IDToValue[Id];
1134     isl_id_free(Id);
1135     Instruction *Param = new AllocaInst(
1136         Val->getType(), Launch + "_param_" + std::to_string(Index),
1137         EntryBlock->getTerminator());
1138     Builder.CreateStore(Val, Param);
1139     Value *Slot = Builder.CreateGEP(
1140         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1141     Value *ParamTyped =
1142         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1143     Builder.CreateStore(ParamTyped, Slot);
1144     Index++;
1145   }
1146 
1147   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1148 
1149   for (long i = 0; i < NumVars; i++) {
1150     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1151     Value *Val = IDToValue[Id];
1152     isl_id_free(Id);
1153     Instruction *Param = new AllocaInst(
1154         Val->getType(), Launch + "_param_" + std::to_string(Index),
1155         EntryBlock->getTerminator());
1156     Builder.CreateStore(Val, Param);
1157     Value *Slot = Builder.CreateGEP(
1158         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1159     Value *ParamTyped =
1160         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1161     Builder.CreateStore(ParamTyped, Slot);
1162     Index++;
1163   }
1164 
1165   for (auto Val : SubtreeValues) {
1166     Instruction *Param = new AllocaInst(
1167         Val->getType(), Launch + "_param_" + std::to_string(Index),
1168         EntryBlock->getTerminator());
1169     Builder.CreateStore(Val, Param);
1170     Value *Slot = Builder.CreateGEP(
1171         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1172     Value *ParamTyped =
1173         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1174     Builder.CreateStore(ParamTyped, Slot);
1175     Index++;
1176   }
1177 
1178   auto Location = EntryBlock->getTerminator();
1179   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
1180                          Launch + "_params_i8ptr", Location);
1181 }
1182 
1183 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
1184   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
1185   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
1186   isl_id_free(Id);
1187   isl_ast_node_free(KernelStmt);
1188 
1189   if (Kernel->n_grid > 1)
1190     DeepestParallel =
1191         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1192   else
1193     DeepestSequential =
1194         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1195 
1196   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1197   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1198 
1199   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1200 
1201   assert(Kernel->tree && "Device AST of kernel node is empty");
1202 
1203   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1204   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1205   ValueMapT HostValueMap = ValueMap;
1206   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1207   ScalarMap.clear();
1208 
1209   SetVector<const Loop *> Loops;
1210 
1211   // Create for all loops we depend on values that contain the current loop
1212   // iteration. These values are necessary to generate code for SCEVs that
1213   // depend on such loops. As a result we need to pass them to the subfunction.
1214   for (const Loop *L : Loops) {
1215     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1216                                             SE.getUnknown(Builder.getInt64(1)),
1217                                             L, SCEV::FlagAnyWrap);
1218     Value *V = generateSCEV(OuterLIV);
1219     OutsideLoopIterations[L] = SE.getUnknown(V);
1220     SubtreeValues.insert(V);
1221   }
1222 
1223   createKernelFunction(Kernel, SubtreeValues);
1224 
1225   create(isl_ast_node_copy(Kernel->tree));
1226 
1227   finalizeKernelArguments(Kernel);
1228   Function *F = Builder.GetInsertBlock()->getParent();
1229   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
1230   clearDominators(F);
1231   clearScalarEvolution(F);
1232   clearLoops(F);
1233 
1234   IDToValue = HostIDs;
1235 
1236   ValueMap = std::move(HostValueMap);
1237   ScalarMap = std::move(HostScalarMap);
1238   EscapeMap.clear();
1239   IDToSAI.clear();
1240   Annotator.resetAlternativeAliasBases();
1241   for (auto &BasePtr : LocalArrays)
1242     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
1243   LocalArrays.clear();
1244 
1245   std::string ASMString = finalizeKernelFunction();
1246   Builder.SetInsertPoint(&HostInsertPoint);
1247   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
1248 
1249   std::string Name = "kernel_" + std::to_string(Kernel->id);
1250   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
1251   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
1252   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
1253 
1254   Value *GridDimX, *GridDimY;
1255   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
1256 
1257   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
1258                          BlockDimZ, Parameters);
1259   createCallFreeKernel(GPUKernel);
1260 
1261   for (auto Id : KernelIds)
1262     isl_id_free(Id);
1263 
1264   KernelIds.clear();
1265 }
1266 
1267 /// Compute the DataLayout string for the NVPTX backend.
1268 ///
1269 /// @param is64Bit Are we looking for a 64 bit architecture?
1270 static std::string computeNVPTXDataLayout(bool is64Bit) {
1271   std::string Ret = "e";
1272 
1273   if (!is64Bit)
1274     Ret += "-p:32:32";
1275 
1276   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
1277 
1278   return Ret;
1279 }
1280 
1281 Function *
1282 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1283                                          SetVector<Value *> &SubtreeValues) {
1284   std::vector<Type *> Args;
1285   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
1286 
1287   for (long i = 0; i < Prog->n_array; i++) {
1288     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1289       continue;
1290 
1291     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1292       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1293       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1294       Args.push_back(SAI->getElementType());
1295     } else {
1296       Args.push_back(Builder.getInt8PtrTy());
1297     }
1298   }
1299 
1300   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1301 
1302   for (long i = 0; i < NumHostIters; i++)
1303     Args.push_back(Builder.getInt64Ty());
1304 
1305   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1306 
1307   for (long i = 0; i < NumVars; i++) {
1308     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1309     Value *Val = IDToValue[Id];
1310     isl_id_free(Id);
1311     Args.push_back(Val->getType());
1312   }
1313 
1314   for (auto *V : SubtreeValues)
1315     Args.push_back(V->getType());
1316 
1317   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
1318   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
1319                               GPUModule.get());
1320   FN->setCallingConv(CallingConv::PTX_Kernel);
1321 
1322   auto Arg = FN->arg_begin();
1323   for (long i = 0; i < Kernel->n_array; i++) {
1324     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1325       continue;
1326 
1327     Arg->setName(Kernel->array[i].array->name);
1328 
1329     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1330     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1331     Type *EleTy = SAI->getElementType();
1332     Value *Val = &*Arg;
1333     SmallVector<const SCEV *, 4> Sizes;
1334     isl_ast_build *Build =
1335         isl_ast_build_from_context(isl_set_copy(Prog->context));
1336     Sizes.push_back(nullptr);
1337     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1338       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1339           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1340       auto V = ExprBuilder.create(DimSize);
1341       Sizes.push_back(SE.getSCEV(V));
1342     }
1343     const ScopArrayInfo *SAIRep =
1344         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
1345     LocalArrays.push_back(Val);
1346 
1347     isl_ast_build_free(Build);
1348     KernelIds.push_back(Id);
1349     IDToSAI[Id] = SAIRep;
1350     Arg++;
1351   }
1352 
1353   for (long i = 0; i < NumHostIters; i++) {
1354     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1355     Arg->setName(isl_id_get_name(Id));
1356     IDToValue[Id] = &*Arg;
1357     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1358     Arg++;
1359   }
1360 
1361   for (long i = 0; i < NumVars; i++) {
1362     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1363     Arg->setName(isl_id_get_name(Id));
1364     Value *Val = IDToValue[Id];
1365     ValueMap[Val] = &*Arg;
1366     IDToValue[Id] = &*Arg;
1367     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1368     Arg++;
1369   }
1370 
1371   for (auto *V : SubtreeValues) {
1372     Arg->setName(V->getName());
1373     ValueMap[V] = &*Arg;
1374     Arg++;
1375   }
1376 
1377   return FN;
1378 }
1379 
1380 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1381   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1382                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1383 
1384   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1385                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1386                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1387 
1388   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1389     std::string Name = isl_id_get_name(Id);
1390     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1391     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1392     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1393     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1394     IDToValue[Id] = Val;
1395     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1396   };
1397 
1398   for (int i = 0; i < Kernel->n_grid; ++i) {
1399     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1400     addId(Id, IntrinsicsBID[i]);
1401   }
1402 
1403   for (int i = 0; i < Kernel->n_block; ++i) {
1404     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1405     addId(Id, IntrinsicsTID[i]);
1406   }
1407 }
1408 
1409 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
1410   auto Arg = FN->arg_begin();
1411   for (long i = 0; i < Kernel->n_array; i++) {
1412     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1413       continue;
1414 
1415     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1416     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1417     isl_id_free(Id);
1418 
1419     if (SAI->getNumberOfDimensions() > 0) {
1420       Arg++;
1421       continue;
1422     }
1423 
1424     Value *Val = &*Arg;
1425 
1426     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
1427       Type *TypePtr = SAI->getElementType()->getPointerTo();
1428       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1429       Val = Builder.CreateLoad(TypedArgPtr);
1430     }
1431 
1432     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
1433     Builder.CreateStore(Val, Alloca);
1434 
1435     Arg++;
1436   }
1437 }
1438 
1439 void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
1440   auto *FN = Builder.GetInsertBlock()->getParent();
1441   auto Arg = FN->arg_begin();
1442 
1443   bool StoredScalar = false;
1444   for (long i = 0; i < Kernel->n_array; i++) {
1445     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1446       continue;
1447 
1448     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1449     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1450     isl_id_free(Id);
1451 
1452     if (SAI->getNumberOfDimensions() > 0) {
1453       Arg++;
1454       continue;
1455     }
1456 
1457     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1458       Arg++;
1459       continue;
1460     }
1461 
1462     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
1463     Value *ArgPtr = &*Arg;
1464     Type *TypePtr = SAI->getElementType()->getPointerTo();
1465     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
1466     Value *Val = Builder.CreateLoad(Alloca);
1467     Builder.CreateStore(Val, TypedArgPtr);
1468     StoredScalar = true;
1469 
1470     Arg++;
1471   }
1472 
1473   if (StoredScalar)
1474     /// In case more than one thread contains scalar stores, the generated
1475     /// code might be incorrect, if we only store at the end of the kernel.
1476     /// To support this case we need to store these scalars back at each
1477     /// memory store or at least before each kernel barrier.
1478     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
1479       BuildSuccessful = 0;
1480 }
1481 
1482 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1483   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1484 
1485   for (int i = 0; i < Kernel->n_var; ++i) {
1486     struct ppcg_kernel_var &Var = Kernel->var[i];
1487     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1488     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1489 
1490     Type *ArrayTy = EleTy;
1491     SmallVector<const SCEV *, 4> Sizes;
1492 
1493     Sizes.push_back(nullptr);
1494     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1495       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1496       long Bound = isl_val_get_num_si(Val);
1497       isl_val_free(Val);
1498       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1499     }
1500 
1501     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1502       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1503       long Bound = isl_val_get_num_si(Val);
1504       isl_val_free(Val);
1505       ArrayTy = ArrayType::get(ArrayTy, Bound);
1506     }
1507 
1508     const ScopArrayInfo *SAI;
1509     Value *Allocation;
1510     if (Var.type == ppcg_access_shared) {
1511       auto GlobalVar = new GlobalVariable(
1512           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1513           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1514       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1515       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1516 
1517       Allocation = GlobalVar;
1518     } else if (Var.type == ppcg_access_private) {
1519       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1520     } else {
1521       llvm_unreachable("unknown variable type");
1522     }
1523     SAI =
1524         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
1525     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1526     IDToValue[Id] = Allocation;
1527     LocalArrays.push_back(Allocation);
1528     KernelIds.push_back(Id);
1529     IDToSAI[Id] = SAI;
1530   }
1531 }
1532 
1533 void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1534                                           SetVector<Value *> &SubtreeValues) {
1535 
1536   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
1537   GPUModule.reset(new Module(Identifier, Builder.getContext()));
1538   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
1539   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
1540 
1541   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
1542 
1543   BasicBlock *PrevBlock = Builder.GetInsertBlock();
1544   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
1545 
1546   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1547   DT.addNewBlock(EntryBlock, PrevBlock);
1548 
1549   Builder.SetInsertPoint(EntryBlock);
1550   Builder.CreateRetVoid();
1551   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1552 
1553   ScopDetection::markFunctionAsInvalid(FN);
1554 
1555   prepareKernelArguments(Kernel, FN);
1556   createKernelVariables(Kernel, FN);
1557   insertKernelIntrinsics(Kernel);
1558 }
1559 
1560 std::string GPUNodeBuilder::createKernelASM() {
1561   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
1562   std::string ErrMsg;
1563   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
1564 
1565   if (!GPUTarget) {
1566     errs() << ErrMsg << "\n";
1567     return "";
1568   }
1569 
1570   TargetOptions Options;
1571   Options.UnsafeFPMath = FastMath;
1572   std::unique_ptr<TargetMachine> TargetM(
1573       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
1574                                      Options, Optional<Reloc::Model>()));
1575 
1576   SmallString<0> ASMString;
1577   raw_svector_ostream ASMStream(ASMString);
1578   llvm::legacy::PassManager PM;
1579 
1580   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
1581 
1582   if (TargetM->addPassesToEmitFile(
1583           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
1584     errs() << "The target does not support generation of this file type!\n";
1585     return "";
1586   }
1587 
1588   PM.run(*GPUModule);
1589 
1590   return ASMStream.str();
1591 }
1592 
1593 std::string GPUNodeBuilder::finalizeKernelFunction() {
1594   if (verifyModule(*GPUModule)) {
1595     BuildSuccessful = false;
1596     return "";
1597   }
1598 
1599   if (DumpKernelIR)
1600     outs() << *GPUModule << "\n";
1601 
1602   // Optimize module.
1603   llvm::legacy::PassManager OptPasses;
1604   PassManagerBuilder PassBuilder;
1605   PassBuilder.OptLevel = 3;
1606   PassBuilder.SizeLevel = 0;
1607   PassBuilder.populateModulePassManager(OptPasses);
1608   OptPasses.run(*GPUModule);
1609 
1610   std::string Assembly = createKernelASM();
1611 
1612   if (DumpKernelASM)
1613     outs() << Assembly << "\n";
1614 
1615   GPUModule.release();
1616   KernelIDs.clear();
1617 
1618   return Assembly;
1619 }
1620 
1621 namespace {
1622 class PPCGCodeGeneration : public ScopPass {
1623 public:
1624   static char ID;
1625 
1626   /// The scop that is currently processed.
1627   Scop *S;
1628 
1629   LoopInfo *LI;
1630   DominatorTree *DT;
1631   ScalarEvolution *SE;
1632   const DataLayout *DL;
1633   RegionInfo *RI;
1634 
1635   PPCGCodeGeneration() : ScopPass(ID) {}
1636 
1637   /// Construct compilation options for PPCG.
1638   ///
1639   /// @returns The compilation options.
1640   ppcg_options *createPPCGOptions() {
1641     auto DebugOptions =
1642         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1643     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1644 
1645     DebugOptions->dump_schedule_constraints = false;
1646     DebugOptions->dump_schedule = false;
1647     DebugOptions->dump_final_schedule = false;
1648     DebugOptions->dump_sizes = false;
1649     DebugOptions->verbose = false;
1650 
1651     Options->debug = DebugOptions;
1652 
1653     Options->reschedule = true;
1654     Options->scale_tile_loops = false;
1655     Options->wrap = false;
1656 
1657     Options->non_negative_parameters = false;
1658     Options->ctx = nullptr;
1659     Options->sizes = nullptr;
1660 
1661     Options->tile_size = 32;
1662 
1663     Options->use_private_memory = PrivateMemory;
1664     Options->use_shared_memory = SharedMemory;
1665     Options->max_shared_memory = 48 * 1024;
1666 
1667     Options->target = PPCG_TARGET_CUDA;
1668     Options->openmp = false;
1669     Options->linearize_device_arrays = true;
1670     Options->live_range_reordering = false;
1671 
1672     Options->opencl_compiler_options = nullptr;
1673     Options->opencl_use_gpu = false;
1674     Options->opencl_n_include_file = 0;
1675     Options->opencl_include_files = nullptr;
1676     Options->opencl_print_kernel_types = false;
1677     Options->opencl_embed_kernel_code = false;
1678 
1679     Options->save_schedule_file = nullptr;
1680     Options->load_schedule_file = nullptr;
1681 
1682     return Options;
1683   }
1684 
1685   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1686   ///
1687   /// Instead of a normal access of the form:
1688   ///
1689   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1690   ///
1691   /// a tagged access has the form
1692   ///
1693   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1694   ///
1695   /// where 'id' is an additional space that references the memory access that
1696   /// triggered the access.
1697   ///
1698   /// @param AccessTy The type of the memory accesses to collect.
1699   ///
1700   /// @return The relation describing all tagged memory accesses.
1701   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1702     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1703 
1704     for (auto &Stmt : *S)
1705       for (auto &Acc : Stmt)
1706         if (Acc->getType() == AccessTy) {
1707           isl_map *Relation = Acc->getAccessRelation();
1708           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1709 
1710           isl_space *Space = isl_map_get_space(Relation);
1711           Space = isl_space_range(Space);
1712           Space = isl_space_from_range(Space);
1713           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1714           isl_map *Universe = isl_map_universe(Space);
1715           Relation = isl_map_domain_product(Relation, Universe);
1716           Accesses = isl_union_map_add_map(Accesses, Relation);
1717         }
1718 
1719     return Accesses;
1720   }
1721 
1722   /// Get the set of all read accesses, tagged with the access id.
1723   ///
1724   /// @see getTaggedAccesses
1725   isl_union_map *getTaggedReads() {
1726     return getTaggedAccesses(MemoryAccess::READ);
1727   }
1728 
1729   /// Get the set of all may (and must) accesses, tagged with the access id.
1730   ///
1731   /// @see getTaggedAccesses
1732   isl_union_map *getTaggedMayWrites() {
1733     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1734                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1735   }
1736 
1737   /// Get the set of all must accesses, tagged with the access id.
1738   ///
1739   /// @see getTaggedAccesses
1740   isl_union_map *getTaggedMustWrites() {
1741     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1742   }
1743 
1744   /// Collect parameter and array names as isl_ids.
1745   ///
1746   /// To reason about the different parameters and arrays used, ppcg requires
1747   /// a list of all isl_ids in use. As PPCG traditionally performs
1748   /// source-to-source compilation each of these isl_ids is mapped to the
1749   /// expression that represents it. As we do not have a corresponding
1750   /// expression in Polly, we just map each id to a 'zero' expression to match
1751   /// the data format that ppcg expects.
1752   ///
1753   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1754   __isl_give isl_id_to_ast_expr *getNames() {
1755     auto *Names = isl_id_to_ast_expr_alloc(
1756         S->getIslCtx(),
1757         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1758     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1759     auto *Space = S->getParamSpace();
1760 
1761     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1762       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1763       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1764     }
1765 
1766     for (auto &Array : S->arrays()) {
1767       auto Id = Array->getBasePtrId();
1768       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1769     }
1770 
1771     isl_space_free(Space);
1772     isl_ast_expr_free(Zero);
1773 
1774     return Names;
1775   }
1776 
1777   /// Create a new PPCG scop from the current scop.
1778   ///
1779   /// The PPCG scop is initialized with data from the current polly::Scop. From
1780   /// this initial data, the data-dependences in the PPCG scop are initialized.
1781   /// We do not use Polly's dependence analysis for now, to ensure we match
1782   /// the PPCG default behaviour more closely.
1783   ///
1784   /// @returns A new ppcg scop.
1785   ppcg_scop *createPPCGScop() {
1786     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1787 
1788     PPCGScop->options = createPPCGOptions();
1789 
1790     PPCGScop->start = 0;
1791     PPCGScop->end = 0;
1792 
1793     PPCGScop->context = S->getContext();
1794     PPCGScop->domain = S->getDomains();
1795     PPCGScop->call = nullptr;
1796     PPCGScop->tagged_reads = getTaggedReads();
1797     PPCGScop->reads = S->getReads();
1798     PPCGScop->live_in = nullptr;
1799     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1800     PPCGScop->may_writes = S->getWrites();
1801     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1802     PPCGScop->must_writes = S->getMustWrites();
1803     PPCGScop->live_out = nullptr;
1804     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1805     PPCGScop->tagger = nullptr;
1806 
1807     PPCGScop->independence = nullptr;
1808     PPCGScop->dep_flow = nullptr;
1809     PPCGScop->tagged_dep_flow = nullptr;
1810     PPCGScop->dep_false = nullptr;
1811     PPCGScop->dep_forced = nullptr;
1812     PPCGScop->dep_order = nullptr;
1813     PPCGScop->tagged_dep_order = nullptr;
1814 
1815     PPCGScop->schedule = S->getScheduleTree();
1816     PPCGScop->names = getNames();
1817 
1818     PPCGScop->pet = nullptr;
1819 
1820     compute_tagger(PPCGScop);
1821     compute_dependences(PPCGScop);
1822 
1823     return PPCGScop;
1824   }
1825 
1826   /// Collect the array acesses in a statement.
1827   ///
1828   /// @param Stmt The statement for which to collect the accesses.
1829   ///
1830   /// @returns A list of array accesses.
1831   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
1832     gpu_stmt_access *Accesses = nullptr;
1833 
1834     for (MemoryAccess *Acc : Stmt) {
1835       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
1836       Access->read = Acc->isRead();
1837       Access->write = Acc->isWrite();
1838       Access->access = Acc->getAccessRelation();
1839       isl_space *Space = isl_map_get_space(Access->access);
1840       Space = isl_space_range(Space);
1841       Space = isl_space_from_range(Space);
1842       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1843       isl_map *Universe = isl_map_universe(Space);
1844       Access->tagged_access =
1845           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1846       Access->exact_write = !Acc->isMayWrite();
1847       Access->ref_id = Acc->getId();
1848       Access->next = Accesses;
1849       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
1850       Accesses = Access;
1851     }
1852 
1853     return Accesses;
1854   }
1855 
1856   /// Collect the list of GPU statements.
1857   ///
1858   /// Each statement has an id, a pointer to the underlying data structure,
1859   /// as well as a list with all memory accesses.
1860   ///
1861   /// TODO: Initialize the list of memory accesses.
1862   ///
1863   /// @returns A linked-list of statements.
1864   gpu_stmt *getStatements() {
1865     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
1866                                        std::distance(S->begin(), S->end()));
1867 
1868     int i = 0;
1869     for (auto &Stmt : *S) {
1870       gpu_stmt *GPUStmt = &Stmts[i];
1871 
1872       GPUStmt->id = Stmt.getDomainId();
1873 
1874       // We use the pet stmt pointer to keep track of the Polly statements.
1875       GPUStmt->stmt = (pet_stmt *)&Stmt;
1876       GPUStmt->accesses = getStmtAccesses(Stmt);
1877       i++;
1878     }
1879 
1880     return Stmts;
1881   }
1882 
1883   /// Derive the extent of an array.
1884   ///
1885   /// The extent of an array is the set of elements that are within the
1886   /// accessed array. For the inner dimensions, the extent constraints are
1887   /// 0 and the size of the corresponding array dimension. For the first
1888   /// (outermost) dimension, the extent constraints are the minimal and maximal
1889   /// subscript value for the first dimension.
1890   ///
1891   /// @param Array The array to derive the extent for.
1892   ///
1893   /// @returns An isl_set describing the extent of the array.
1894   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1895     unsigned NumDims = Array->getNumberOfDimensions();
1896     isl_union_map *Accesses = S->getAccesses();
1897     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1898     Accesses = isl_union_map_detect_equalities(Accesses);
1899     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1900     AccessUSet = isl_union_set_coalesce(AccessUSet);
1901     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
1902     AccessUSet = isl_union_set_coalesce(AccessUSet);
1903 
1904     if (isl_union_set_is_empty(AccessUSet)) {
1905       isl_union_set_free(AccessUSet);
1906       return isl_set_empty(Array->getSpace());
1907     }
1908 
1909     if (Array->getNumberOfDimensions() == 0) {
1910       isl_union_set_free(AccessUSet);
1911       return isl_set_universe(Array->getSpace());
1912     }
1913 
1914     isl_set *AccessSet =
1915         isl_union_set_extract_set(AccessUSet, Array->getSpace());
1916 
1917     isl_union_set_free(AccessUSet);
1918     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
1919 
1920     isl_pw_aff *Val =
1921         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
1922 
1923     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
1924     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
1925     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
1926                                    isl_pw_aff_dim(Val, isl_dim_in));
1927     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
1928                                    isl_pw_aff_dim(Val, isl_dim_in));
1929     OuterMin =
1930         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
1931     OuterMax =
1932         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
1933 
1934     isl_set *Extent = isl_set_universe(Array->getSpace());
1935 
1936     Extent = isl_set_intersect(
1937         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
1938     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
1939 
1940     for (unsigned i = 1; i < NumDims; ++i)
1941       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
1942 
1943     for (unsigned i = 1; i < NumDims; ++i) {
1944       isl_pw_aff *PwAff =
1945           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
1946       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
1947           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
1948       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
1949                                   isl_pw_aff_dim(Val, isl_dim_in));
1950       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
1951                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
1952       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
1953       Extent = isl_set_intersect(Set, Extent);
1954     }
1955 
1956     return Extent;
1957   }
1958 
1959   /// Derive the bounds of an array.
1960   ///
1961   /// For the first dimension we derive the bound of the array from the extent
1962   /// of this dimension. For inner dimensions we obtain their size directly from
1963   /// ScopArrayInfo.
1964   ///
1965   /// @param PPCGArray The array to compute bounds for.
1966   /// @param Array The polly array from which to take the information.
1967   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
1968     if (PPCGArray.n_index > 0) {
1969       if (isl_set_is_empty(PPCGArray.extent)) {
1970         isl_set *Dom = isl_set_copy(PPCGArray.extent);
1971         isl_local_space *LS = isl_local_space_from_space(
1972             isl_space_params(isl_set_get_space(Dom)));
1973         isl_set_free(Dom);
1974         isl_aff *Zero = isl_aff_zero_on_domain(LS);
1975         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
1976       } else {
1977         isl_set *Dom = isl_set_copy(PPCGArray.extent);
1978         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
1979         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
1980         isl_set_free(Dom);
1981         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
1982         isl_local_space *LS =
1983             isl_local_space_from_space(isl_set_get_space(Dom));
1984         isl_aff *One = isl_aff_zero_on_domain(LS);
1985         One = isl_aff_add_constant_si(One, 1);
1986         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
1987         Bound = isl_pw_aff_gist(Bound, S->getContext());
1988         PPCGArray.bound[0] = Bound;
1989       }
1990     }
1991 
1992     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
1993       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
1994       auto LS = isl_pw_aff_get_domain_space(Bound);
1995       auto Aff = isl_multi_aff_zero(LS);
1996       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
1997       PPCGArray.bound[i] = Bound;
1998     }
1999   }
2000 
2001   /// Create the arrays for @p PPCGProg.
2002   ///
2003   /// @param PPCGProg The program to compute the arrays for.
2004   void createArrays(gpu_prog *PPCGProg) {
2005     int i = 0;
2006     for (auto &Array : S->arrays()) {
2007       std::string TypeName;
2008       raw_string_ostream OS(TypeName);
2009 
2010       OS << *Array->getElementType();
2011       TypeName = OS.str();
2012 
2013       gpu_array_info &PPCGArray = PPCGProg->array[i];
2014 
2015       PPCGArray.space = Array->getSpace();
2016       PPCGArray.type = strdup(TypeName.c_str());
2017       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
2018       PPCGArray.name = strdup(Array->getName().c_str());
2019       PPCGArray.extent = nullptr;
2020       PPCGArray.n_index = Array->getNumberOfDimensions();
2021       PPCGArray.bound =
2022           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
2023       PPCGArray.extent = getExtent(Array);
2024       PPCGArray.n_ref = 0;
2025       PPCGArray.refs = nullptr;
2026       PPCGArray.accessed = true;
2027       PPCGArray.read_only_scalar =
2028           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
2029       PPCGArray.has_compound_element = false;
2030       PPCGArray.local = false;
2031       PPCGArray.declare_local = false;
2032       PPCGArray.global = false;
2033       PPCGArray.linearize = false;
2034       PPCGArray.dep_order = nullptr;
2035       PPCGArray.user = Array;
2036 
2037       setArrayBounds(PPCGArray, Array);
2038       i++;
2039 
2040       collect_references(PPCGProg, &PPCGArray);
2041     }
2042   }
2043 
2044   /// Create an identity map between the arrays in the scop.
2045   ///
2046   /// @returns An identity map between the arrays in the scop.
2047   isl_union_map *getArrayIdentity() {
2048     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
2049 
2050     for (auto &Array : S->arrays()) {
2051       isl_space *Space = Array->getSpace();
2052       Space = isl_space_map_from_set(Space);
2053       isl_map *Identity = isl_map_identity(Space);
2054       Maps = isl_union_map_add_map(Maps, Identity);
2055     }
2056 
2057     return Maps;
2058   }
2059 
2060   /// Create a default-initialized PPCG GPU program.
2061   ///
2062   /// @returns A new gpu grogram description.
2063   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2064 
2065     if (!PPCGScop)
2066       return nullptr;
2067 
2068     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2069 
2070     PPCGProg->ctx = S->getIslCtx();
2071     PPCGProg->scop = PPCGScop;
2072     PPCGProg->context = isl_set_copy(PPCGScop->context);
2073     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
2074     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
2075     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
2076     PPCGProg->tagged_must_kill =
2077         isl_union_map_copy(PPCGScop->tagged_must_kills);
2078     PPCGProg->to_inner = getArrayIdentity();
2079     PPCGProg->to_outer = getArrayIdentity();
2080     PPCGProg->any_to_outer = nullptr;
2081     PPCGProg->array_order = nullptr;
2082     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
2083     PPCGProg->stmts = getStatements();
2084     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
2085     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
2086                                        PPCGProg->n_array);
2087 
2088     createArrays(PPCGProg);
2089 
2090     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2091 
2092     return PPCGProg;
2093   }
2094 
2095   struct PrintGPUUserData {
2096     struct cuda_info *CudaInfo;
2097     struct gpu_prog *PPCGProg;
2098     std::vector<ppcg_kernel *> Kernels;
2099   };
2100 
2101   /// Print a user statement node in the host code.
2102   ///
2103   /// We use ppcg's printing facilities to print the actual statement and
2104   /// additionally build up a list of all kernels that are encountered in the
2105   /// host ast.
2106   ///
2107   /// @param P The printer to print to
2108   /// @param Options The printing options to use
2109   /// @param Node The node to print
2110   /// @param User A user pointer to carry additional data. This pointer is
2111   ///             expected to be of type PrintGPUUserData.
2112   ///
2113   /// @returns A printer to which the output has been printed.
2114   static __isl_give isl_printer *
2115   printHostUser(__isl_take isl_printer *P,
2116                 __isl_take isl_ast_print_options *Options,
2117                 __isl_take isl_ast_node *Node, void *User) {
2118     auto Data = (struct PrintGPUUserData *)User;
2119     auto Id = isl_ast_node_get_annotation(Node);
2120 
2121     if (Id) {
2122       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
2123 
2124       // If this is a user statement, format it ourselves as ppcg would
2125       // otherwise try to call pet functionality that is not available in
2126       // Polly.
2127       if (IsUser) {
2128         P = isl_printer_start_line(P);
2129         P = isl_printer_print_ast_node(P, Node);
2130         P = isl_printer_end_line(P);
2131         isl_id_free(Id);
2132         isl_ast_print_options_free(Options);
2133         return P;
2134       }
2135 
2136       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
2137       isl_id_free(Id);
2138       Data->Kernels.push_back(Kernel);
2139     }
2140 
2141     return print_host_user(P, Options, Node, User);
2142   }
2143 
2144   /// Print C code corresponding to the control flow in @p Kernel.
2145   ///
2146   /// @param Kernel The kernel to print
2147   void printKernel(ppcg_kernel *Kernel) {
2148     auto *P = isl_printer_to_str(S->getIslCtx());
2149     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
2150     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
2151     P = isl_ast_node_print(Kernel->tree, P, Options);
2152     char *String = isl_printer_get_str(P);
2153     printf("%s\n", String);
2154     free(String);
2155     isl_printer_free(P);
2156   }
2157 
2158   /// Print C code corresponding to the GPU code described by @p Tree.
2159   ///
2160   /// @param Tree An AST describing GPU code
2161   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
2162   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
2163     auto *P = isl_printer_to_str(S->getIslCtx());
2164     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
2165 
2166     PrintGPUUserData Data;
2167     Data.PPCGProg = PPCGProg;
2168 
2169     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
2170     Options =
2171         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
2172     P = isl_ast_node_print(Tree, P, Options);
2173     char *String = isl_printer_get_str(P);
2174     printf("# host\n");
2175     printf("%s\n", String);
2176     free(String);
2177     isl_printer_free(P);
2178 
2179     for (auto Kernel : Data.Kernels) {
2180       printf("# kernel%d\n", Kernel->id);
2181       printKernel(Kernel);
2182     }
2183   }
2184 
2185   // Generate a GPU program using PPCG.
2186   //
2187   // GPU mapping consists of multiple steps:
2188   //
2189   //  1) Compute new schedule for the program.
2190   //  2) Map schedule to GPU (TODO)
2191   //  3) Generate code for new schedule (TODO)
2192   //
2193   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2194   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2195   // strategy directly from this pass.
2196   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2197 
2198     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2199 
2200     PPCGGen->ctx = S->getIslCtx();
2201     PPCGGen->options = PPCGScop->options;
2202     PPCGGen->print = nullptr;
2203     PPCGGen->print_user = nullptr;
2204     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2205     PPCGGen->prog = PPCGProg;
2206     PPCGGen->tree = nullptr;
2207     PPCGGen->types.n = 0;
2208     PPCGGen->types.name = nullptr;
2209     PPCGGen->sizes = nullptr;
2210     PPCGGen->used_sizes = nullptr;
2211     PPCGGen->kernel_id = 0;
2212 
2213     // Set scheduling strategy to same strategy PPCG is using.
2214     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2215     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
2216     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2217 
2218     isl_schedule *Schedule = get_schedule(PPCGGen);
2219 
2220     int has_permutable = has_any_permutable_node(Schedule);
2221 
2222     if (!has_permutable || has_permutable < 0) {
2223       Schedule = isl_schedule_free(Schedule);
2224     } else {
2225       Schedule = map_to_device(PPCGGen, Schedule);
2226       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
2227     }
2228 
2229     if (DumpSchedule) {
2230       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2231       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2232       P = isl_printer_print_str(P, "Schedule\n");
2233       P = isl_printer_print_str(P, "========\n");
2234       if (Schedule)
2235         P = isl_printer_print_schedule(P, Schedule);
2236       else
2237         P = isl_printer_print_str(P, "No schedule found\n");
2238 
2239       printf("%s\n", isl_printer_get_str(P));
2240       isl_printer_free(P);
2241     }
2242 
2243     if (DumpCode) {
2244       printf("Code\n");
2245       printf("====\n");
2246       if (PPCGGen->tree)
2247         printGPUTree(PPCGGen->tree, PPCGProg);
2248       else
2249         printf("No code generated\n");
2250     }
2251 
2252     isl_schedule_free(Schedule);
2253 
2254     return PPCGGen;
2255   }
2256 
2257   /// Free gpu_gen structure.
2258   ///
2259   /// @param PPCGGen The ppcg_gen object to free.
2260   void freePPCGGen(gpu_gen *PPCGGen) {
2261     isl_ast_node_free(PPCGGen->tree);
2262     isl_union_map_free(PPCGGen->sizes);
2263     isl_union_map_free(PPCGGen->used_sizes);
2264     free(PPCGGen);
2265   }
2266 
2267   /// Free the options in the ppcg scop structure.
2268   ///
2269   /// ppcg is not freeing these options for us. To avoid leaks we do this
2270   /// ourselves.
2271   ///
2272   /// @param PPCGScop The scop referencing the options to free.
2273   void freeOptions(ppcg_scop *PPCGScop) {
2274     free(PPCGScop->options->debug);
2275     PPCGScop->options->debug = nullptr;
2276     free(PPCGScop->options);
2277     PPCGScop->options = nullptr;
2278   }
2279 
2280   /// Approximate the number of points in the set.
2281   ///
2282   /// This function returns an ast expression that overapproximates the number
2283   /// of points in an isl set through the rectangular hull surrounding this set.
2284   ///
2285   /// @param Set   The set to count.
2286   /// @param Build The isl ast build object to use for creating the ast
2287   ///              expression.
2288   ///
2289   /// @returns An approximation of the number of points in the set.
2290   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
2291                                              __isl_keep isl_ast_build *Build) {
2292 
2293     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
2294     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
2295 
2296     isl_space *Space = isl_set_get_space(Set);
2297     Space = isl_space_params(Space);
2298     auto *Univ = isl_set_universe(Space);
2299     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
2300 
2301     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
2302       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
2303       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
2304       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
2305       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
2306       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
2307       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
2308     }
2309 
2310     isl_set_free(Set);
2311     isl_pw_aff_free(OneAff);
2312 
2313     return Expr;
2314   }
2315 
2316   /// Approximate a number of dynamic instructions executed by a given
2317   /// statement.
2318   ///
2319   /// @param Stmt  The statement for which to compute the number of dynamic
2320   ///              instructions.
2321   /// @param Build The isl ast build object to use for creating the ast
2322   ///              expression.
2323   /// @returns An approximation of the number of dynamic instructions executed
2324   ///          by @p Stmt.
2325   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
2326                                              __isl_keep isl_ast_build *Build) {
2327     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
2328 
2329     long InstCount = 0;
2330 
2331     if (Stmt.isBlockStmt()) {
2332       auto *BB = Stmt.getBasicBlock();
2333       InstCount = std::distance(BB->begin(), BB->end());
2334     } else {
2335       auto *R = Stmt.getRegion();
2336 
2337       for (auto *BB : R->blocks()) {
2338         InstCount += std::distance(BB->begin(), BB->end());
2339       }
2340     }
2341 
2342     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
2343     auto *InstExpr = isl_ast_expr_from_val(InstVal);
2344     return isl_ast_expr_mul(InstExpr, Iterations);
2345   }
2346 
2347   /// Approximate dynamic instructions executed in scop.
2348   ///
2349   /// @param S     The scop for which to approximate dynamic instructions.
2350   /// @param Build The isl ast build object to use for creating the ast
2351   ///              expression.
2352   /// @returns An approximation of the number of dynamic instructions executed
2353   ///          in @p S.
2354   __isl_give isl_ast_expr *
2355   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
2356     isl_ast_expr *Instructions;
2357 
2358     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
2359     Instructions = isl_ast_expr_from_val(Zero);
2360 
2361     for (ScopStmt &Stmt : S) {
2362       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
2363       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
2364     }
2365     return Instructions;
2366   }
2367 
2368   /// Create a check that ensures sufficient compute in scop.
2369   ///
2370   /// @param S     The scop for which to ensure sufficient compute.
2371   /// @param Build The isl ast build object to use for creating the ast
2372   ///              expression.
2373   /// @returns An expression that evaluates to TRUE in case of sufficient
2374   ///          compute and to FALSE, otherwise.
2375   __isl_give isl_ast_expr *
2376   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
2377     auto Iterations = getNumberOfIterations(S, Build);
2378     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
2379     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
2380     return isl_ast_expr_ge(Iterations, MinComputeExpr);
2381   }
2382 
2383   /// Generate code for a given GPU AST described by @p Root.
2384   ///
2385   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
2386   /// @param Prog The GPU Program to generate code for.
2387   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
2388     ScopAnnotator Annotator;
2389     Annotator.buildAliasScopes(*S);
2390 
2391     Region *R = &S->getRegion();
2392 
2393     simplifyRegion(R, DT, LI, RI);
2394 
2395     BasicBlock *EnteringBB = R->getEnteringBlock();
2396 
2397     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
2398 
2399     // Only build the run-time condition and parameters _after_ having
2400     // introduced the conditional branch. This is important as the conditional
2401     // branch will guard the original scop from new induction variables that
2402     // the SCEVExpander may introduce while code generating the parameters and
2403     // which may introduce scalar dependences that prevent us from correctly
2404     // code generating this scop.
2405     BasicBlock *StartBlock =
2406         executeScopConditionally(*S, this, Builder.getTrue());
2407 
2408     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
2409                                StartBlock, Prog);
2410 
2411     // TODO: Handle LICM
2412     auto SplitBlock = StartBlock->getSinglePredecessor();
2413     Builder.SetInsertPoint(SplitBlock->getTerminator());
2414     NodeBuilder.addParameters(S->getContext());
2415 
2416     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
2417     isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build);
2418     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
2419     Condition = isl_ast_expr_and(Condition, SufficientCompute);
2420     isl_ast_build_free(Build);
2421 
2422     Value *RTC = NodeBuilder.createRTC(Condition);
2423     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2424 
2425     Builder.SetInsertPoint(&*StartBlock->begin());
2426 
2427     NodeBuilder.initializeAfterRTH();
2428     NodeBuilder.create(Root);
2429     NodeBuilder.finalize();
2430 
2431     /// In case a sequential kernel has more surrounding loops as any parallel
2432     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
2433     /// point in running it on a CPU.
2434     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
2435       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
2436 
2437     if (!NodeBuilder.BuildSuccessful)
2438       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
2439   }
2440 
2441   bool runOnScop(Scop &CurrentScop) override {
2442     S = &CurrentScop;
2443     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2444     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2445     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2446     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
2447     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2448 
2449     // We currently do not support scops with invariant loads.
2450     if (S->hasInvariantAccesses())
2451       return false;
2452 
2453     auto PPCGScop = createPPCGScop();
2454     auto PPCGProg = createPPCGProg(PPCGScop);
2455     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
2456 
2457     if (PPCGGen->tree)
2458       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
2459 
2460     freeOptions(PPCGScop);
2461     freePPCGGen(PPCGGen);
2462     gpu_prog_free(PPCGProg);
2463     ppcg_scop_free(PPCGScop);
2464 
2465     return true;
2466   }
2467 
2468   void printScop(raw_ostream &, Scop &) const override {}
2469 
2470   void getAnalysisUsage(AnalysisUsage &AU) const override {
2471     AU.addRequired<DominatorTreeWrapperPass>();
2472     AU.addRequired<RegionInfoPass>();
2473     AU.addRequired<ScalarEvolutionWrapperPass>();
2474     AU.addRequired<ScopDetection>();
2475     AU.addRequired<ScopInfoRegionPass>();
2476     AU.addRequired<LoopInfoWrapperPass>();
2477 
2478     AU.addPreserved<AAResultsWrapperPass>();
2479     AU.addPreserved<BasicAAWrapperPass>();
2480     AU.addPreserved<LoopInfoWrapperPass>();
2481     AU.addPreserved<DominatorTreeWrapperPass>();
2482     AU.addPreserved<GlobalsAAWrapperPass>();
2483     AU.addPreserved<ScopDetection>();
2484     AU.addPreserved<ScalarEvolutionWrapperPass>();
2485     AU.addPreserved<SCEVAAWrapperPass>();
2486 
2487     // FIXME: We do not yet add regions for the newly generated code to the
2488     //        region tree.
2489     AU.addPreserved<RegionInfoPass>();
2490     AU.addPreserved<ScopInfoRegionPass>();
2491   }
2492 };
2493 } // namespace
2494 
2495 char PPCGCodeGeneration::ID = 1;
2496 
2497 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
2498 
2499 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
2500                       "Polly - Apply PPCG translation to SCOP", false, false)
2501 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
2502 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
2503 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
2504 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
2505 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
2506 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
2507 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
2508                     "Polly - Apply PPCG translation to SCOP", false, false)
2509